Search completed in 1.16 seconds.
<tbody>: The Table Body 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. The <t
body> element, along with its cousins <thead> and <tfoot>, provide useful semantic information that can be used when rendering for either screen or printer as well as for accessibility purposes. Content categories None. Permitted content Zero or more <tr> elements. ...
...tps://github.com/mdn/interactive-examples and send us a pull request. The <t
body> element, along with its cousins <thead> and <tfoot>, provide useful semantic information that can be used when rendering for either screen or printer as well as for accessibility purposes. Content categories None. Permitted content Zero or more <tr> elements. Tag omission The <t
body> element is not a required child element for a parent <table> element to graphically render. However, it must not be present, if its parent <table> element has a <tr> element as a child. Permitted parents Within the required parent <table> element, the <t
body> element can be added after a <caption>, <colgroup>, and a <thead> element. Implicit ARIA role rowgroup Pe...
... which will put the text as close to the bottom of the cell as it is possible; middle, which will center the text in the cell; and top, which will put the text as close to the top of the cell as it is possible. As this attribute is deprecated, use the CSS vertical-align property instead. Usage notes If the table includes a <thead> block (to semantically identify header rows), the <t
body> block must come after it. If you use <t
body>, you can't also have table rows (<tr> elements) which are direct children of the <table> but not included inside the <t
body>. All non-header and non-footer rows must be inside the <t
body> if one is used. When printing a document, the <thead> and <tfoot> elements specify information that may be the same--or at least very similar--on every page of a m...
...And 11 more matches
Body.body - Web APIs
The
body read-only property of the
Body mixin is a simple getter used to expose a ReadableStream of the
body contents. Syntax var stream = response.
body; Value A ReadableStream. 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. ...
...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. ...
...e, 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. ...
...And 3 more matches
<body>: The Document Body element - HTML: Hypertext Markup Language
The HTML <
body> Element represents the content of an HTML document. There can be only one <
body> element in a document. Content categories Sectioning root. Permitted content Flow content. Tag omission The start tag may be omitted if the first thing inside it is not a space character, comment, <script> element or <style> element. The end tag may be omitted if the <
body> element has contents or has a start tag, and is not immediately followed by a comment. Permitted parents It must be the second element of an <html> element. Implicit ARIA role document Permitted ARIA roles No role permitted DOM interface HTML
BodyElement The <
body> element exposes the HTML
BodyElement interface. You can access the ...
...ody> element has contents or has a start tag, and is not immediately followed by a comment. Permitted parents It must be the second element of an <html> element. Implicit ARIA role document Permitted ARIA roles No role permitted DOM interface HTML
BodyElement The <
body> element exposes the HTML
BodyElement interface. You can access the <
body> element through the document.
body property. Attributes This element includes the global attributes. alink Color of text for hyperlinks when selected. This method is non-conforming, use CSS color property in conjunction with the :active pseudo-class instead. background URI of a image to use as a background. This method is non-conforming, use CSS background property on t...
... use CSS color property in conjunction with the :active pseudo-class instead. background URI of a image to use as a background. This method is non-conforming, use CSS background property on the element instead. bgcolor Background color for the document. This method is non-conforming, use CSS background-color property on the element instead. bottommargin The margin of the bottom of the
body. This method is non-conforming, use CSS margin-bottom property on the element instead. leftmargin The margin of the left of the
body. This method is non-conforming, use CSS margin-left property on the element instead. link Color of text for unvisited hypertext links. This method is non-conforming, use CSS color property in conjunction with the :link pseudo-class instead. onafterprint Fu...
...And 3 more matches
Body.bodyUsed - Web APIs
The
bodyUsed read-only property of the
Body mixin contains a Boolean that indicates whether the
body has been read yet. Syntax var my
BodyUsed = response.
bodyUsed; Value A Boolean. Example In our fetch request example (run fetch request live), we create a new request using the Request() constructor, then use it to fetch a JPG. When the fetch is successful, we read a Blob out of the response using blob(), put it into an object URL using URL.createObjectURL, and then set that URL as the source of an <img> element to display the image. Notice that we log response.
bodyUsed to the console once before the response.blob() call and once after. This returns false before and true afterwards, as at that point the
body has been read. HTML Content <img class="my-image" src="https://udn.realityripp...
...ll and once after. This returns false before and true afterwards, as at that point the
body has been read. HTML Content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> JS Content var myImage = document.querySelector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) { console.log(response.
bodyUsed); var res = response.blob(); console.log(response.
bodyUsed); return res; }).then(function(response) { var objectURL = URL.createObjectURL(response); myImage.src = objectURL; }); Specifications Specification Status Comment FetchThe definition of '
bodyUsed' in that specification. Living Standard ...
PerformanceResourceTiming.encodedBodySize - Web APIs
Example The following example, the value of the size properties of all "resource" type events are logged. ...
... The encoded
BodySize read-only property represents the size (in octets) received from the fetch (HTTP or cache), of the payload
body, before removing any applied content-codings. Note: This feature is available in Web Workers. If the resource is retrieved from an application cache or a local resource, it must return the size of the payload
body before removing any applied content-codings. Syntax resource.encoded
BodySize; Return value A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload
body, before removing any applied content-codings. Example The following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfEntry){ // Check for support of the PerformanceEntry.*size properties and p...
...epresenting the size (in octets) received from the fetch (HTTP or cache), of the payload
body, before removing any applied content-codings. Example The following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfEntry){ // Check for support of the PerformanceEntry.*size properties and print their values // if supported. ...
...And 8 more matches
PerformanceResourceTiming.decodedBodySize - Web APIs
The decoded
BodySize read-only property returns the size (in octets) received from the fetch (HTTP or cache) of the message
body, after removing any applied content-codings. If the resource is retrieved from an application cache or local resources, it returns the size of the payload after removing any applied content-codings. Note: This feature is available in Web Workers. Syntax resource.decoded
BodySize; Return value The size (in octets) received from the fetch (HTTP or cache) of the message
body, after removing any applied content-codings. Example The following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfEntry){ // Check for support of the *size properties and print their values // if supported. ...
...coded
BodySize; Return value The size (in octets) received from the fetch (HTTP or cache) of the message
body, after removing any applied content-codings. Example The following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfEntry){ // Check for support of the *size properties and print their values // if supported. ...
...ts) received from the fetch (HTTP or cache) of the message
body, after removing any applied content-codings. Example The following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfEntry){ // Check for support of the *size properties and print their values // if supported. ...
...And 7 more matches
HTMLBodyElement - Web APIs
The HTML
BodyElement interface provides special properties (beyond those inherited from the regular HTMLElement interface) for manipulating <
body> elements. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">EventTarget</text></a><polyline points="111,25 121,2...
...aco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLElement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#D4DDE4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#D4DDE4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#D4DDE4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/HTML
BodyElement" target="_top"><rect x="341" y="65" width="150" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="416" y="94" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTML
BodyElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits pr...
...F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="416" y="94" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTML
BodyElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, HTMLElement and from WindowEventHandlers. HTML
BodyElement.aLink Is a DOMString that represents the color of active hyperlinks. HTML
BodyElement.background Is a DOMString that represents the description of the location of the background image resource. Note that this is not an URI, though some older version of some browsers do expect it. HTML
BodyElement.bgColor Is a DOMString that represents the background color for the document. HTMLBo...
...And 5 more matches
Body - Web APIs
The
Body mixin of the Fetch API represents the
body of the response/request, allowing you to declare what its content type is and how it should be handled.
Body is implemented by both Request and Response. This provides these objects with an associated
body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence). Properties
Body.
body Read only A simple getter used to expose a ReadableStream of the
body contents.
Body.
bodyUsed Read only A Boolean that indicates whether the
body has been read. Methods
Body.arrayBuffer() Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer.
Body.blob() Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob. B...
...It returns a promise that resolves with a USVString (text). The response is always decoded using UTF-8. ...
...ves with an ArrayBuffer.
Body.blob() Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob.
Body.formData() Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object.
Body.json() Takes a Response stream and reads it to completion. ...
...And 3 more matches
DeprecationReportBody - Web APIs
A deprecation report is generated when a deprecated feature (e.g. a deprecated API method) is used on a document being observed by a ReportingObserver. Properties id A string representing the deprecated feature that generated the report, for example NavigatorGetUserMedia. This can be used to group reports by deprecated feature. anticipatedRemoval A Date object (rendered as a string) representing the date when the feature is expected to be removed from the current browser. If the date is not known, this property will return null. ...
...We loop over each report using a basic for loop, then iterate over each entry of in the repo...
...createElement('li'); let textNode = document.createTextNode('Report ' + (i + 1) + ', type: ' + reports[i].type); listItem.appendChild(textNode); let innerList = document.createElement('ul'); listItem.appendChild(innerList); list.appendChild(listItem); for (let key in reports[i].
body) { let innerListItem = document.createElement('li'); let keyValue = reports[i].
body[key]; innerListItem.textContent = key + ': ' + keyValue; innerList.appendChild(innerListItem); } } } The reports parameter contains an array of all the reports in the observer's report queue. We loop over each report using a basic for loop, then iterate over each entry of in the report's
body (a DeprecationReport
Body instance) using a for...in structure, displaying each key/val...
...ains an array of all the reports in the observer's report queue. We loop over each report using a basic for loop, then iterate over each entry of in the report's
body (a DeprecationReport
Body instance) using a for...in structure, displaying each key/value pair inside a list item. Specifications Specification Status Comment Reporting APIThe definition of 'DeprecationReport
Body' in that specification. Editor's Draft ...
JS_DecompileFunctionBody
Generate the source code representing the
body of a function, minus the function keyword, name, parameters, and braces. Syntax JSString * JS_DecompileFunction
Body(JSContext *cx, JS::Handle<JSFunction*> fun, unsigned indent); Name Type Description cx JSContext * The context in which to decompile the function. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. fun JS::Handle<JSFunction*> The function to decompile. indent unsigned If it's not JS_DONT_PRETTY_PRINT, JS_DecompileFunction returns pretty printed source code of the function. ...
...* The context in which to decompile the function. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. fun JS::Handle<JSFunction*> The function to decompile. indent unsigned If it's not JS_DONT_PRETTY_PRINT, JS_DecompileFunction returns pretty printed source code of the function. Description JS_DecompileFunction
Body generates the source code of a function's
body, minus the function keyword, name, parameters, and braces, from a function's compiled form, fun. If successful, JS_DecompileFunction
Body returns a string containing the source code of the function
body. Otherwise, it returns NULL. The source code generated by this function is accurate but unadorned and is not suitable for recompilation without provid...
...s, and braces, from a function's compiled form, fun. If successful, JS_DecompileFunction
Body returns a string containing the source code of the function
body. Otherwise, it returns NULL. The source code generated by this function is accurate but unadorned and is not suitable for recompilation without providing the function's declaration. If you decompile a function that makes a native C call, the
body of the function only contains the text "[native code]". Notes To decompile a complete function, including its
body and declaration, call JS_DecompileFunction instead. See Also MXR ID Search for JS_DecompileFunction
Body JS_DecompileScript JS_CallFunction JS_CallFunctionName JS_CallFunctionValue JS_CompileFunction JS_DecompileFunction JS_DefineFunction JS_DefineFunctions JS_GetFunctionOb...
CrashReportBody - Web APIs
A crash report is generated when a document becomes unusable due to the browser (or one of its processes) crashing. For security reasons, no details of the crash are communicated in the
body except for a general crash reason. Properties reason A string representing the reason for the crash. Current possible reasons are: oom: The browser ran out of memory. unresponsive: The page was killed due to being unresponsive. Examples Crash reports are generally only retrievable via endpoints set up using the Report-To header. ...
...eports are generally only retrievable via endpoints set up using the Report-To header. It is difficult to retrieve a crash report via a ReportingObserver, as by that point the page would have crashed! 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. If you want to receive other kinds of reports, but not crash reports, make sure to use a different name for the endpoint group that you choose for those reports. Specifications Specification Status Comment Reporting A...
... Editor's Draft ...
Document.body - Web APIs
The Document.
body property represents the <
body> or <frameset> node of the current document, or null if no such element exists. Syntax const objRef = document.
body document.
body = objRef Example // Given this HTML: <
body id="old
BodyElement"></
body> alert(document.
body.id); // "old
BodyElement" const aNew
BodyElement = document.createElement("
body"); aNew
BodyElement.id = "new
BodyElement"; document.
body = aNew
BodyElement; alert(document.
body.id); // "new
BodyElement" Notes document.
body is the element that contains the content for the document. In documents with <
body> contents, returns the <
body> element, and in frameset documents, this returns the outermost <frameset> element. ...
... aNew
BodyElement = document.createElement("
body"); aNew
BodyElement.id = "new
BodyElement"; document.
body = aNew
BodyElement; alert(document.
body.id); // "new
BodyElement" Notes document.
body is the element that contains the content for the document. In documents with <
body> contents, returns the <
body> element, and in frameset documents, this returns the outermost <frameset> element. Though the
body property is settable, setting a new
body on a document will effectively remove all the current children of the existing <
body> element. Specification Specification Status Comment HTML Living StandardThe definition of 'Document.
body' in that specification. Living Standard HTML 5.1The definition of 'Document.
body' in that specification. Recommendatio...
...ocument will effectively remove all the current children of the existing <
body> element. Specification Specification Status Comment HTML Living StandardThe definition of 'Document.
body' in that specification. Living Standard HTML 5.1The definition of 'Document.
body' in that specification. Recommendation HTML5The definition of 'Document.
body' in that specification. Recommendation ...
Body.json() - Web APIs
It returns a promise that resolves with the result of parsing the
body text as JSON. Syntax response.json().then(data => { // do something with your data }); Parameters None. Return value A Promise that resolves to a JavaScript object. This object could be anything that can be represented by JSON -- an object, an array, a string, a number... Example In our fetch json example (run fetch json live), we create a new request using the Request() constructor, then use it to fetch a .json file. ...
... Living Standard Initial definition ...
InterventionReportBody - Web APIs
An intervention report is generated when usage of a feature in a web document has been blocked by the browser for reasons such as security, performance, or user annoyance. 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. Properties id A string representing the intervention that generated the report. This can be used to group reports by deprecated feature. ...
...or null otherwise. columnNumber A number representing the column in the source file in which the intervention occurred, if known, or null otherwise. 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(firstReport.
body.columnNumber); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'InterventionReport
Body' in that specification. Editor's Draft ...
Report.body - Web APIs
The
body read-only property of the Report interface returns the
body of the report, which is a Report
Body object containing the detailed report information. Syntax let report
Body = reportInstance.
body Returns A Report
Body object containing the detailed report information. Depending on what type the Report is, the object returned will actually be a DeprecationReport
Body, InterventionReport
Body, CrashReport
Body, or FeaturePolicyViolationReport
Body. These all inherit from the base Report
Body class -- study their reference pages for more information on what the particular report
body types contain. Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { let firstReport = reports[0]; // Log the f...
...ody, or FeaturePolicyViolationReport
Body. These all inherit from the base Report
Body class -- study their reference pages for more information on what the particular report
body types contain. 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. a DeprecationReport
Body object console.log(firstReport.
body); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'Report.
body' in that specification. Editor's Draft ...
SyntaxError: missing } after function body - JavaScript
Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle. ...
...Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle. ...
Body.arrayBuffer() - Web APIs
It returns a promise that resolves with an ArrayBuffer. Syntax response.arrayBuffer().then(function(buffer) { // do something with buffer }); Parameters None. Return value A promise that resolves with an ArrayBuffer. Examples Playing music In our fetch array buffer live, we have a Play button. When pressed, the getData() function is run. Note that before playing full audio file will be downloaded. If you need to play ogg during downloading (stream it) - consider HTMLAudioElement: new Audio("music.ogg").play(); In getData() we create a new request using the Request() constructor, then use it to fetch an OGG music track. ...
Body.blob() - Web APIs
It returns a promise that resolves with a Blob. Syntax response.blob().then(function(myBlob) { // do something with myBlob }); Parameters None. Note: If the Response has a Response.type of "opaque", the resulting Blob will have a Blob.size of 0 and a Blob.type of empty string "", which renders it useless for methods like URL.createObjectURL. Return value A promise that resolves with a Blob. Example In our fetch request example (run fetch request live), we create a new request using the Request() constructor, then use it to fetch a JPG. ...
Body.formData() - Web APIs
It returns a promise that resolves with a FormData object. Note: This is mainly relevant to service workers. 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). Syntax response.formData() .then(function(formdata) { // do something with your formdata }); Parameters None. Return value A Promise that resolves with a FormData object. Example TBD. Specifications Specification Status Comment FetchThe definition of 'formData()' in that specification. ...
Body.text() - Web APIs
It returns a promise that resolves with a USVString object (text). The response is always decoded using UTF-8. Syntax response.text().then(function (text) { // do something with the text response }); Parameters None. Return value A Promise that resolves with a USVString. 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. ...
Notification.body - Web APIs
Note: This feature is available in Web Workers. The
body read-only property of the Notification interface indicates the
body string of the notification, as specified in the
body option of the Notification() constructor. Syntax var
body = Notification.
body; Value A DOMString. Examples function spawnNotification(the
Body, theIcon, theTitle) { var options = {
body: the
Body, icon: theIcon } var n = new Notification(theTitle, options); console.log(n.
body); } Specifications Specification Status Comment Notifications APIThe definition of '
body' in that specification. Living Standard Living standard ...
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
l (Core) level 1 specification. DOM level 1 includes both methods for generic document access and manipulation (DOM 1 Core) as well as methods specific to HTML documents (DOM 1 HTML). ...
...vel 1 specification. DOM level 1 includes both methods for generic document access and manipulation (DOM 1 Core) as well as methods specific to HTML documents (DOM 1 HTML). ...
...des both methods for generic document access and manipulation (DOM 1 Core) as well as methods specific to HTML documents (DOM 1 HTML). ...
...And 46 more matches
Parser API
te JavaScript source programs, such as syntax highlighters, static analyses, translators, compilers, obfuscators, etc. NOTE: This page describes SpiderMonkey-specific behavior and might be incomplete. Visit ESTree spec for a community AST standard that includes latest ECMAScript features and is backward-compatible with SpiderMonkey format. ...
...on (the position of the first character after the parsed source region): interface SourceLocation { source: string | null; start: Position; end: Position; } Each Position object consists of a line number (1-indexed) and a column number (0-indexed): interface Position { line: uint32 >= 1; column: uint32 >= 0; } Programs interface Program <: Node { type: "Program";
body: [ Statement ]; } A complete program source tree. Functions interface Function <: Node { id: Identifier | null; params: [ Pattern ]; defaults: [ Expression ]; rest: Identifier | null;
body: BlockStatement | Expression; generator: boolean; expression: boolean; } A function declaration or expression. The
body of the function may be a block statement, or in the case...
... Statements interface Statement <: Node { } Any statement. interface EmptyStatement <: Statement { type: "EmptyStatement"; } An empty statement, i.e., a solitary semicolon. ...
...And 34 more matches
Index - Web APIs
eference The AbortController() constructor creates a new AbortController object instance. 8 AbortController.abort() API, AbortController, Experimental, Fetch, Method, Reference, abort() The abort() method of the AbortController interface aborts a DOM request (e.g. a Fetch request) before it has completed. This is able to abort fetch requests, consumption of any response
Body, and streams. 9 AbortController.signal API, AbortController, Experimental, Fetch, Property, Reference, signal The signal read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort a DOM request as desired. 10 AbortSignal API, AbortSignal, DOM, Experimental, Interface, Reference T...
...ad-only property returns a Boolean that indicates whether this is a primary service. If it is not a primary service, it is a secondary service. 353 uuid API, Bluetooth, BluetoothRemoteGATTService, Experimental, Property, Reference, Web Bluetooth API, uuid The BluetoothGATTService.uuid read-only property returns a DOMString representing the UUID of this service. ...
...ty returns a Boolean that indicates whether this is a primary service. If it is not a primary service, it is a secondary service. 353 uuid API, Bluetooth, BluetoothRemoteGATTService, Experimental, Property, Reference, Web Bluetooth API, uuid The BluetoothGATTService.uuid read-only property returns a DOMString representing the UUID of this service. ...
...And 33 more matches
Examples - Archive of obsolete content
XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"> <head> <title>Problem 1 - < in XHTML</title> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" /> <script type="text/javascript"> var i = 0; while (++i > 10) { // ... ...
...ang="en-US" xml:lang="en-US"> <head> <title>Problem 1 - < in XHTML</title> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" /> <script type="text/javascript"> var i = 0; while (++i > 10) { // ... } </script> </head> <
body> <h1>Problem 1 - < in XHTML</h1> <p> This document is not well formed due to the use of a raw <. ...
... </p> <p...
...And 19 more matches
filter - CSS: Cascading Style Sheets
not accept percentage values. ...
... <feGaussianBlur in="SourceGraphic" stdDeviation="3.5"/> </filter> <image xlink:href="/files/3710/Test_Form_2.jpeg" filter="url(#svgBlur)" width="212px" height="161px"/> </svg> </div> </td> <td><img alt="Test_Form_s.jpg" id="img4" class="internal default" src="/files/3711/Test_Form_2_s.jpg" style="width: 100%;" /></td> </tr> </t
body> </table> html { height:100%; }
body { font: 14px/1.286 "Lucida Grande", "Lucida Sans Unicode", "DejaVu Sans", Lucida, Arial, Helvetica, sans-serif; color: rgb(51, 51, 51); height:100%; overflow:hidden; } #img2 { width:100%; height:auto; -webkit-filter:blur(5px); -ms-filter:blur(5px); filter:blur(5px); } table.standard-table { border: 1px solid rgb(187, 187, 187); border-...
...nt]"/> </feComponentTransfer> </filter> </svg> <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> <t
body> <tr> <td><img alt="Test_Form.jpg" id="img1" class="internal default" src="/files/3708/Test_Form.jpg" style="width: 100%;" /></td> <td><img alt="Test_Form.jpg" id="img2" class="internal default" src="/files/3708/Test_Form.jpg" style="width: 100%;" /></td> <td><div class="svg-container"><svg xmlns="http://www.w3.org/2000/svg" id="img3" viewbox="0 0 286 217" color-interpolatio...
...And 19 more matches
Timing element visibility with the Intersection Observer API - Web APIs
a></li> <li><a href="#link2">Another link</a></li> <li><a href="#link3">One more link</a></li> </ul> </nav> </aside> <main> </main> </div> This is the framework for the entire site. At the top is the site's header region, contained within a <header> block. Below that, we define the site's sidebar as a list of links within an <aside> block. Finally comes the main
body. ...
...e the site's sidebar as a list of links within an <aside> block. Finally comes the main
body. We start with an empty <main> element here. This box will be populated using script later. Styling the site with CSS With the structure of the site defined, we turn to the styling for the site. Let's look at the style for each component of the page individually. The basics We provide styles for the <
body> and <main> elements to define the site's background as well as the grid the various parts of the site will be placed in. ...
...ment here. This box will be populated using script later. Styling the site with CSS With the structure of the site defined, we turn to the styling for the site. Let's look at the style for each component of the page individually. The basics We provide styles for the <
body> and <main> elements to define the site's background as well as the grid the various parts of the site will be placed in. ...
...And 15 more matches
Drawing shapes with canvas - Web APIs
ngular area, making it fully transparent. Each of these three functions takes the same parameters. x and y specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle. width and height provide the rectangle's size. Below is the draw() function from the previous page, but now it is making use of these three functions. 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. ScreenshotLive ...
...the current point to the start. If the shape has already been closed or there's only one point in the list, this function does nothing. Note: When you call fill(), any open shapes are closed automatically, so you don't have to call closePath(). This is not the case when you call stroke(). ...
... one point in the list, this function does nothing. Note: When you call fill(), any open shapes are closed automatically, so you don't have to call closePath(). This is not the case when you call stroke(). ...
...And 14 more matches
Layout and the containing block - CSS: Cascading Style Sheets
element's containing block. The properties that work this way are box model properties and offset properties: The height, top, and bottom properties compute percentage values from the height of the containing block. The width, left, right, padding, and margin properties compute percentage values from the width of the containing block. ...
...e box model properties and offset properties: The height, top, and bottom properties compute percentage values from the height of the containing block. The width, left, right, padding, and margin properties compute percentage values from the width of the containing block. 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. ...
...age values from the width of the containing block. 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. ...
...And 14 more matches
<tr>: The Table Row element - HTML: Hypertext Markup Language
pan multiple rows or columns, no captions, and only the most basic styling to create lines around the components of the table for something resembling clarity. There are just four rows (including one header row), each with four columns (including one header column). Not even the table section elements are used; instead, the browser is allowed to determine this automatically. We'll add <thead>, <t
body>, and <tfoot> in the next example. <table> <tr> <th>Name</th> <th>ID</th> <th>Member Since</th> <th>Balance</th> </tr> <tr> <td>Margaret Nguyen</td> <td>427311</td> <td><time datetime="2010-06-03">June 3, 2010</time></td> <td>0.00</td> </tr> <tr> <td>Edvard Galinski</td> <td>533175</td> <td><time datetime="2011-01-13">January 13, 2011</time><...
...ment to add row and column groups to help make our CSS easier. HTML The HTML is where the action is here, and the action is pretty simple. ...
...Note the use of rowspan on to make the "Name", "ID", and "Balance" headers occupy two rows instead of just one, and the use of colspan to make the "Membership Dates" header cell span across two columns. Once again, we haven't touched the CSS. table { ...
...And 13 more matches
ARIA: grid role - Accessibility
The grid role is for a widget that contains one or more rows of cells. The position of each cell is significant and can be focused using keyboard input. ...
...While it does not imply a specific visual presentation, it implies a relationship among elements. Uses fall into two categories: presenting tabular information (data grids) and grouping other widgets (layout grids). Even though both data grids and layout grids emplo...
...ia-label="Sunday">S</th> <th role="columnheader" aria-label="Monday">M</th> <th role="columnheader" aria-label="Tuesday">T</th> <th role="columnheader" aria-label="Wednesday">W</th> <th role="columnheader" aria-label="Thursday">T</th> <th role="columnheader" aria-label="Friday">F</th> <th role="columnheader" aria-label="Saturday">S</th> </tr> </thead> <t
body role="rowgroup"> <tr role="row"> <th scope="row" role="rowheader">Week 35</th> <td>26</td> <td>27</td> <td>28</td> <td>29</td> <td>30</td> <td>31</td> <td role="gridcell" tabindex="-1">1</td> </tr> <tr role="row"> <th scope="row" role="rowheader">Week 36</th> <td role="gridcell" tabindex="-1"> 2 </td> <...
...And 11 more matches
Functions - JavaScript
Values can be passed to a function, and the function will return a value. In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects. ...
...year: 1998 }; /* Logs 'Honda' */ console.log(mycar.brand); /* Pass object reference to the function */ myFunc(mycar); /* * Logs 'Toyota' as the value of the 'brand' property * of the object, as changed to by the function. */ console.log(mycar.brand); The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function
body. Defining functions There are several ways to define functions: The function declaration (function statement) There is a special syntax for declaring functions (see function statement for details): function name([param[, param[, ... param]]]) { statements } name The function name. param The name of an argument to be passed to the function. statements The statements comprisi...
...ning functions There are several ways to define functions: The function declaration (function statement) There is a special syntax for declaring functions (see function statement for details): function name([param[, param[, ... param]]]) { statements } name The function name. param The name of an argument to be passed to the function. statements The statements comprising the
body of the function. The function expression (function expression) A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function e...
...And 11 more matches
Table Layout Strategy - Archive of obsolete content
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. width = "0*" Assume that you would like to give all the space to the second column in a table. ...
...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. width = "0*" Assume that you would like to give all the space to the second column in a table. ...
...orrectly due to technical constraints on wiki content. You can help by editing this page and adding screenshots or links to example pages. width = "0*" Assume that you would like to give all the space to the second column in a table. ...
...And 10 more matches
2D maze game with device orientation - Game development
game. Setting up the Canvas We will be rendering our game on Canvas, but we won't do it manually -- this will be taken care of by the framework. Let's set it up: our starting point is the index.html file with the following content. ...
...a charset="utf-8" /> <title>Cyber Orb demo</title> <style>
body { margin: 0; background: #333; } </style> <script src="src/phaser-arcade-physics.2.2.2.min.js"></script> <script src="src/Boot.js"></script> <script src="src/Preloader.js"></script> <script src="src/MainMenu.js"></script> <script src="src/Howto.js"></script> <script src="src/Game.js"></script> </head> <
body> <script> (function() { var game = new Phaser.Game(320, 480, Phaser.CANVAS, 'game'); game.state.add('Boot', Ball.Boot); game.state.add('Preloader', Ball.Preloader); game.state.add('MainMenu', Ball.MainMenu); game.state.add('Howto', Ball.Howto); game.state.add('Game', Ball.Game); game.state.start('Boot'); })(); </script> </
body> </html> So far we have a simple HTML web...
... game.state.add('Preloader', Ball.Preloader); game.state.add('MainMenu', Ball.MainMenu); game.state.add('Howto', Ball.Howto); game.state.add('Game', Ball.Game); game.state.start('Boot'); })(); </script> </
body> </html> So far we have a simple HTML website with some basic content in the <head> section: charset, title, CSS styling and the inclusion of the JavaScript files. The <
body> contains initialization of the Phaser framework and the definitions of the game states. var game = new Phaser.Game(320, 480, Phaser.CANVAS, 'game'); The line above will initialize the Phaser instance -- the arguments are the width of the Canvas, height of the Canvas, rendering method (we're using CANVAS, but there are also WEBGL and AUTO options available) and the optional ID of the DOM contai...
...And 10 more matches
JavaScript Daemons Management - Archive of obsolete content
oSpan, "parent": this }; aLetters.push(oLetter); oLetter.pos = Math.random() * 50; oLetter.elem.style.position = "relative"; this.appendChild(oSpan); } } var nMaxDist = 25, aLetters = [], sText = "Do you feel lucky, punk?", oRecompose = new Daemon(document.createElement("p"), perform, 33, 30, prepare); onload = function () { oRecompose.owner.id = "perform-me"; document.
body.appendChild(oRecompose.owner); oRecompose.play(); }; </script> <style type="text/css">
body { font-family: monospace, sans-serif; background: #DDDDDD; overflow: hidden; } #perform-me { margin: 50px; font-size: 20px; line-height: 20px; } </style> </head> <
body> <h1>new Daemon(<em>@thisObject</em>, <em>@callback</em>[, <em>@rate</em>, <em>@length</em>, <em>@init</em>, <em>@onstar...
...">unmakeLoop</button> <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(…)</title> <script type="text/javascript" src="daemon.js"></script> <script type="text/javascript" src="daemon-methods.js"></script> <script type="text/javascript"> /*\ |*| |*| :: Daemon.
...dex && this.clock + this.delta < this.interval) { clock += this.delta; return; } this.clock = 0; oLetter.elem.textContent = nIndex / nLength - oLetter.index / this.numletters >= 0 ? ...
...And 9 more matches
HTML table advanced features and accessibility - Learn web development
Prerequisites: The basics of HTML (see Introduction to HTML). Objective: To learn about more advanced HTML table features, and the accessibility of tables. ...
...article. Open up your language teacher's school timetable from the end of HTML Table Basics, or make a local copy of our timetable-fixed.html file. Add a suitable caption for the table. Save your code and open it in a browser to see what it looks like. Note: You can find our version on GitHub -- see timetable-caption.html (see it live also). Adding structure with <thead>, <tfoot>, and <t
body> As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear way to do this is by using <thead>, <tfoot>, and <t
body>, which allow you to mark up a header, footer, and
body section for the table. These elements don't make the table any more accessible to screenreader users, and don't result in any visual enhancement on their own. They are ...
...s don't make the table any more accessible to screenreader users, and don't result in any visual enhancement on their own. They are however very useful for styling and layout -- acting as useful hooks for adding CSS to your table. To give you some interesting examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table
body display on a single page and have the contents available by scrolling up and down. To use them: The <thead> element must wrap the part of the table that is the header -- this is usually the first row containing the column headings, but this is not necessarily always the case. If you are using <col>/<colgroup> element, the table header should come just below those. The <tfoot> element needs t...
...And 9 more matches
Graceful asynchronous programming with Promises - Learn web development
ctions that perform potentially lengthy tasks. To use modern web technologies you'll need to use promises. 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. In the first example, we'll use the fetch() method to fetch an image from the web, the blob() method to transform the fetch response's raw
body contents into a Blob object, and then display that blob inside an <img> element. This is very similar to the example we looked at in the first article of the series, but we'll do it a bit differently as we get you building your own promise-based code. Note: The following example will not work if you just run it directly from the file (i.e. via a file:// URL). You need to run it through a local ...
...own promise-based code. Note: The following example will not work if you just run it directly from the file (i.e. via a file:// URL). You need to run it through a local testing server, or use an online solution such as Glitch or GitHub pages. First of all, download our simple HTML template and the sample image file that we'll fetch. Add a <script> element at the bottom of the HTML <
body>. Inside your <script> element, add the following line: let promise = fetch('coffee.jpg'); This calls the fetch() method, passing it the URL of the image to fetch from the network as a parameter. This can also take an options object as an optional second parameter, but we are just using the simplest version for now. We are storing the promise object returned by fetch() inside a variab...
...block works is similar to when you add an event listener to an object using AddEventListener(). It doesn't run until an event occurs (when the promise fulfills). The most notable difference is that a .then() will only run once for each time it is used, whereas an event listener could be invoked multiple times. We immediately run the blob() method on this response to ensure that the response
body is fully downloaded, and when it is available transform it into a Blob object that we can do something with. The result of this is returned like so: response => response.blob() which is shorthand for function(response) { return response.blob(); } Unfortunately, we need to do slightly more than this. Fetch promises do not fail on 404 or 500 errors -- only on something catasrophic lik...
...And 9 more matches
HTTP Index - HTTP
HTTP, Headers, Reference, Web The Connection general header controls whether or not the network connection stays open after the current transaction finishes. If the value sent is keep-alive, the connection is persistent and not closed, allowing for subsequent requests to the same server to be done. 70 Content-Disposition HTTP, Reference, header In a multipart/form-data
body, the HTTP Content-Disposition general header is a header that can be used on the subpart of a multipart
body to give information about the field it applies to. The subpart is delimited by the boundary defined in the Content-Type header. Used on the
body itself, Content-Disposition has no effect. 71 Content-Encoding HTTP, Headers, Reference The Content-Encoding entity header i...
...It lets the client know how to decode in order to obtain the media-type referenced by the Content-Type header. ...
...nt-Type header. 72 Content-Language HTTP, Headers, Reference The Content-Language entity header is used to describe the language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language. 73 Content-Length HTTP, Headers, Reference The Content-Length entity header indicates the size of the entity-
body, in bytes, sent to the recipient. 74 Content-Location HTTP, Reference, header The Content-Location header indicates an alternate location for the returned data. The principal use is to indicate the URL of a resource transmitted as the result of content negotiation. 75 Content-Range HTTP, HTTP Header, Reference, Response Header, header The Content-Range re...
...And 9 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
ct Netscape 7. Using JavaScript Objects to Determine vendor/version As we already discussed, a common approach in the past was to use objects to classify browsers by vendor/version. A common type of detection which originally was written to support only Netscape Navigator 4 and Internet Explorer 4 might look like: // WRONG APPROACH - do not use! if (document.all) { // IE4 height = document.
body.offsetHeight; } else if (document.layers) { // NN4 height = window.innerHeight; } else { // other height = 0; } With the introduction of the W3C DOM, the standard method document.getElementById became available in Internet Explorer 5 and later in Netscape 6 (Gecko). Many web authors decided that the easiest way to add support for Netscape Gecko was to add another code fork as follows: ...
...ht; } else { // other height = 0; } With the introduction of the W3C DOM, the standard method document.getElementById became available in Internet Explorer 5 and later in Netscape 6 (Gecko). Many web authors decided that the easiest way to add support for Netscape Gecko was to add another code fork as follows: // WRONG APPROACH - do not use! if (document.all) { // IE4 height = document.
body.offsetHeight; } else if (document.layers) { // NN4 height = window.innerHeight; } else if (document.getElementById) { // They think this is Gecko // but could be wrong! height = window.innerHeight; } else { // other height = 0; } The approach is incorrect since it assumes that the only other browser besides Internet Explorer 5+ that implements document.getElementById is Gecko. Thi...
...several methods of detecting support for various features such as support for scripting and FRAMES. Use these natural abilities of HTML to extend the range of browsers your content supports. Using NOFRAMES to support NON-FRAMES capable browsers <HTML> <HEAD> <TITLE>FRAMES</TITLE> </HEAD> <FRAMESET ROWS="30,*"> <FRAME SRC="foo.html"> <FRAME SRC="bar.html"> <NOFRAMES> <
BODY> <P> This page requires frames. See <a href="noframes.html">sitemap</a>. </P> </
BODY> </NOFRAMES> </FRAMESET> </HTML> Using NOSCRIPT to support non-scriptable browsers Some browsers may not support scripting while some users may have scripting support turned off in their browser. Use the NOSCRIPT tag to provide these users with alternative unscripted versi...
...And 8 more matches
Beginner's guide to media queries - Learn web development
wser what kind of media this code is for (e.g. print, or screen). A media expression, which is a rule, or test that must be passed for the contained CSS to be applied. A set of CSS rules that will be applied if the test passes and the media type is correct. Media types The possible types of media you can specify are: all print screen speech The following media query will only set the
body to 12pt if the page is printed. It will not apply when the page is loaded in a browser. @media print {
body { font-size: 12pt; } } Note: the media type here is different from the so-called MIME type. Note: there were a number of other media types defined in the Level 3 Media Queries specification; these have been deprecated and should be avoided. Note: Media types are opt...
... feature we tend to detect most often in order to create responsive designs (and that has widespread browser support) is viewport width, and we can apply CSS if the viewport is above or below a certain width -- or an exact width -- using the min-width, max-width, and width media features. These features are used to create layouts that respond to different screen sizes. For example, to change the
body text color to red if the viewport is exactly 600 pixels, you would use the following media query. @media screen and (width: 600px) {
body { color: red; } } Open this example in the browser, or view the source. The width (and height) media features can be used as ranges, and therefore be prefixed with min- or max- to indicate that the given value is a minimum, or a maximum. For ...
... In practice, using minimum or maximum values is much more useful for responsive design so you will rarely see width or height used alone. ...
...And 8 more matches
Positioning - Learn web development
s <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. ...
...s <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. ...
...the absolutely positioned element will be contained in the initial containing block. The initial containing block has the dimensions of the viewport, and is also the block that contains the <html> element. Simply put, the absolutely positioned element will be displayed outside of the <html> element, and be positioned relative to the initial viewport. The positioned element is nested inside the <
body> in the HTML source, but in the final layout, it is 30px away from the top and left of the edge of the page. We can change the positioning context -- which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors -- to one of the elements it is nested inside (you can't position it relative to an element it is not ne...
...And 8 more matches
How CSS is structured - Learn web development
single CSS file to multiple web pages, styling all of them with the same CSS stylesheet. In the Getting started with CSS, we linked an external stylesheet to our web page. 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, ...
... inside a <style> element contained inside the HTML <head>. The HTML for an internal stylesheet might look like this: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My CSS experiment</title> <style> h1 { color: blue; background-color: yellow; border: 1px solid black; } p { color: red; } </style> </head> <
body> <h1>Hello World!</h1> <p>This is my first CSS example</p> </
body> </html> In some circumstances, internal stylesheets can be useful. For example, perhaps you're working with a content management system where you are blocked from modifying external CSS files. But for sites with more than one page, an internal stylesheet becomes a less efficient way of working. To apply uniform CSS sty...
...s the risk that even one simple styling change may require edits to multiple web pages. Inline styles Inline styles are CSS declarations that affect a single HTML element, contained within a style attribute. The implementation of an inline style in an HTML document might look like this: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My CSS experiment</title> </head> <
body> <h1 style="color: blue;background-color: yellow;border: 1px solid black;">Hello World!</h1> <p style="color:red;">This is my first CSS example</p> </
body> </html> Avoid using CSS in this way when possible. It is the opposite of a best practice. First, it is the least efficient implementation of CSS for maintenance. One styling change might require multiple edits within in a single web...
...And 8 more matches
Client-side storage - Learn web development
ide the 'forget' part of the form and show the 'remember' part forgetDiv.style.display = 'none'; rememberDiv.style.display = 'block'; } } Last but not least, we need to run the nameDisplayCheck() function every time the page is loaded. If we don't do this, then the personalized greeting will not persist across page reloads. Add the following to the bottom of your code: document.
body.onload = nameDisplayCheck; Your example is finished -- well done! All that remains now is to save your code and test your HTML page in a browser. You can see our finished version running live here. Note: There is another, slightly more complex example to explore at Using the Web Storage API. Note: In the line <script src="index.js" defer></script> of the source for our finished version, ...
...apable of, but we will give you enough to get started. Working through a note storage example Here we'll run you through an example that allows you to store notes in your browser and view and delete them whenever you like, getting you to build it up for yourself and explaining the most fundamental parts of IDB as we go along. The app looks something like this: Each note has a title and some
body text, each individually editable. The JavaScript code we'll go through below has detailed comments to help you understand what's going on. Getting started First of all, make local copies of our index.html, style.css, and index-start.js files into a new directory on your local machine. Have a look at the files. You'll see that the HTML is pretty simple: a web site with a header and footer, as...
... HTML is pretty simple: a web site with a header and footer, as well as a main content area that contains a place to display notes, and a form for entering new notes into the database. The CSS provides some simple styling to make it clearer what is going on. The JavaScript file contains five declared constants containing references to the <ul> element the notes will be displayed in, the title and
body <input> elements, the <form> itself, and the <button>. Rename your JavaScript file to index.js. You are now ready to start adding code to it. Database initial set up Now let's look at what we have to do in the first place, to actually set up a database. Below the constant declarations, add the following lines: // Create an instance of a db object for us to store the open database in ...
...And 8 more matches
Examples of web and XML development using the DOM - Web APIs
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 + "<\/li>"; } strHtml += "<\/ul>"; objOutput.innerHTML = strHtml; } </script> </head> <
body onload="init();"> <p>Image 1: no height, width, or style <img id="image1" src="https://udn.realityripple.com/samples/d2/8ba7141ed1.gif"> </p> <p>Image 2: height="50", width="500", but no style <img id="image2" src="https://udn.realityripple.com/samples/d2/8ba7141ed1.gif" height="50" width="500"> </p> <p>Image 3: no height, width, but style="height: 50px; width: 500px;" <img...
...height="50", width="500", but no style <img id="image2" src="https://udn.realityripple.com/samples/d2/8ba7141ed1.gif" height="50" width="500"> </p> <p>Image 3: no height, width, but style="height: 50px; width: 500px;" <img id="image3" src="https://udn.realityripple.com/samples/d2/8ba7141ed1.gif" style="height: 50px; width: 500px;"> </p> <div id="output"> </div> </
body> </html> Example 2: Image Attributes <!DOCTYPE html> <html lang="en"> <head> <title>Modifying an image border</title> <script> function setBorderWidth(width) { document.getElementById("img1").style.borderWidth = width + "px"; } </script> </head> <
body> <p> <img id="img1" src="image1.gif" style="border: 5px solid green;" width="100" height="100" alt="border test"> </p...
...In this case, you are manipulating the individual styles directly. ...
...And 8 more matches
Introduction to the DOM - Web APIs
he web page. Your DOM programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated DOM methods to actually create new content, as in the longer example below. This following JavaScript will display an alert when the document is loaded (and when the whole DOM is available for use): <
body onload="window.alert('Welcome to my home page!');"> Another example. This function creates a new H1 element, adds text to that element, and then adds the H1 to the tree for this document: <html> <head> <script> // run this function when the document is loaded window.onload = function() { // create a couple of elements in an otherwise empty HTML page const...
...But there are a number of different data types being passed around the API that you should be aware of. Note: Because the vast majority of code that uses the DOM revolves around manipulating HTML documents, it'...
...But there are a number of different data types being passed around the API that you should be aware of. Note: Because the vast majority of code that uses the DOM revolves around manipulating HTML documents, it's common to refer to the nodes in the DOM as elements, althoug...
...And 8 more matches
Using Fetch - Web APIs
on') .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. The simplest use of fetch() takes one argument -- the path to the resource you want to fetch -- and returns a promise containing the response (a Response object). This is just an HTTP response, not the actual JSON. To extract the JSON
body content from the response, we use the json() method (defined on the
Body mixin, which is implemented by both the Request and Response objects.) Note: The
Body mixin also has similar methods to extract other types of
body content; see the
Body section for more. Fetch requests are controlled by the connect-src directive of Content Security Policy rather than the directive of the resources it's ...
...n', // include, *same-origin, omit headers: { 'Content-Type': 'application/json' // 'Content-Type': 'application/x-www-form-urlencoded', }, redirect: 'follow', // 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 ...
...same-origin' }); To instead ensure browsers don't include credentials in the request, use credentials: 'omit'. fetch('https://example.com', { credentials: 'omit' }) Uploading JSON data Use fetch() to POST JSON-encoded data. const data = { username: 'example' }; fetch('https://example.com/profile', { method: 'POST', // or 'PUT' headers: { 'Content-Type': 'application/json', },
body: JSON.stringify(data), }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch((error) => { console.error('Error:', error); }); Uploading a file Files can be uploaded using an HTML <input type="file" /> input element, FormData() and fetch(). const formData = new FormData(); const fileField = document.querySelector('input[type="file"]'); formData.app...
...And 8 more matches
Floats - Learn web development
floating a block of text around an element. You can follow along by creating a new index.html file on your computer, filling it with a simple HTML template, and inserting the below code into it at the appropriate places. At the bottom of the section, you can see a live example of what the final code should look like. First, we'll start off with some simple HTML -- add the following to your HTML
body, removing anything that was inside there before: <h1>Simple float example</h1> <div class="box">Float</div> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. </p> <p>Sed auctor cursus massa at...
...olor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> Now apply the following CSS to your HTML (using a <style> element or a <link> to a separate .css file -- your choice):
body { width: 90%; max-width: 900px; margin: 0 auto; font: .9em/1.2 Arial, Helvetica, sans-serif } .box { width: 150px; height: 100px; border-radius: 5px; background-color: rgb(207,232,220); padding: 1em; } If you save and refresh now, you'll see something much like what you'd expect -- the box is sitting above the text, in normal flow. To float the text around it add the float and...
...t dapibus ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. ...
...And 7 more matches
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
gs in a way that is responsive without needing to add media queries to make it so. In this next example I'm combining CSS Grid and Flexbox Layouts to make a simple product listing layout. The markup for my listing is an unordered list of items. Each item contains a heading, some text of varying height, and a call to action link. ...
...ng layout. The markup for my listing is an unordered list of items. Each item contains a heading, some text of varying height, and a call to action link. ...
...tem One</h2> <div class="
body"><p>The content of this listing item goes here.</p></div> <div class="cta"><a href="">Call to action!</a></div> </li> <li> <h2>Item Two</h2> <div class="
body"><p>The content of this listing item goes here.</p></div> <div class="cta"><a href="">Call to action!</a></div> </li> <li class="wide"> <h2>Item Three</h2> <div class="
body"><p>The content of this listing item goes here.</p> <p>This one has more text than the other items.</p> <p>Quite a lot more</p> <p>Perhaps we could do something different with it?</p></div> <div class="cta"><a href="">Call to action!</a></div> </li> <li> <h2>Item Four</h2> <div class="
body"><p>The content of this listing item goes here.</p></div> <div cl...
...And 7 more matches
Interacting with page scripts - Archive of obsolete content
lo from add-on"}; unsafeWindow.clonedContentScriptObject = cloneInto(contentScriptObject, unsafeWindow); unsafeWindow.assignedContentScriptObject = contentScriptObject; The "page.html" file adds two buttons and assigns an event listener to each: one listener displays a property of the cloned object, and the other listener displays a property of the assigned object: <html> <head> </head> <
body> <input id="works" type="button" value="I will work"/> <input id="fails" type="button" value="I will not work"/> <script> var works = document.getElementById("works"); works.addEventListener("click", function() { alert(clonedContentScriptObject.greeting); }, false); var fails = document.getElementById("fails"); fails.addEventListener("click", fu...
...Clicking "I will not work" fails, and the following message is logged: Permission denied to access property 'greeting' Expose functions to page scripts The structured clone algorithm is a bit more powerful than simple JSON serialization, but not much: in particular, functions aren't cloned. T...
...cript context. Note that the function's closure will be exported, too: // content-script.js var salutation = "hello, "; function greetme(user) { return salutation + user; } exportFunction(greetme, unsafeWindow, {defineAs: "greetme"}); Finally, the "page.html" file adds a button and a page script that calls the exported function when the user pushes the button: <html> <head> </head> <
body> <input id="test" type="button" value="Click me"/> <script> var test = document.getElementById("test"); test.addEventListener("click", function() { alert(window.greetme("page script")); }, false); </script> </
body> </html> exportFunction() works by structured cloning the arguments and return value of the function from one scope to the other. Since structur...
...And 6 more matches
HTML to DOM - Archive of obsolete content
turn that HTML string into DOM for easier manipulation. However, there are potential dangers involved in injecting remote content in a privileged context in your extension, so it can be desirable to parse the HTML safely. The function below will safely parse simple HTML and return a DOM object which can be manipulated like web page elements. ...
...e simple HTML and return a DOM object which can be manipulated like web page elements. This will remove tags like <script>, <style>, <head>, <
body>, <title>, and <iframe>. It will also remove all JavaScript, including element attributes that contain JavaScript. ...
...ke web page elements. This will remove tags like <script>, <style>, <head>, <
body>, <title>, and <iframe>. It will also remove all JavaScript, including element attributes that contain JavaScript. ...
...And 6 more matches
How can we design for all types of users? - Learn web development
This article lists the most important quick-wins for universal design. ...
...mum standard (4.5:1) and should enable many visually-impaired people to read this page. Font size You can specify font size on a website either through relative units or absolute units. Absolute units Absolute units are not proportionally calculated but refer to a size set in stone, so to speak, and are expressed most of the time in pixels (px). For instance, if in your CSS you declare this:
body { font-size:16px; } ... you are telling the browser that whatever happens, the font size must be 16 pixels. Modern browsers get around this rule by pretending that you're asking for "16 pixels when the user sets a zoom factor of 100%". Yet, for many years Internet Explorer adamantly displayed 16 pixels as 16 pixels. In this case, zooming did nothing, even as late as Internet Explorer 8, which w...
...as portions of 1, like em. Suppose we wanted a base font size of 16px and an h1 (main heading) at the equivalent of 32px, yet if within the h1 we find a span with the subheading class, it too must be rendered at the default font size (usually 16px). ...
...And 6 more matches
Looping code - Learn web development
dom 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 WIDTH = document.documentElement.
...er) { return Math.floor(Math.random()*number); } function draw() { ctx.clearRect(0,0,WIDTH,HEIGHT); for (let i = 0; i < 100; i++) { ctx.beginPath(); ctx.fillStyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI); ctx.fill(); } } btn.addEventListener('click',draw); </script> </
body> </html> You don't have to understand all the code for now, but let's look at the part of the code that actually draws the 100 circles: 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(); } random(x), defined earlier in the code, returns a whole number between 0 and x-...
...ff', 'Pete', 'Biggles', 'Jasmin']; let info = 'My cats are called '; const para = document.querySelector('p'); for (let i = 0; i < cats.length; i++) { info += cats[i] + ', '; } para.textContent = info; This gives us the following output: Hidden code 2 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Basic for loop example</title> <style> </style> </head> <
body> <p></p> <script> const cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin']; let info = 'My cats are called '; const para = document.querySelector('p'); for (let i = 0; i < cats.length; i++) { info += cats[i] + ', '; } para.textContent = info; </script> </
body> </html> Note: You can find this example code on GitHub too (also see it running li...
...And 6 more matches
Creating reftest-based unit tests
ut this, but the released builds and the nightly builds are built with the "--disable-tests" option and reftest will not work - see bug 369809. Step 2 Open a terminal window. Create a directory (inside Firefox's source code tree) and make that your current directory (i.e. move to that directory). ...
...ds and the nightly builds are built with the "--disable-tests" option and reftest will not work - see bug 369809. Step 2 Open a terminal window. Create a directory (inside Firefox's source code tree) and make that your current directory (i.e. move to that directory). ...
...ep 2 Open a terminal window. Create a directory (inside Firefox's source code tree) and make that your current directory (i.e. move to that directory). ...
...And 6 more matches
Encrypt Decrypt_MAC_Using Token
CK_MECHANISM_TYPE type) { return CryptInit(dk, iv, ivLen, type, CKA_DECRYPT); } /* * Read cryptographic parameters from the header file. ...
...pe) { return CryptInit(dk, iv, ivLen, type, CKA_DECRYPT); } /* * Read cryptographic parameters from the header file. ...
...(trailer, MACKEY_TRAILER); break; case IV: strcpy(header, IV_HEADER); strcpy(trailer, IV_TRAILER); break; case MAC: strcpy(header, MAC_HEADER); strcpy(trailer, MAC_TRAILER); break; case PAD: strcpy(header, PAD_HEADER); strcpy(trailer, PAD_TRAILER); break; } rv = FileToItem(&filedata, file); non
body = (char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* Check for headers and trailers and remove them. */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body) ...
...And 6 more matches
Bytecode Descriptions
object" with a next method, but notes that it "is never directly accessible" to scripts. The object we use for this has no public methods.) If val is null or undefined, this pushes an empty iterator. The iter object pushed by this instruction must not be used or removed from the stack except by JSOp::MoreIter and JSOp::EndIter, or by error handling. The script's JSScript::trynotes() must mark the
body of the for-in loop, i.e. exactly those instructions that begin executing with iter on the stack, starting with the next instruction (always JSOp::LoopHead). Code must not jump into or out of this region: control can enter only by executing JSOp::Iter and can exit only by executing a JSOp::EndIter or by exception unwinding. (A JSOp::EndIter is always emitted at the end of the loop, and extra copie...
...te at most once per generator or async call). InitialYield Operands: (uint24_t resumeIndex) Stack: gen => rval, gen, resumeKind Suspend the current generator and return to the caller. When a generator is called, its script starts running, like any other JS function, because FunctionDeclarationInstantation and other generator object setup are implemented mostly in bytecode. However, the Function
Body of the generator is not supposed to start running until the first .next() call, so after setup the script suspends itself: the "initial yield". Later, when resuming execution, rval, gen and resumeKind will receive the values passed in by JSOp::Resume. resumeKind is the GeneratorResumeKind stored as an Int32 value. This instruction must appear only in scripts for generators and async generators. g...
... ("jump if true"), but if the branch is taken, pop and discard an additional stack value. This is used to implement switch statements when the JSOp::TableSwitch optimization is not possible. The switch statement switch (expr) { case A: stmt1; case B: stmt2; } compiles to this bytecode: # dispatch code - evaluate expr, check it against each `case`, # jump to the right place in the
body or to the end. <expr> Dup; <A>; StrictEq; Case L1; JumpTarget Dup; <B>; StrictEq; Case L2; JumpTarget Default LE #
body code L1: JumpTarget; <stmt1> L2: JumpTarget; <stmt2> LE: JumpTarget This opcode is weird: it's the only one whose ndefs varies depending on which way a conditional branch goes. We could implement switch statements using JSOp::IfNe and JSOp::Pop, but that wo...
...And 6 more matches
nsIPromptService
. You should use this method instead of window.alert in chrome code. void alert( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText ); Parameters aParent The parent window for the dialog, or null, in which case the parent window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of the dialog. aText Text to appear in the
body of the dialog. See also the alert_example. alertCheck() Shows an alert dialog with an OK button and a labeled checkbox. void alertCheck( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText, in wstring aCheckMsg, inout boolean aCheckState ); Parameters aParent The parent window for the dialog. If set to null the parent window will be nsIWindowWatcher.activeWindo...
... labeled checkbox. void alertCheck( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText, in wstring aCheckMsg, inout boolean aCheckState ); Parameters aParent The parent window for the dialog. If set to null the parent window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of the dialog. aText Text to appear in the
body of the dialog. aCheckMsg Text to appear with the checkbox. aCheckState Contains the initial checked state of the checkbox when this method is called and the final checked state after this method returns. If you call this method from JavaScript you need to wrap this argument in an object with its 'value' property set to a boolean (or use an empty object). See also the alertCheck_e...
...lertCheck_example. confirm() Shows a dialog with OK and cancel buttons. boolean confirm( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText ); Parameters aParent The parent window for the dialog. If set to null the parent window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of the dialog. aText Text to appear in the
body of the dialog. Return value true for OK, false for Cancel See also the confirm_example. confirmCheck() Shows a dialog with OK and Cancel buttons and a labeled checkbox. See also the confirm_example. boolean confirmCheck( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText, in wstring aCheckMsg, inout boolean aCheckState ); Parameters aParent The parent wi...
...And 6 more matches
PerformanceResourceTiming.transferSize - Web APIs
The transferSize read-only property represents the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload
body (as defined by RFC7230). Note: This feature is available in Web Workers. If the resource is fetched from a local cache, or if it is a cross-origin resource, this property returns zero. Syntax resource.transferSize; Return value A number representing the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload
body (RFC7230). Example The following example, the value of size properties of all "resource" type events are logged. function log_sizes(perfEntry){ // Check for support of the PerformanceEntry.*size properties and print their values // if supported. ...
...presenting the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload
body (RFC7230). Example The following example, the value of size properties of all "resource" type events are logged. function log_sizes(perfEntry){ // Check for support of the PerformanceEntry.*size properties and print their values // if supported. ...
...esource. The size includes the response header fields plus the response payload
body (RFC7230). Example The following example, the value of size properties of all "resource" type events are logged. function log_sizes(perfEntry){ // Check for support of the PerformanceEntry.*size properties and print their values // if supported. ...
...And 6 more matches
Using readable streams - Web APIs
: This article assumes that you understand the use cases of readable streams, and are aware of the high-level concepts. If not, we suggest that you first read the Streams concepts and usage overview and dedicated Streams API concepts article, then come back. Note: If you are looking for information on writable streams try Using writable streams instead. Browser support You can consume Fetch
Body objects as streams and create your own custom readable streams in Firefox 65+ and Chrome 42+ (and equivalent Chromium-based browsers). Pipe chains are only supported in Chrome at the moment, and that functionality is subject to change. 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 wel...
...xamples/streams repo. You can find the full source code there, as well as links to the examples. Consuming a fetch as a stream The Fetch API allows you to fetch resources across the network, providing a modern alternative to XHR. It has a number of advantages, and what is really nice about it is that browsers have recently added the ability to consume a fetch response as a readable stream. The
Body mixin now includes the
body property, which is a simple getter exposing the
body contents as a readable stream. This mixin is implemented by both the Request and Response interfaces, so it is available on both, although consuming the stream of a response
body is perhaps a bit more obvious. As our Simple stream pump example shows (see it live also), exposing it is a matter of just accessing the b...
...dable stream. This mixin is implemented by both the Request and Response interfaces, so it is available on both, although consuming the stream of a response
body is perhaps a bit more obvious. 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. Attaching a reader Now we've got our streaming
body, reading the stream requires attaching a reader to it. ...
...And 6 more matches
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
e a choice, and the other two are set when the user clicks yes or no respectively. When accepted, the permission works for both notifications and push. ...
...(Fo...
...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 notif
Body = 'Created by '+games[randomItem].author+'.'; var notifImg = 'data/img/'+games[randomItem].slug+'.jpg'; var options = {
body: notif
Body, icon: notifImg } var notif = new Notification(notifTitle, options); setTimeout(randomNotification, 30000); } A new random notification is created every 30 seconds until it becomes too annoying and is disabled by the user. (For a real app, the notifications should be much less frequent, and more useful.) The advantage of the Notifications API is that it uses the op...
...And 6 more matches
Browser Feature Detection - Archive of obsolete content
true Document.createComment() true true true Document.createAttribute() true true true Document.getElementsByTagName() true true true Document.title true true true Document.referrer true true true Document.domain true true true Document.URL true true true Document.
body true true true Document.images true true true Document.applets true true true Document.links true true true Document.forms true true true Document.anchors true true true Document.cookie true true true Document.open() true true true Document.close() tru...
... true true Document.open() true true true Document.close() true true true Document.write() true true true Document.writeln() true true true Document.getElementById() true true true Document.getElementsByName() true true true DOM CSS 1 Support for properties/methods in document.
body.style name Firefox 1.5 IE 6 & 7 Opera 8.54 - 9.01 background true true true backgroundattachment true true true backgroundcolor true true true backgroundimage true true true backgroundrepeat true true true border true true true borderspacing true false t...
... true true true textdecoration true true true textindent true true true texttransform true true true verticalalign true true true whitespace true true true width true true true wordspacing true true true DOM CSS 2 Support for properties/methods in document.
body.style</caption> name Firefox 1.5 IE 6 & 7 Opera 8.54 - 9.01 azimuth true false false backgroundposition true true true bordercollapse true true true borderSpacing true false true bordertopcolor true true true borderrightcolor true true true borderbottomcolor t...
...And 5 more matches
GLSL Shaders - Game development
d: Make sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. Create a directory to store your experiments in. Save a copy of the latest minimized Three.js library inside your directory. HTML structure Here's the HTML structure we will use. ...
... experiments in. Save a copy of the latest minimized Three.js library inside your directory. HTML structure Here's the HTML structure we will use. ...
...argin: 0; padding: 0; font-size: 0; } canvas { width: 100%; height: 100%; } </style> <script src="three.min.js"></script> </head> <
body> <script id="vertexShader" type="x-shader/x-vertex"> // vertex shader's code goes here </script> <script id="fragmentShader" type="x-shader/x-fragment"> // fragment shader's code goes here </script> <script> // scene setup goes here </script> </
body> </html> It contains some basic information like the document <title>, and some CSS to set the width and height of the <canvas> element that Three.js will insert on the page to be the full size of the viewport. ...
...And 5 more matches
Grids - Learn web development
to the grid. Let's add three 200-pixel columns here. You can use any length unit, or percentages to create these column tracks. .container { display: grid; grid-template-columns: 200px 200px 200px; } Add the 2nd declaration to your CSS rule, then reload the page, and you should see that the items have rearranged themselves one into each cell of the created grid. ...
... .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. You can mix fr units and fixed length tracks -- in such a case the space needed for the fixed tracks is taken away before the space is distributed to the other tracks. ...
...re out. Gaps between tracks To create gaps between tracks we use the properties grid-column-gap for gaps between columns, grid-row-gap for gaps between rows, and grid-gap to set both at once. .container { display: grid; grid-template-columns: 2fr 1fr 1fr; grid-gap: 20px; } These gaps can be any length unit or a percentage, but not an fr unit. ...
...And 5 more matches
Legacy layout methods - Learn web development
e example -- a two column layout. You can follow along by creating a new index.html file on your computer, filling it with a simple HTML template, and inserting the below code into it at the appropriate places. At the bottom of the section you can see a live example of what the final code should look like. First of all, we need some content to put into our columns. 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. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. Sed auctor cursus massa at porta. Integer ligula ...
...ascetur ridiculus mus.</p> </div> Each one of the columns needs an outer element to contain its content and let us manipulate all of it at once. In this example case we've chosen <div>s, but you could choose something more semantically appropriate like <article>s, <section>s, and <aside>, or whatever. Now for the CSS. First, of all, apply the following to your HTML to provide some basic setup:
body { width: 90%; max-width: 900px; margin: 0 auto; } The
body will be 90% of the viewport wide until it gets to 900px wide, in which case it will stay fixed at this width and center itself in the viewport. By default, its children (the <h1> and the two <div>s) will span 100% of the width of the
body. If we want the two <div>s to be floated alongside one another, we need to set their widths to...
...us ut, facilisis sed est. Nam id risus quis ante semper consectetur eget aliquam lorem. Vivamus tristique elit dolor, sed pretium metus suscipit vel. Mauris ultricies lectus sed lobortis finibus. Vivamus eu urna eget velit cursus viverra quis vestibulum sem. Aliquam tincidunt eget purus in interdum. ...
...And 5 more matches
Making asynchronous programming easier with async and await - Learn web development
t 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! ...
... async/await to see how much simpler it makes things: async function myFetch() { let response = await fetch('coffee.jpg'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { let myBlob = await response.blob(); let objectURL = URL.createObjectURL(myBlob); let image = document.createElement('img'); image.src = objectURL; document.
body.appendChild(image); } } myFetch() .catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); }); It makes code much simpler and easier to understand -- no more .then() blocks everywhere! Since an async keyword turns a function into a promise, you could refactor your code to use a hybrid approach of promises and await, bringing the second half of the func...
... But how does it work? You'll note that we've wrapped the code inside a function, and we've included the async keyword before the function keyword. This is necessary -- you have to create an async function to define a block of code in which you'l...
...And 5 more matches
Using images - Web APIs
for a small line graph. Using backdrops can make your script considerably smaller because we can avoid the need for code to generate the background. In this example, we're only using one image, so I use the image object's load event handler to execute the drawing statements. The drawImage() method places the backdrop at the coordinate (0, 0), which is the top-left corner of the canvas. ...
...cause we can avoid the need for code to generate the background. In this example, we're only using one image, so I use the image object's load event handler to execute the drawing statements. The drawImage() method places the backdrop at the coordinate (0, 0), which is the top-left corner of the canvas. ...
...nt positions. In the code below, the first for loop iterates over the rows. The second for loop iterates over the columns. The image is scaled to one third of its original size, which is 50x38 pixels. Note: Images can become blurry when scaling up or grainy if they're scaled down too much. Scaling is probably best not done if you've got some text in it which needs to remain legible. ...
...And 5 more matches
Element.getClientRects() - Web APIs
Example 3: This HTML creates two tables with captions. Client rects are painted for the <table> in the second block. ...
...L creates two tables with captions. Client rects are painted for the <table> in the second block. ...
...ith captions. Client rects are painted for the <table> in the second block. ...
...And 5 more matches
Pointer events - Web APIs
<html> <script> var id = -1; function process_id(event) { // Process this event based on the event's identifier } function process_mouse(event) { // Process the mouse pointer event } function...
... down_handler; el.onpointermove = move_handler; el.onpointerup = up_handler; el.onpointercancel = cancel_handler; el.onpointerout = out_handler; el.onpointerleave = leave_handler; el.gotpointercapture = gotcapture_handler; el.lostpointercapture = lostcapture_handler; } </script> <
body onload="init();"> <div id="target"> Touch me ... </div> </
body> </html> Event properties This example illustrates accessing all of a touch event's properties. <html> <script> var id = -1; function process_id(event) { // Process this event based on the event's identifier } function process_mouse(event) { // Process the mouse pointer event } function process_pen(event) { // Process the pen pointer event } ...
...The application can use the isPrimary property to identify a mast...
...And 5 more matches
ARIA: rowgroup role - Accessibility
That ro...
...> </div> </div> </div> Description Rowgroup establishes a relationship between owned row elements and is a structural equivalent to the thead, tfoot and t
body elements in HTML. There is, however, no differentiation between different types of rowgroups. Their elements must be contained in, or owned by, elements with either the table or grid role. Using the native <thead>, <tfoot> , and <t
body> HTML elements, whenever possible, is strongly encouraged. To create an ARIA table header, table footer or table
body, add role="rowgroup" to the element. That rowgroup should be nested within a grid, table or treegrid, encompassing a group of one or more rows. Each row, in turn, contains child cells. These cells can be of different types, depending on whether they are column or row headers, or ...
...oup" to the element. That rowgroup should be nested within a grid, table or treegrid, encompassing a group of one or more rows. Each row, in turn, contains child cells. These cells can be of different types, depending on whether they are column or row headers, or plain or grid cells. Note: Using the native HTML table element (<table>) along with the table header (<thead>), footer (<tfoot>), and
body (<t
body>) elements whenever possible is strongly encouraged. Associated WAI-ARIA roles, states, and properties Context roles role="table" One of the three possible contexts (along with grid and treegrid) in which you'll find a row. It identifies the row as being part of a non-interactive table structure containing data arranged in rows and columns, similar to the native <table> HTML elem...
...And 5 more matches
jspage - Archive of obsolete content
||f.event;if(a.$extended){return a;}this.$extended=true;var j=a.type; var g=a.target||a.srcElement;while(g&&g.nodeType==3){g=g.parentNode;}if(j.test(/key/)){var b=a.which||a.keyCode;var m=Event.Keys.keyOf(b);if(j=="keydown"){var d=b-111; if(d>0&&d<13){m="f"+d;}}m=m||String.fromCharCode(b).toLowerCase();}else{if(j.match(/(click|mouse|menu)/i)){k=(!k.compatMode||k.compatMode=="CSS1Compat")?k.html:k.
body; var i={x:a.pageX||a.clientX+k.scrollLeft,y:a.pageY||a.clientY+k.scrollTop};var c={x:(a.pageX)?a.pageX-f.pageXOffset:a.clientX,y:(a.pageY)?a.pageY-f.pageYOffset:a.clientY}; if(j.match(/DOMMouseScroll|mousewheel/)){var h=(a.wheelDelta)?a.wheelDelta/120:-(a.detail||0)/3;}var e=(a.which==3)||(a.button==2);var l=null;if(j.match(/over|out/)){switch(j){case"mouseover":l=a.relatedTarget||a.fromElement; ...
...):"IFrame_"+$time()); c=new Element(c||"iframe",d);var b=function(){var g=$try(function(){return c.contentWindow.location.host;});if(!g||g==window.location.host){var h=new Window(c.contentWindow); new Document(c.contentWindow.document);$extend(h.Element.prototype,Element.Prototype);}e.call(c.contentWindow,c.contentWindow.document);};var a=$try(function(){return c.contentWindow; });((a&&a.document.
body)||window.frames[d.id])?b():c.addListener("load",b);return c;}});var Elements=new Native({initialize:function(f,b){b=$extend({ddup:true,cash:true},b); f=f||[];if(b.ddup||b.cash){var g={},e=[];for(var c=0,a=f.length;c<a;c++){var d=document.id(f[c],!b.cash);if(b.ddup){if(g[d.uid]){continue;}g[d.uid]=true; }if(d){e.push(d);}}f=e;}return(b.cash)?$extend(f,this):f;}});Elements.implement({filter:functio...
...lement.Properties=new Hash;Element.Properties.style={set:function(a){this.style.cssText=a; },get:function(){return this.style.cssText;},erase:function(){this.style.cssText="";}};Element.Properties.tag={get:function(){return this.tagName.toLowerCase(); }};Element.Properties.html=(function(){var c=document.createElement("div");var a={table:[1,"<table>","</table>"],select:[1,"<select>","</select>"],t
body:[2,"<table><t
body>","</t
body></table>"],tr:[3,"<table><t
body><tr>","</tr></t
body></table>"]}; a.thead=a.tfoot=a.t
body;var b={set:function(){var e=Array.flatten(arguments).join("");var f=Browser.Engine.trident&&a[this.get("tag")];if(f){var g=c;g.innerHTML=f[1]+e+f[2]; for(var d=f[0];d--;){g=g.firstChild;}this.empty().adopt(g.childNodes);}else{this.innerHTML=e;}}};b.erase=b.set;return b;})();if(Bro...
...And 4 more matches
Adding Methods to XBL-defined Elements - Archive of obsolete content
e name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">Window.open(). You can define custom methods for your elements using the method element. The general syntax of methods is as follows: <implementation> <method name="method-name"> <parameter name="parameter-name1"/> <parameter name="parameter-name2"/> . . . <
body> <-- method script goes here --> </
body> </method> </implementation> A method declaration goes inside the implementation element, like the fields and properties do. The method element contains two type of child elements, parameter elements which describe the parameters to the method and
body which contains the script for the method. The value of the name attribute becomes the name ...
...f the name attribute becomes the name of the method. Similarly, the name attributes on the parameter elements become the names of each parameter. Each parameter element is used to declare one parameter for the method. For example, if the method had three parameters, there would be three parameter elements. You do not need to have any though, in which case the method would take no parameters. The
body element contains the script that is executed when the method is called. The names of the parameters are defined as variables in the script as if they had been passed as parameters. 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"> <pa...
...he method is called. The names of the parameters are defined as variables in the script as if they had been passed as parameters. 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 <= 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. Note that the less-than symbol has to be escaped because otherwise it would look like the start of a tag. You can also use a CDATA section to escape the entire block of code. You can call the method by using code ...
...And 4 more matches
Trees - Archive of obsolete content
ables of data with multiple rows and columns, and both may contain column headers. The tree also supports nested rows, whereas the listbox does not. However, listboxes may contain any type of content, whereas trees may only contain text and images. (Using advanced features, progress meters or checkboxes also can be added to the tree) A tree consists of two parts, the set of columns, and the tree
body. The set of columns is defined by a number of treecol elements, one for each column. Each column will appear as a header at the top of the tree. The second part, the tree
body, contains the data to appear in the tree and is created with a treechildren tag. The tree is unique in that the
body of the tree consists only of a single widget which draws all of the data in the tree. This contrasts...
...y, XUL provides a couple of built-in view implementations which do most of the hard work for you. For most trees, especially when you first start to use trees, you will use one of these built-in types. However, you can create a view entirely from scratch if necessary. If you do, you might store the data in an array or JavaScript data structure, or load the data from an XML file. Since the entire
body of the tree is a single widget, you can't change the style of individual rows or cells in the normal way. This is because there are no elements that display the individual cells, like there is with the listbox. Instead, all drawing is done by the tree
body using data supplied by the view. This is an important point and many XUL developers have trouble understanding this aspect. To modify the appe...
...In a sense, it is somewhat like using CSS classes. Tree styling will be discussed in detail in a later section. Tree Elements Trees can be created with the tree element, which is described in the following sections. ...
...And 4 more matches
Styling tables - Learn web development
yees; we decided to make things more interesting by making it about famous punk bands from the UK. The markup looks like so: <table> <caption>A summary of the UK's most famous punk bands</caption> <thead> <tr> <th scope="col">Band</th> <th scope="col">Year formed</th> <th scope="col">No. of Albums</th> <th scope="col">Most famous song</th> </tr> </thead> <t
body> <tr> <th scope="row">Buzzcocks</th> <td>1976</td> <td>9</td> <td>Ever fallen in love (with someone you shouldn't've)</td> </tr> <tr> <th scope="row">The Clash</th> <td>1976</td> <td>6</td> <td>London Calling</td> </tr> ... some rows removed for brevity <tr> <th scope="row">The Stranglers</th> <td>1974</td> ...
...6</td> <td>9</td> <td>Ever fallen in love (with someone you shouldn't've)</td> </tr> <tr> <th scope="row">The Clash</th> <td>1976</td> <td>6</td> <td>London Calling</td> </tr> ... some rows removed for brevity <tr> <th scope="row">The Stranglers</th> <td>1974</td> <td>17</td> <td>No More Heroes</td> </tr> </t
body> <tfoot> <tr> <th scope="row" colspan="2">Total albums</th> <td colspan="2">77</td> </tr> </tfoot> </table> The table is nicely marked up, easily styleable, and accessible, thanks to features such as scope, <caption>, <thead>, <t
body>, etc. Unfortunately, it doesn't look good when rendered on the screen (see it live at punk-bands-unstyled.html): With only the default b...
...We've also set our custom font on the headings inside the <thead> and <tfoot> elements, for a nice grungy, punky look. We've set...
...And 4 more matches
Introduction to CSS layout - Learn web development
t value. inherit -- Specifies that the value of the float property should be inherited from the element's parent element. In the example below we float a <div> left, and give it a margin on the right to push the text away from the element. This gives us the effect of text wrapped around that box, and is most of what you need to know about floats as used in modern web design. Floats example
body { width: 90%; max-width: 900px; margin: 0 auto; } p { line-height: 2; word-spacing: 0.1rem; } .box { background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227); padding: 10px; border-radius: 5px; } <h1>Simple float example</h1> <div class="box">Float</div> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor,...
...ple To provide familiarity with these page layout techniques, we'll show you a couple of quick examples. Our examples will all feature the same HTML, which is as follows: <h1>Positioning</h1> <p>I am a basic block level element.</p> <p class="positioned">I am a basic block level element.</p> <p>I am a basic block level element.</p> This HTML will be styled by default using the following CSS:
body { width: 500px; margin: 0 auto; } p { background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227); padding: 10px; margin: 10px; border-radius: 5px; } The rendered output is as follows: Relative positioning Relative positioning allows you to offset an item from the position in normal flow it would have by default. This means you could achieve a task such as...
...xpecting, but you need to think of it as the element being pushed on its left and top sides, which result in it moving right and down. ...
...And 4 more matches
How to build custom form controls - Learn web development
dle them, but it can be a real problem for exotic new controls. When it comes to standardized elements, of which the <select> is one, the specification authors spent an inordinate amount of time specifying all interactions for every use case for every input device. Creating new controls is not that easy, especially if you are creating something that has not been done before, and therefore which no
body has the slightest idea of what the expected behaviors and interactions are. At least select has been done before, so we know how it should behave! Designing new interactions is generally only an option for very large industry players who have enough reach that an interaction they create can become a standard. For example, Apple introduced the scroll wheel with the iPod in 2001. They had the mark...
... consider and cover the basics in our example (a full discussion of solving this issue for all scenarios would require a book). Just remember, it is vital make your script generic and reusable. In our example, if our JavaScript code isn't running, we'll fall back to displaying a standard <select> element. We include our control and the <select>; which one is displayed depends on the class of the
body element, with the class of the
body element being updated by the script that makes the control function, when it loads successfully To achieve this, we need two things: First, we need to add a regular <select> element before each instance of our custom control. There is a benefit to having this "extra" select even if our JavaScript works as hoped: we will use this select to send data from our c...
...ction, when it loads successfully To achieve this, we need two things: First, we need to add a regular <select> element before each instance of our custom control. There is a benefit to having this "extra" select even if our JavaScript works as hoped: we will use this select to send data from our custom control along with the rest of our form data. We will discuss this in greater depth later. ...
...And 4 more matches
CSS basics - Learn web development
high */ font-family: "Open Sans", sans-serif; /* this should be the rest of the output you got from Google fonts */ } Note: Anything in CSS between /* and */ is a CSS comment. The browser ignores comments as it renders the code. CSS comments are a way for you to write helpful notes about your code or logic. Now let's set font sizes for elements that will have text inside the HTML
body (<h1>, <li>, and <p>). We'll also center the heading. Finally, let's expand the second ruleset (below) with settings for line height and letter spacing to make
body content more readable. h1 { font-size: 60px; text-align: center; } p, li { font-size: 16px; line-height: 2; letter-spacing: 1px; } Adjust the px values as you like. Your work-in-progress should look similar to this: ...
... an element. (keep reading to learn more) To continue, let's add more CSS. Keep adding these new rules at the bottom of style.css. Experiment with changing values to see what happens. Changing the page color html { background-color: #00539F; } This rule sets a background color for the entire page. Change the color code to the color you chose in What will my website look like?. Styling the
body body { width: 600px; margin: 0 auto; background-color: #FF9500; padding: 0 20px 20px 20px; border: 5px solid black; } There are several declarations for the <
body> element. Let's go through these line-by-line: width: 600px; This forces the
body to always be 600 pixels wide. margin: 0 auto; When you set two values on a property like margin or padding, the first value affects the el...
... top and bottom side (setting it to 0 in this case); the second value affects the left and right side. (Here, auto is a special value that divides the available horizontal space evenly between left and right). You can also use one, three, or four values, as documented in Margin Syntax. background-color: #FF9500; This sets the element's background color. This project uses a reddish orange for the
body background color, as opposed to dark blue for the <html> element. (Feel free to experiment.) padding: 0 20px 20px 20px; This sets four values for padding. The goal is to put some space around the content. In this example, there is no padding on the top of the
body, and 20 pixels on the right, bottom and left. The values set top, right, bottom, left, in that order. As with margin, you can use on...
...And 4 more matches
Introducing asynchronous JavaScript - Learn web development
ules is synchronous -- you run some code, and the result is returned as soon as the browser can do so. Let's look at a simple example (see it live here, and see the source): const btn = document.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> element that is already available in the DOM. We add a click event listener to it so that when the button is clicked: An alert() message appears. Once the alert is dismissed, we create a <p> element. We then give it some text content. Finally, we append the par...
...; In this block, the lines are executed one after the other: We grab a reference to a <button> element that is already available in the DOM. We add a click event listener to it so that when the button is clicked: An alert() message appears. Once the alert is dismissed, we create a <p> element. We then give it some text content. Finally, we append the paragraph to the document
body. While each operation is being processed, nothing else can happen -- rendering is paused. This is because as we said in the previous article, JavaScript is single threaded. Only one thing can happen at a time, on a single main thread, and everything else is blocked until an operation completes. So in the example above, after you've clicked the button the paragraph won't appear until after...
...d-fashioned now, but you'll still see them in use in a number of older-but-still-commonly-used APIs. An example of an async callback is the second parameter of the addEventListener() method (as we saw in action above): btn.addEventListener('click', () => { alert('You clicked me!'); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.
body.appendChild(pElem); }); The first parameter is the type of event to be listened for, and the second parameter is a callback function that is invoked when the event is fired. When we pass a callback function as an argument to another function, we are only passing the function's reference as an argument, i.e, the callback function is not executed immediately. It is "called back" (hence the name) ...
...And 4 more matches
Introduction to events - Learn web development
We also define a function that returns a random number. The third part of the code is the event handler. The btn constant points to a <button> element, and this type of object has a number of events that can fire on it, and therefore, event...
... number. The third part of the code is the event handler. The btn constant points to a <button> element, and this type of object has a number of events that can fire on it, and therefore, event handlers available. We are listening for the click event firing, by setting the onclick event handler property to equal an anonymous function containing code that generates a random RGB color and sets the <
body> background-color equal to it. This code is run whenever the click event fires on the <button> element, that is, whenever a user selects it. The example output is as follows: It's not just web pages Another thing worth mentioning at this point is that events are not unique to JavaScript -- most programming languages have some kind of event model, and the way the model works often differs fr...
...rious mechanisms and discuss which ones you should use. Event handler properties These are the properties that exist to contain event handler code we have seen most frequently during the course. Returning to the above example: const btn = document.querySelector('button'); btn.onclick = function() { const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.
body.style.backgroundColor = rndCol; } The onclick property is the event handler property being used in this situation. It is essentially a property like any other available on the button (e.g. btn.textContent, or btn.style), but it is a special type -- when you set it to be equal to some code, that code is run when the event fires on the button. You could also set the handler property to be equal t...
...And 4 more matches
Client-Server Overview - Learn web development
r update some data). The different methods/verbs and their associated actions are listed below: GET: Get a specific resource (e.g. an HTML file containing information about a product, or a list of products). POST: Create a new resource (e.g. add a new article to a wiki, add a new contact to a database). HEAD: Get the metadata information about a specific resource without getting the
body like GET would. 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. PUT: Update an existing resource (or create a new one if it doesn't exist). DELETE: Delete the specified resource. TRACE, OPTIONS, CONNECT, PATCH: These verbs are for less common/advanc...
... an equals sign (=) separating each name from its associated value, and an ampersand (&) separating each pair. URL parameters are inherently "insecure" as they can be changed by users and then resubmitted. As a result URL parameters/GET requests are not used for requests that update data on the server. POST data. POST requests add new resources, the data for which is encoded within the request
body. Client-side cookies. Cookies contain session data about the client, including keys that the server can use to determine their login status and permissions/accesses to resources. Web servers wait for client request messages, process them when they arrive, and reply to the web browser with an HTTP Response message. The response contains an HTTP Response status code indicating whether or ...
...es. Web servers wait for client request messages, process them when they arrive, and reply to the web browser with an HTTP Response message. The response contains an HTTP Response status code indicating whether or not the request succeeded (e.g. "200 OK" for success, "404 Not Found" if the resource cannot be found, "403 Forbidden" if the user isn't authorised to see the resource, etc). The
body of a successful response to a GET request would contain the requested resource. When an HTML page is returned it is rendered by the web browser. As part of processing the browser may discover links to other resources (e.g. an HTML page usually references JavaScript and CSS pages), and will send separate HTTP Requests to download these files. Both static and dynamic websites (discussed in the fo...
...And 4 more matches
Introduction to automated testing - Learn web development
r example. Create a new file inside your project root called call_bstack.js. ...
...our project root called call_bstack.js. ...
...e indicated places. These can be retrieved from your BrowserStack automation dashboard. Fill these in now. Make sure everything is saved, and run your file like so: node call_bstack Below we've also provided some other ready-made functions you might find useful when working with the BrowserStack restful API. function getBuilds(){ request({uri: baseUrl + "builds.json"}, function(err, res,
body){ console.log(JSON.parse(
body)); }); /* Response: [ { automation_build: { name: <string>, duration: <int>, status: <string>, hashed_id: <string> } }, { automation_build: { name: <string>, duration: <int>, status: <string>, hashed_id: <string> } }, ... ] */ }; function getSessionsInBuild(build){ let buildId = build.automation_build.has...
...And 4 more matches
Scroll-linked effects
ffect to be laggy, janky, or jittery -- in short, something we want to avoid. 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. <
body style="height: 5000px" onscroll="document.getElementById('toolbar').style.top = Math.max(100, window.scrollY) + 'px'"> <div id="toolbar" style="position: absolute; top: 100px; width: 100px; height: 20px; background-color: green"></div> </
body> This implementation of sticky positioning relies on the scroll event listener to reposition the "toolbar" div. As the scroll event listener runs in the J...
...tive to the user-visible scroll, and so the div will not stay visually fixed as intended. Instead, it will move with the user's scrolling, and then "snap" back into position when the scroll event handler runs. This constant moving and snapping will result in a jittery visual effect. One way to implement this without the scroll event listener is to use the CSS property designed for this purpose: <
body style="height: 5000px"> <div id="toolbar" style="position: sticky; top: 0px; margin-top: 100px; width: 100px; height: 20px; background-color: green"></div> </
body> This version works well with asynchronous scrolling because position of the "toolbar" div is updated by the browser as the user scrolls. Example 2: Scroll snapping Below is an implementation of scroll snapping, where the scroll pos...
... width: 100px; height: 20px; background-color: green"></div> </
body> This version works well with asynchronous scrolling because position of the "toolbar" div is updated by the browser as the user scrolls. 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 4 more matches
Ajax navigation example - Web APIs
at the paragraph Submitting forms and uploading files. first_page.php: <?php $page_title = "First page"; $as_json = false; if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") { $as_json = true; ob_start(); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" . $page_title . ...
..."ajax-content"> <?php } ?> <p>This is the content of <strong>first_page.php</strong>.</p> <?php if ($as_json) { echo json_encode(array("page" => $page_title, "content" => ob_get_clean())); } else { ?> </div> <p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> <?php include "include/after_content.php"; echo "</
body>\n</html>"; } ?> second_page.php: <?php $page_title = "Second page"; $as_json = false; if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") { $as_json = true; ob_start(); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" . $page_title . "</title>"; ?> </head> <
body> <?php include "include...
...This content is stored into a php variable.</p>"; if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") { echo json_encode(array("page" => $page_title, "content" => $page_content)); } else { ?> <!doctype html> <html> ...
...And 4 more matches
Using IndexedDB - Web APIs
ML Content <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <h1>IndexedDB Demo: storing blobs, e-publication example</h1> <div class="note"> <p> Works and tested with: </p> <div id="compat"> </div> </div> <div id="msg"> </div> <form id="register-form"> <table> <t
body> <tr> <td> <label for="pub-title" class="required"> Title: </label> </td> <td> <input type="text" id="pub-title" name="pub-title" /> </td> </tr> <tr> <td> <label for="pub-biblioid" class="required"> Bibliographic ID:<br/>...
... </td> <td> <input type="text" id="pub-biblioid" name="pub-biblioid"/> </td> </tr> <tr> <td> <label for="pub-year"> Year: </label> </td> <td> <input type="number" id="pub-year" name="pub-year" /> </td> </tr> </t
body> <t
body> <tr> <td> <label for="pub-file"> File image: </label> </td> <td> <input type="file" id="pub-file"/> </td> </tr> <tr> <td> <label for="pub-file-url"> Online-file image URL:<br/> <span class...
..."pub-file"/> </td> </tr> <tr> <td> <label for="pub-file-url"> Online-file image URL:<br/> <span class="note">(same origin URL)</span> </label> </td> <td> <input type="text" id="pub-file-url" name="pub-file-url"/> </td> </tr> </t
body> </table> <div class="button-pane"> <input type="button" id="add-button" value="Add Publication" /> <input type="reset" id="register-form-reset"/> </div> </form> <form id="delete-form"> <table> <t
body> <tr> <td> <label for="pub-biblioid-to-delete"> Bibliographic ID:<br/> <...
...And 4 more matches
Generating HTML - Web APIs
The XML document contains both HTML elements and XML elements, but only one namespace is needed, namely for the XML elements. ...
...e2.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. Foo</myNS:Author> <myNS:Author>Mr. Bar</myNS:Author> </myNS:Authors> <myNS:
Body> The <b>rain</b> in <u>Spain</u> stays mainly in the plains. </myNS:
Body> </myNS:Article> The XSL Stylesheet used will need to have two namespaces - one for the XSLT elements and one for our own XML elements used in the XML document. The output of the XSL Stylesheet is set to HTML by using the xsl:output element. By setting the output to be HTML and not having a namespace on the res...
...cture of the HTML page. Figure 4 : Creating the basic HTML document XSL Stylesheet (example2.xsl): ... <xsl:template match="/"> <html> <head> <title> <xsl:value-of select="/myNS:Article/myNS:Title"/> </title> <style type="text/css"> .myBox {margin:10px 155px 0 50px; border: 1px dotted #639ACE; padding:0 5px 0 5px;} </style> </head> <
body> <p class="myBox"> <span class="title"> <xsl:value-of select="/myNS:Article/myNS:Title"/> </span> </br> Authors: <br /> <xsl:apply-templates select="/myNS:Article/myNS:Authors/myNS:Author"/> </p> <p class="myBox"> <xsl:apply-templates select="//myNS:
Body"/> </p> </
body> </html> </xsl:template> ... Three ...
...And 4 more matches
ARIA: contentinfo role - Accessibility
element or by declaring role="contentinfo". contentinfo landmarks present in content embedded via <iframe> elements do not count towards this limit. Using the <footer> element will automatically communicate a section has a role of contentinfo. Developers should always prefer using the correct semantic HTML element over using ARIA, making sure to test for known issues in VoiceOver. 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>(C) 2005-2018 Mozilla and individual contributors. Content is available under <a href="#">these licenses<...
... 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>(C) 2005-2018 Mozilla and individual contributors. ...
... Mega-footers Do not nest additional <footer> elements or contentinfo landmarks inside of the document's footer. Use other content sectioning elements instead. ...
...And 4 more matches
@media - CSS: Cascading Style Sheets
ge the returned values in some manner in order to prevent them from being used to precisely identify a computer. 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-name> : <mf-value><mf-boolean> = <mf-name><mf-range> = <mf-name> [ '<' | '>' ]? '='? <mf-value> | <mf-value> [ '<' | '>' ]? '='? <mf-name> | <mf-value> '<' '='? <mf-name> '<' '='? <mf-value> | <mf-value> '>' '='? <mf-name> '>' '='? ...
...e><mf-range> = <mf-name> [ '<' | '>' ]? '='? <mf-value> | <mf-value> [ '<' | '>' ]? '='? <mf-name> | <mf-value> '<' '='? <mf-name> '<' '='? <mf-value> | <mf-value> '>' '='? <mf-name> '>' '='? ...
...And 4 more matches
Printing - Developer guides
You can also try changing the code to use <code>beforeprint</code> to see the differen...
...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.write('</
body></html>'); } </script> </head> <
body> <p>To try out the <code>afterprint</code> event, click the link below to open the window to print. ...
...rint this window, it will close afterward.</p>'); my_window.document.write('</
body></html>'); } </script> </head> <
body> <p>To try out the <code>afterprint</code> event, click the link below to open the window to print. 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="...
...And 4 more matches
Preloading content with rel="preload" - HTML: Hypertext Markup Language
resource in the href attribute. The type of resource in the as attribute. 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> </
body> Here we preload our CSS and JavaScript files so they will be available as soon as they are required for the rendering of the page later on. 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 be...
...rce, and will only download it if so, ignoring it if not. ...
...Browsers that don't support MP4 can still load the WebM version, but don't get the advantages of preloading. ...
...And 4 more matches
Index - HTTP
HTTP, Headers, Reference, Web The Connection general header controls whether or not the network connection stays open after the current transaction finishes. If the value sent is keep-alive, the connection is persistent and not closed, allowing for subsequent requests to the same server to be done. 22 Content-Disposition HTTP, Reference, header In a multipart/form-data
body, the HTTP Content-Disposition general header is a header that can be used on the subpart of a multipart
body to give information about the field it applies to. The subpart is delimited by the boundary defined in the Content-Type header. Used on the
body itself, Content-Disposition has no effect. 23 Content-Encoding HTTP, Headers, Reference The Content-Encoding entity header i...
...It lets the client know how to decode in order to obtain the media-type referenced by the Content-Type header. ...
...nt-Type header. 24 Content-Language HTTP, Headers, Reference The Content-Language entity header is used to describe the language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language. 25 Content-Length HTTP, Headers, Reference The Content-Length entity header indicates the size of the entity-
body, in bytes, sent to the recipient. 26 Content-Location HTTP, Reference, header The Content-Location header indicates an alternate location for the returned data. The principal use is to indicate the URL of a resource transmitted as the result of content negotiation. 27 Content-Range HTTP, HTTP Header, Reference, Response Header, header The Content-Range re...
...And 4 more matches
Authoring MathML - MathML
CSS, DOM, Javascript or SVG. This is out of the scope of this document but anyone with basic knowledge of Web languages will easily be able to mix these features with MathML. Check out our demos and MathML references for more details. Using MathML MathML in HTML pages You can use Presentation MathML inside HTML5 documents: <!DOCTYPE html> <html> <head> <title>MathML in HTML5</title> </head> <
body> <h1>MathML in HTML5</h1> <p> Square root of two: <math> <msqrt> <mn>2</mn> </msqrt> </math> </p> </
body> </html> Content MathML is not supported by browsers. 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. Tools mentioned on this page generates P...
...r others in your own project, you might need the detection scripts to verify the level of MathML support. 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); return Math.abs(box.height - 23) <= 1 && Math.abs(box.width - 77) <= 1; } Alternatively, the following UA string sniffing will allow to detect the rendering engines with native MathML support (Gecko and WebKit). Note that UA string sniffing is not the most reliable method and might b...
...s for Mozilla 2.0. For Gecko 31.0 (Firefox 31.0 / Thunderbird 31.0 / SeaMonkey 2.28), this is much simpler and is compatible with any Web rendering engine with MathML support. 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 and Latin Modern Math. See this GitHub repository to get WOFF fonts and sample CSS stylesheets to use on your Web site and check its test page. MathML in XML documents (XHTML, EPUB, etc) If for some reason you need to...
...And 4 more matches
d - SVG: Scalable Vector Graphics
The d attribute defines a path to be drawn. A path definition is a list of path commands where each command is composed of a command letter and numbers that represent the command parameters. The commands are detailed below. Three elements have this attribute: <path>, <glyph>, and <missing-glyph> 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,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z" /> </svg> path For <path>, d is a string containing a series of path commands that define the path to be drawn. Value <string> Default value none Animatable Yes glyph Warning: As of SVG2 <glyph> is deprecated ...
...(L) command(s) (see below). Formula: Pn = {x, y} m (dx, dy)+ Move the current point by shifting the last known position of the path by dx along the x-axis and by dy along the y-axis. Any subsequent coordinate pair(s) are interpreted as parameter(s) for implicit relative LineTo (l) command(s) (see below). ...
...la: Po? = Pn = {xo, y} v dy+ Draw a vertical line from the current point to the end point, which is specified by the current point shifted by dy along the y-axis and the current point's x coordinate. Any subsequent value(s) are interpreted as parameter(s) for implicit relative vertical LineTo (v) command(s). ...
...And 4 more matches
transform - SVG: Scalable Vector Graphics
The transform attribute defines a list of transform definitions that are applied to an element and the element's children. html,
body,svg { height:100% } <svg viewBox="-40 0 150 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g fill="grey" transform="rotate(-10 50 100) translate(-36 45.5) skewX(40) scale(1 0.5)"> <path id="heart" d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z" /> </g> <use xlink:href="#heart" fill="none" stroke="red"/> </svg> Note: As of SVG2, transform is a presentation attribute, meaning it can be used as a CSS property. However, be aware that there are some difference in syntax between the CSS property and the attribute. See the do...
...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 + e = 3 * 10 ...
... + 30 = 120 newY = b * oldX + d * oldY + f = 1 * 40 + 3 * 30 + 40 = 170 --> <rect x="10" y="10" width="30" height="20" fill="red" transform="matrix(3 1 -1 3 30 40)" /> </svg> Translate The translate(<x> [<y>]) transform function moves the object by x and y. If y is not provided, it is assumed to be 0. ...
...And 4 more matches
Content Scripts - Archive of obsolete content
ain code and content scripts to communicate with each other This complete add-on illustrates all of these principles. Its "main.js" attaches a content script to the current tab using the tabs module. In this case the content script is passed in as a string. The content script simply replaces the content of the page: // main.js var tabs = require("sdk/tabs"); var contentScriptString = 'document.
body.innerHTML = "<h1>this page has been eaten</h1>";' tabs.activeTab.attach({ contentScript: contentScriptString }); The following high-level SDK modules can use content scripts to modify web pages: page-mod: enables you to attach content scripts to web pages that match a specific URL pattern. tabs: exports a Tab object for working with a browser tab. The Tab object includes an attach() funct...
...s guide are available as complete, but minimal, add-ons in the addon-sdk-content-scripts repository on GitHub. Loading content scripts You can load a single script by assigning a string to either the contentScript or the contentScriptFile option. The contentScript option treats the string itself as a script: // main.js var pageMod = require("sdk/page-mod"); var contentScriptValue = 'document.
body.innerHTML = ' + ' "<h1>Page matches ruleset</h1>";'; pageMod.PageMod({ include: "*.mozilla.org", contentScript: contentScriptValue }); The contentScriptFile option treats the string as a resource:// URL pointing to a script file stored in your add-on's data directory. jpm doesn't make a "data" directory by default, so you must add it and put your content scripts in ...
...and put your content scripts in there. This add-on supplies a URL pointing to the file "content-script.js", located in the data subdirectory under the add-on's root directory: // main.js var data = require("sdk/self").data; var pageMod = require("sdk/page-mod"); pageMod.PageMod({ include: "*.mozilla.org", contentScriptFile: data.url("content-script.js") }); // content-script.js document.
body.innerHTML = "<h1>Page matches ruleset</h1>"; From Firefox 34 onwards, you can use "./content-script.js" as an alias for self.data.url("content-script.js"). So you can rewrite the above main.js code like this: var pageMod = require("sdk/page-mod"); pageMod.PageMod({ include: "*.mozilla.org", contentScriptFile: "./content-script.js" }); Unless your content script is extremely simple and...
...And 3 more matches
panel - Archive of obsolete content
ent from the // main add-on code. It means that the panel's about // to be shown. // // Set the focus to the text area so the user can // just start typing. self.port.on("show", function onShow() { textArea.focus(); }); Finally, the "text-entry.html" file defines the <textarea> element: <html> <head> <style type="text/css" media="all"> textarea { margin: 10px; }
body { background-color: gray; } </style> </head> <
body> <textarea rows="13" cols="33" id="edit-box"></textarea> </
body> </html> Finally, save these three icon files to the "data" directory: icon-16.png icon-32.png icon-64.png To learn much more about content scripts, see the Working with Content Scripts guide. Scripting truste...
...m the // main add-on code. It means that the panel's about // to be shown. // // Set the focus to the text area so the user can // just start typing. ...
.... // // Set the focus to the text area so the user can // just start typing. addon.port.on("show", function onShow() { textArea.focus(); }); Finally, the HTML file now references "get-text.js" inside a <script> tag: <html> <head> <style type="text/css" media="all"> textarea { margin: 10px; }
body { background-color: gray; } </style> </head> <
body> <textarea rows="13" cols="33" id="edit-box"></textarea> <script src="get-text.js"></script> </
body> </html> Styling panel content The panel's default style is different for each operating system: This helps to ensure that the panel's style is consistent with the dialogs displayed by Firefox and other applications, but means you need to take care when applying your own styles. If t...
...And 3 more matches
Forms related code snippets - Archive of obsolete content
offsetHeight) + "px"; oTarget.parentNode.insertBefore(oTable, oTarget); }; aInstances.push(this); } DatePicker.prototype.writeDays = function () { const nEndBlanks = (this.current.getDay() + bZeroIsMonday * 6) % 7, nEnd = aMonthLengths[this.current.getMonth()] + nEndBlanks, nTotal = nEnd + ((7 - nEnd % 7) % 7); var oTD, oTR; if (this.oT
Body) { this.container.removeChild(this.oT
Body); } this.oT
Body = document.createElement("t
body"); for (var nDay, oDay, nIter = 0; nIter < nTotal; nIter++) { if (nIter % 7 === 0) { oTR = document.createElement("tr"); this.oT
Body.appendChild(oTR); } nDay = nIter - nEndBlanks + 1; oTD = document.createElement("td"); if (nIter + 1 > nEndBlanks && nIt...
...ll"; oTD.id = sPrefs + "-day-" + this.id + "-" + nDay; oTD.onclick = onDayClick; oTD.appendChild(document.createTextNode(nDay)); } else { oTD.className = sPrefs + "-empty-cell"; } oTR.appendChild(oTD); } this.display.innerHTML = sMonthsNames[this.current.getMonth()] + " " + this.current.getFullYear(); this.container.appendChild(this.oT
Body); }; function onDocClick (oPssEvt) { const oEvt = oPssEvt || /* IE */ window.event; var bOutside = true; for (var oNode = oEvt.target || /* IE */ oEvt.srcElement; oNode; oNode = oNode.parentNode) { if (oNode.className === sPrefs + "-calendar" || oNode.className === sDPClass) { bOutside = false; break; } } if (bOutside) { return; } aInstanc...
...It is supported in Firefox & Chrome (V8) and partially supported in Opera 9+ and Safari. It ...
...And 3 more matches
Introducing the Audio API extension - Archive of obsolete content
vent has the following attributes: mozChannels: Number of channels mozSampleRate: Sample rate per second mozFrameBufferLength: Number of samples collected in all channels This information is needed later to decode the audio data stream. ...
...Once the buffer is full, the event MozAudioAvailable is triggered. This event therefore contains the raw samples of a period of time. Those samples may or may not have been played yet at the tim...
...ted by channels; they are all delivered together. For example, for a two-channel signal: Channel1-Sample1 Channel2-Sample1 Channel1-Sample2 Channel2-Sample2 Channel1-Sample3 Channel2-Sample3. ...
...And 3 more matches
Notifications - Archive of obsolete content
pack Prototype, which is no longer under active development. Read the experiment report for what we learned from it and the blog post announcing the first SDK release for what we're up to next! The Notification Box appears at the bottom right corner of the browser and displays important information to the user. The namespace for this class is jetpack.notifications. ...
...ed from it and the blog post announcing the first SDK release for what we're up to next! The Notification Box appears at the bottom right corner of the browser and displays important information to the user. The namespace for this class is jetpack.notifications. Methods show(titlestring, [
body as string] iconstring)Draws a notification box. ...
...e bottom right corner of the browser and displays important information to the user. The namespace for this class is jetpack.notifications. Methods show(titlestring, [
body as string] iconstring)Draws a notification box. ...
...And 3 more matches
Elements - Archive of obsolete content
one binding attached (explicitly or inherited) at one moment. From several bindings only the last in the sequence will be used (like with any CSS rule). ...
...last in the sequence will be used (like with any CSS rule). ...
...structor The code inside the destructor is called when a binding is being removed from an element. You can use this to unload resources to free memory. However the destructor is often not called when it should, see bug 230086. The destructor tag must be placed inside the implementation tag. id - The id attribute is a document-unique identifier. method <!ENTITY % method-content "(parameter*,
body?)"> <!ELEMENT method %method-content;> <!ATTLIST method id ID #IMPLIED name CDATA #REQUIRED type CDATA #IMPLIED > The method element is used to describe a single method of a binding implementation. id - The id attribute is a document-unique identifier. name - The name attribute's value is the name given to the method whe...
...And 3 more matches
background-size - Archive of obsolete content
, here's a page with both rules - the CSS is derived from the code on the page here, this is what it looks like in 3.6a2pre on Linux, the background image appears on the whole page, and then again behind the main content. Here's a slightly more complex example (screenshot), and the same page without the -moz-border-image image rule (screenshot). ...
...h both rules - the CSS is derived from the code on the page here, this is what it looks like in 3.6a2pre on Linux, the background image appears on the whole page, and then again behind the main content. Here's a slightly more complex example (screenshot), and the same page without the -moz-border-image image rule (screenshot). User:robertc 2009-08-09 This is only an issue with <
body> and <html>. ...
...e in 3.6a2pre on Linux, the background image appears on the whole page, and then again behind the main content. Here's a slightly more complex example (screenshot), and the same page without the -moz-border-image image rule (screenshot). User:robertc 2009-08-09 This is only an issue with <
body> and <html>. <
body>'s background extends per CSS spec to <html>. Since you have a 8px default margin on <
body> and your <
body>'s content is smaller than the viewport's height, you see what you see. ...
...And 3 more matches
Multiple-column layout - Learn web development
two properties column-count or column-width. The column-count property will create as many columns as the value you give it, so if you add the following CSS to your stylesheet and reload the page, you will get three columns: .container { column-count: 3; } The columns that you create have flexible widths -- the browser works out how much space to assign each column. 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. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultr...
... } Change your CSS to use column-width as follows: .container { column-width: 200px; } The browser will now give you as many columns as it can of the size that you specify; any remaining space is then shared between the existing columns. This means that you will not get exactly the width that you specify, unless your container is exactly divisible by that width. column-width 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. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis felis orci, pulvinar id metus ut, rutrum luctus orci. Cras porttitor imperdiet nunc, at ultricies ...
...column-rule. In a similar way to the border property that you encountered in previous lessons, column-rule is a shorthand for column-rule-color, column-rule-style, and column-rule-width, and accepts the same values as border. .container { column-count: 3; column-gap: 20px; column-rule: 4px dotted rgb(79, 185, 227); } Try adding rules of different styles and colors. Styling the columns
body { width: 90%; max-width: 900px; margin: 2em auto; font: .9em/1.2 Arial, Helvetica, sans-serif; } .container { column-count: 3; column-gap: 20px; column-rule: 4px dotted rgb(79, 185, 227); } <div class="container"> <h1>Simple multicol example</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. Duis fe...
...And 3 more matches
Sending form data - Learn web development
ber of different methods, the most common being the GET method and the POST method To understand the difference between those two methods, let's step back and examine how HTTP works. Each time you want to reach a resource on the Web, the browser sends a request to a URL. ...
...nsists of two parts: a header that contains a set of global metadata about the browser's capabilities, and a
body that can contain information necessary for the server to process the specific request. The GET method The GET method is the method used by the browser to ask the server to send back a given resource: "Hey server, I want to get this resource." In this case, the browser sends an empty
body. Because the
body is empty, if a form is sent using this method the data sent to the server is appended to the URL. Consider the following form: <form action="http://www.foo.com" method="GET"> <div> <label for="say">What greeting do you want to say?</label> <input name="say" id="say" value="Hi"> </div> <div> <label for="to">Who do you want to say it to?</label> <input name...
...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). The POST method The POST method is a little different. It's the method the browser uses to talk to the server when asking for a response that takes into account the data provided in the
body of the HTTP request: "Hey server, take a look at this data and send me back an appropriate result." If a form is sent using this method, the data is appended to the
body of the HTTP request. 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. <form action="https://www.foo.com" method="POST"> <div> <label for="...
...And 3 more matches
Getting started with HTML - Learn web development
style="min-height: 100px;width: 95%"> This is my text. ...
...tyle="min-height: 100px;width: 95%"> <p>A link to my favorite website.</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', funct...
....</a> Instead, you need to do this: <a href='http://www.example.com' title='Isn't this fun?'>A link to my example.</a> Anatomy of an HTML document Individual HTML elements aren't very useful on their own. Next, let's examine how individual elements combine to form an entire HTML page: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My test page</title> </head> <
body> <p>This is my page</p> </
body> </html> Here we have: <!DOCTYPE html>: The doctype. When HTML was young (1991-1992), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML. Doctypes used to look something like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transiti...
...And 3 more matches
HTML text fundamentals - Learn web development
to navigate. On such occasions, it is advisable to spread the content over multiple pages if possible. Why do we need structure? 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). You should save a copy of this file on your local machine, as you'll need it for the exercises later on. This document's
body currently contains multiple pieces of content--they aren't marked up in any way, but they are separated with linebreaks (Enter/Return pressed to go onto the next line). However, when you open the document in your browser, you'll see that the text appears as a big chunk! This is because there are no elements to give the content structure, so the browser does not know what is a heading and what...
...istician and my name is Trish. ...
...area id="code" class="input" style="min-height: 100px; width: 95%">milk eggs bread hummus</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', funct...
...And 3 more matches
Choosing the right approach - Learn web development
"callback hell"). Failure callbacks need to be called once for each level of nesting, whereas with promises you can just use a single .catch() block to handle the errors for the entire chain. Async callbacks just aren't very graceful. Promise callbacks ar...
...If you nest a number of promises, you can end up with similar troubles to callback hell. For example: remotedb.allDocs({ include_docs: true, attachments: true }).then(function (result) { let docs = result.row...
...You ...
...And 3 more matches
What is JavaScript? - Learn web development
Note: If your example doesn't seem to work, go through the st...
... file. Call it script.js -- make sure it has that .js filename extension, as that's how it is recognized as JavaScript. Replace your current <script> element with the following: <script src="script.js" defer></script> Inside script.js, add the following script: function createParagraph() { let para = document.createElement('p'); para.textContent = 'You clicked the button!'; document.
body.appendChild(para); } const buttons = document.querySelectorAll('button'); for(let i = 0; i < buttons.length ; i++) { buttons[i].addEventListener('click', createParagraph); } Save and refresh your browser, and you should see the same thing! It works just the same, but now we've got our JavaScript in an external file. This is generally a good thing in terms of organizing your code and making...
.... Note: You can see this version on GitHub as apply-javascript-external.html and script.js (see it live too). Inline JavaScript handlers Note that sometimes you'll come across bits of actual JavaScript code living inside HTML. It might look something like this: function createParagraph() { let para = document.createElement('p'); para.textContent = 'You clicked the button!'; document.
body.appendChild(para); } <button onclick="createParagraph()">Click me!</button> You can try this version of our demo below. This demo has exactly the same functionality as in the previous two sections, except that the <button> element includes an inline onclick handler to make the function run when the button is pressed. Please don't do this, however. It is bad practice to pollute your HTML wi...
...And 3 more matches
Creating localizable web applications
e pages of your website are going to be localized, you may consider removing links to the English-only pages from the navigation (headers, footers, sidebars) in the localized versions. Define the locale and the direction in the HTML Generate the lang attribute dynamically, depending on the current locale. ...
...direction in the HTML Generate the lang attribute dynamically, depending on the current locale. Use the dir attribute on the <html/> element and consider using a rtl class on <html/> or <
body/> as well, in order to easily change CSS rules like in the example below. Snippet 1. Bad: <html lang="en"> Snippet 2. ...
...="en"> Snippet 2. Good: CSS: html[dir='rtl'] foo { /* RTL-specific rules for the FOO element */ }
body.rtl foo { /* RTL-specific rules for the FOO element */ } HTML/PHP: <?php function isRTL($locale) { $RTL_locales = array('ar', 'fa', 'he'); return in_array($locale, $RTL_locales); } ?> <html lang="<?= $locale?>" dir="<?= isRTL($locale) ? 'rtl' : 'ltr' ?>" > <
body class="<?= $locale?> <?= isRTL($locale) ? ...
...And 3 more matches
NSS API Guidelines
w we accomplish these tasks, it makes it easier for the developer to learn how to use our functions. This section of the document should grow as we develop our API. First some general rules. These rules are derived from existing coding practices inside the security library, since consistency is more important than debates about what might look nice. ...
...e our functions. This section of the document should grow as we develop our API. First some general rules. These rules are derived from existing coding practices inside the security library, since consistency is more important than debates about what might look nice. Public functions should have the form LAYER_
Body(), where LAYER is an all caps prefix for what layer the function lives in, and
Body is concatenated English words, where the beginning letter of each word is capitalized (also known as CamelCase). For Example: LAYER_CapitalizedEnglishWords() or CERT_DestroyCertificate(). Data types and typdefs should have the Form LAYER
Body, with the same definitions for LAYER as public functions, and
Body in camel case English words. For example: LAYERCapitalizedEnglishWords or SECKEYPrivateKe...
...Private functions include functions that may be "public" in a C sense, but are not exported out of the layer. For example: layer_CapitalizedEnglishWords() or pk11_GenerateKeyID(). ...
...And 3 more matches
Using dynamic styling information - Web APIs
l style rules that make up a CSS stylesheet. To get to the style objects from the document, you can use the document.styleSheets property and access the individual objects by index (e.g., document.styleSheets[0] is the first stylesheet defined for the document, etc.). ...
... document.styleSheets[0] is the first stylesheet defined for the document, etc.). Modify a stylesheet rule with CSSOM <html> <head> <title>Modifying a stylesheet rule with CSSOM</title> <style type="text/css">
body { background-color: red; } </style> <script type="text/javascript"> var stylesheet = document.styleSheets[0]; stylesheet.cssRules[0].style.backgroundColor="blue"; </script> </head> <
body> The stylesheet declaration for the
body's background color is modified via JavaScript. </
body> </html> The list of properties available in the DOM from the style property is given on the DOM CSS Properties List page. To modify styles to a document using CSS syntax, one can insert rules or insert <style> tags whose innerHTML property is set to the desired CSS. Modify an element's style The ...
...owing example for the element(s) you want to style. ...
...And 3 more matches
HTMLTableElement.insertRow() - Web APIs
The row does not need to be appended separately as would be the case if Document.createElement() had been used to create the new <tr> element. ...
...The row does not need to be appended separately as would be the case if Document.createElement() had been used to create the new <tr> element. ...
...The row does not need to be appended separately as would be the case if Document.createElement() had been used to create the new <tr> element. ...
...And 3 more matches
Using XMLHttpRequest - Web APIs
take a look at how to use XMLHttpRequest to issue HTTP requests in order to exchange data between the web site and a server. Examples of both common and more obscure use cases for XMLHttpRequest are included. To send an HTTP request, create an XMLHttpRequest object, open a URL, and send the request. After the transaction completes, the object will contain useful information such as the response
body and the HTTP status of the result. 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. The type of request is dicta...
...TML document If you use XMLHttpRequest to get the content of a remote HTML webpage, the responseText property is a string containing the raw HTML. This could prove difficult to manipulate and analyze. There are three primary ways to analyze and parse this raw HTML string: Use the XMLHttpRequest.responseXML property as covered in the article HTML in XMLHttpRequest. Inject the content into the
body of a document fragment via fragment.
body.innerHTML and traverse the DOM of the fragment. RegExp can be used if you always know the content of the HTML responseText beforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the HTML code changes slightly, the method will likely fail. Handling binary dat...
...me + "\"\r\n\r\n" + oField.value + "\r\n" : /* enctype is application/x-www-form-urlencoded or text/plain or method is GET */ fFilter(oField.name) + "=" + fFilter(oField.value) ); } } processStatus(this); } return function (oFormElement) { if (!oFormElement.action) { return; } new SubmitRequest(oFormElement); }; })(); </script> </head> <
body> <h1>Sending forms with pure AJAX</h1> <h2>Using the GET method</h2> <form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Registration example</legend> <p> First name: <input type="text" name="firstname" /><br /> Last name: <input type="text" name="lastname" /> </p> <p> <input type="submit" value="Submit" />...
...And 3 more matches
all - CSS: Cascading Style Sheets
ritednoComputed 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. </blockquote> Phasellus eget velit sagittis. ...
...te"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. </blockquote> Phasellus eget velit sagittis. CSS
body { font-size: small; background-color: #F0F0F0; color: blue; } blockquote { background-color: skyblue; color: red; } Result No all property <blockquote id="quote">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</blockquote> Phasellus eget velit sagittis.
body { font-size: small; background-color: #F0F0F0; color:blue; } blockquote { background-color: skyblue; color: red; } The <blockquote> uses the browser's default styling together with a specific background and text color. It also behaves as a block element: the text that follows it is beneath it. all:unset <blockquote id="quote">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</blockq...
... #F0F0F0; color:blue; } blockquote { background-color: skyblue; color: red; } The <blockquote> uses the browser's default styling together with a specific background and text color. It also behaves as a block element: the text that follows it is beneath it. all:unset <blockquote id="quote">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</blockquote> Phasellus eget velit sagittis.
body { font-size: small; background-color: #F0F0F0; color:blue; } blockquote { background-color: skyblue; color: red; } blockquote { all: unset; } The <blockquote> doesn't use the browser default styling: it is an inline element now (initial value), its background-color is transparent (initial value), but its font-size is still small (inherited value) and its color is blue (inherited value). all...
...And 3 more matches
<table>: The Table element - HTML: Hypertext Markup Language
to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Content categories Flow content Permitted content In this order: an optional <caption> element, zero or more <colgroup> elements, an optional <thead> element, either one of the following: zero or more <t
body> elements one or more <tr> elements an optional <tfoot> element Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts flow content Implicit ARIA role table Permitted ARIA roles Any DOM interface HTMLTableElement Attributes This ele...
.... To achieve a similar effect, use the border-style and border-width properties. rules This enumerated attribute defines where rules, i.e. lines, should appear in a table. It can have the following values: none, which indicates that no rules will be displayed; it is the default value; groups, which will cause the rules to be displayed between row groups (defined by the <thead>, <t
body> and <tfoot> elements) and between column groups (defined by the <col> and <colgroup> elements) only; rows, which will cause the rules to be displayed between rows; columns, which will cause the rules to be displayed between columns; all, which will cause the rules to be displayed between rows and columns. To achieve a similar effect, apply the border property to the appropriate <thead>...
...d <tfoot> elements) and between column groups (defined by the <col> and <colgroup> elements) only; rows, which will cause the rules to be displayed between rows; columns, which will cause the rules to be displayed between columns; all, which will cause the rules to be displayed between rows and columns. To achieve a similar effect, apply the border property to the appropriate <thead>, <t
body>, <tfoot>, <col>, or <colgroup> elements. summary This attribute defines an alternative text that summarizes the content of the table. Use the <caption> element instead. width This attribute defines the width of the table. Use the CSS width property instead. Examples Simple Table <table> <tr> <td>John</td> <td>Doe</td> </tr> <tr> <td>Jane</td> <td>Doe</td> ...
...And 3 more matches
HTTP Messages - HTTP
require any alteration of the APIs or config files applied: it is broadly transparent to the user. HTTP requests, and responses, share similar structure and are composed of: A start-line describing the requests to be implemented, or its status of whether successful or a failure. This start-line is always a single line. An optional set of HTTP headers specifying the request, or describing the
body included in the message. A blank line indicating all meta-information for the request has been sent. An optional
body containing data associated with the request (like content of an HTML form), or the document associated with a response. The presence of the
body and its size is specified by the start-line and HTTP headers. The start-line and HTTP headers of the HTTP message are collectively k...
... HTTP Requests Start line HTTP requests are messages sent by the client to initiate an action on the server. Their start-line contain three elements: An HTTP method, a verb (like GET, PUT or POST) or a noun (like HEAD or OPTIONS), that describes the action to be performed. ...
... are numerous request headers available. They can be divided in several groups: General headers, like Via, apply to the message as a whole. Request headers, like User-Agent, Accept-Type, modify the request by specifying it further (like Accept-Language), by giving context (like Referer), or by conditionally restricting it (like If-None). Entity headers, like Content-Length which apply to the
body of the request. Obviously, there is no such header transmitted if there is no
body in the request.
Body The final part of the request is its
body. Not all requests have one: requests fetching resources, like GET, HEAD, DELETE, or OPTIONS, usually don't need one. Some requests send data to the server in order to update it: as often the case with POST requests (containing HTML form data). Bod...
...And 3 more matches
Closures - JavaScript
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(). The displayName() function is an inner function that is defined inside init() and is available only within the
body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init(). Run the code using this JSFiddle link and notice that the alert() statement within the displayName() function successfully displays the va...
...unction. The function it returns takes a single argument y, and returns the sum of x and y. In essence, makeAdder is a function factory. It creates functions that can add a specific value to their argument. In the above example, the function factory creates two new functions--one that adds five to its argument, and one that adds 10. add5 and add10 are both closures. They share the same function
body definition, but store different lexical environments. In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10. Practical closures Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the ...
...ten in front-end JavaScript is event-based. You define some behavior, and then attach it to an event that is triggered by the user (such as a click or a keypress). The code is attached as a callback (a single function that is executed in response to the event). For instance, suppose we want to add buttons to a page to adjust the text size. ...
...And 3 more matches
Classes - JavaScript
d class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError: const p = new Rectangle(); // ReferenceError class Rectangle {} Class expressions A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's
body. (it can be retrieved through the class's (not an instance's) name property, though). // unnamed let Rectangle = class { constructor(height, width) { this.height = height; this.width = width; } }; console.log(Rectangle.name); // output: "Rectangle" // named let Rectangle = class Rectangle2 { constructor(height, width) { this.height = height; this.width = width; } }; cons...
...; this.width = width; } }; console.log(Rectangle.name); // output: "Rectangle" // named let Rectangle = class Rectangle2 { constructor(height, width) { this.height = height; this.width = width; } }; console.log(Rectangle.name); // output: "Rectangle2" Note: Class expressions are subject to the same hoisting restrictions as described in the Class declarations section. ...
...console.log(Rectangle.name); // output: "Rectangle" // named let Rectangle = class Rectangle2 { constructor(height, width) { this.height = height; this.width = width; } }; console.log(Rectangle.name); // output: "Rectangle2" Note: Class expressions are subject to the same hoisting restrictions as described in the Class declarations section. Class
body and method definitions The
body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructor. Strict mode The
body of a class is executed in strict mode, i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ECMAScript. Constructor The...
...And 3 more matches
stroke-linejoin - SVG: Scalable Vector Graphics
presentation attribute defining the shape to be used at the corners of paths when they are stroked. Note: As a presentation attribute stroke-linejoin can be used as a CSS property. ...
... arcs Note: the arcs value as been introduced in SVG2 and it isn't widely supported yet, see Browser compatibility bellow for details. The arcs value indicates that an arcs corner is to be used to join path segments. The arcs shape is formed by extending the outer edges of the stroke at the join point with arcs that have the same curvature as the outer edges at the join point. ...
... <g id="p"> <path d="M1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3" stroke="pink" fill="none" stroke-width="0.025" /> <circle cx="1" cy="5" r="0.05" fill="pink" /> <circle cx="3" cy="2" r="0.05" fill="pink" /> <circle cx="5" cy="5" r="0.05" fill="pink" /> </g> </svg> bevel The bevel value indicates that a bevelled corner is to be used to join path segments. ...
...And 3 more matches
SVG In HTML Introduction - SVG: Scalable Vector Graphics
w This article and its associated example shows how to use inline SVG to provide a background picture for a form. It shows how JavaScript and CSS can be used to manipulate the picture in the same way you would script regular HTML. ...
...G to provide a background picture for a form. It shows how JavaScript and CSS can be used to manipulate the picture in the same way you would script regular HTML. ...
...ure in the same way you would script regular HTML. ...
...And 3 more matches
Modifying Web Pages Based on URL - Archive of obsolete content
Run jpm init, accepting all the defaults Open the file index.js and add the code above Run jpm run Open ietf.org in the browser window that opens. Below is what you should see. Specifying the Match Pattern Match pattern uses match-pattern syntax. You ca...
... 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", contentScriptFile: "./my-script.js" }); Loading Multiple Content Scripts You can load more than one script, and the scripts can interact directly with each other. For example, You could rewrite my-script.js to use jQuery. $("
body").html("<h1>Page matches ruleset</h1>"); Then download jQuery to add-on's data directory, and load the script and jQuery together (making sure to load jQuery first). // 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...
...criptFile are loaded first. // 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", contentScriptFile: self.data.url("jquery-1.7.min.js"), contentScript: '$("
body").html("<h1>Page matches ruleset</h1>");' }); Note, though, that you can't load a script from a web site. The script must be loaded from data. Communicating With the Content Script Your add-on script and content scripts can't directly access each other's variables or call each other's functions, but they can send each other messages. To send a message from one side to the other, sender calls...
...And 2 more matches
XBL Example - Archive of obsolete content
decrement the value by one, and then call the onset handler to set the value. setPage method Now let's define the 'setPage' method. It will take one parameter, the page number to set the page to. It will need to make sure the page is not out of range and then modify the deck's selectedIndex attribute and the text widget's label attribute. ...
...This is the general mechanism in all XML files that can be used to escape all of the text inside it. That way, you don't have to escape every less-than and greater-than sign inside it. Let's break down the code piece by piece. var thedeck=document.
...des.length; if (newidx<0) return 0; if (newidx>=totalpages) return totalpages; thedeck.setAttribute("selectedIndex",newidx); document.getAnonymousNodes(this)[0].childNodes[1].childNodes[1] .setAttribute("value",(newidx+1)+" of "+totalpages); return newidx; ]]> </
body> </method> This function is called setPage and takes one parameter newidx. The
body of the method has been enclosed inside <![CDATA[ and ]]>. This is the general mechanism in all XML files that can be used to escape all of the text inside it. That way, you don't have to escape every less-than and greater-than sign inside it. Let's break down the code piece by piece. var thedeck=document.getAnonymousNodes(this)[0].childNodes[0]; Get the first element of the anonymous co...
...And 2 more matches
Styling links - Learn web development
ecause the link styles build on one another, for example the styles in the first rule will apply to all the subsequent ones, and when a link is being activated, it is also being hovered over. If you put these in the wrong order, things won't work properly. To remember the order, you could try using a mnemonic like LoVe Fears HAte. ...
...et of rules and add your own declarations to make the links look really cool. Use your imagination, go wild. We are sure you can come up with something cooler and just as functional as our example above. If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to insert the example we showed above. ...
...of a box -- for this example, we'll use this great example from icons8.com. Let's look at some HTML and CSS that will give us the effect we want. ...
...And 2 more matches
Creating hyperlinks - Learn web development
ill have difficulty accessing title information. 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. Inside the HTML
body, add one or more paragraphs or other types of content you already know about. Change some of the content into links. Include title attributes. Block level links As mentioned before, almost any content can be made into a link, even block-level elements. If you have an image you want to make into a link, use the <a> element and reference the image file with the <img> element. <a href="https:/...
...d by the user's email client with no destination address. This is often useful as "Share" links that users can click to send an email to an address of their choosing. Specifying details In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. ...
...you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "
body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term. ...
...And 2 more matches
Drawing graphics - Learn web development
prices, the fallback content could be a static image of the latest stock graph, with alt text saying what the prices are in text. Creating and sizing our canvas Let's start by creating our own canvas that we draw future experiments on to. First make a local copy of our 0_canvas_start.html file, and open it in your text editor. Add the following code into it, just below the opening <
body> tag: <canvas class="myCanvas"> <p>Add suitable fallback here.</p> </canvas> We have added a class to the <canvas> element so it will be easier to select if we have multiple canvases on the page, but we have removed the width and height attributes for now (you could add them back in if you wanted, but we will set them using JavaScript in a below section). Canvases with no explicit width a...
...canvas width and height easily accessible in the width/height variables, as they are useful values to have available for later (for example, if you want to draw something exactly halfway across the width of the canvas). If you save and load your example in a browser now, you'll see nothing, which is fine, but you'll also see scrollbars -- this is a problem for us, which happens because the <
body> element has a margin that, added to our full-window-size canvas, results in a document that's wider than the window. To get rid of the scrollbars, we need to remove the margin and also set overflow to hidden. Add the following into the <head> of your document: <style>
body { margin: 0; overflow: hidden; } </style> The scrollbars should now be gone. Note: You should general...
... and Y values. We also use onmousedown and onmouseup event handlers to change the value of pressed to true when the mouse button is pressed, and back to false again when it is released. ...
...And 2 more matches
Manipulating documents - Learn web development
red. We have created a simple example page at dom-example.html (see it live also). Try opening this up in your browser -- it is a very simple page containing a <section> element inside which you can find an image, and a paragraph with a link inside. ...
... You can see here that each element and bit of text in the document has its own entry in the tree -- each one is called a node. ...
...se of HTML is always the HTML node (other markup vocabularies like SVG and custom XML will have different root elements). Child node: A node directly inside another node. For example, IMG is a child of SECTION in the above example. Descendant node: A node anywhere inside another node. For example, IMG is a child of SECTION in the above example, and it is also a descendant. IMG is not a child of
BODY, as it is two levels below it in the tree, but it is a descendant of
BODY. Parent node: A node which has another node inside it. For example,
BODY is the parent node of SECTION in the above example. Sibling nodes: Nodes that sit on the same level in the DOM tree. For example, IMG and P are siblings in the above example. Text node: A node containing a text string. It is useful to familiarize ...
...And 2 more matches
JS_CompileFunctionForPrincipals
ture is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Create a security-enabled JS function from a text string. ...
...Requires request. ...
... is to be associated. principals JSPrincipals * Pointer to the structure holding the security information for this function. name const char * Name to assign the newly compiled function. nargs unsigned int Number of arguments to pass to the function. argnames const char ** Names to assign to the arguments passed to the function.
body const char * or const jschar * String containing the source code of the function to compile. length size_t The length, in characters, of
body. filename const char * Name of file or URL containing the function. Used to report filename or URL in error messages. lineno unsigned int Line number. Used to report the offending line in the file or URL if...
...And 2 more matches
nsIDOMNSHTMLDocument
ing commandID); Obsolete since Gecko 14.0 DOMString queryCommandValue(in DOMString commandID); void releaseEvents(in long eventFlags); void routeEvent(in nsIDOMEvent evt); void write(); Obsolete since Gecko 2.0 void writeln(); Obsolete since Gecko 2.0 Attributes Attribute Type Description alinkColor DOMString Same as
body.aLink bgColor DOMString Same as
body.bgColor compatMode DOMString Returns "BackCompat" if the document is in Quirks mode or "CSS1Compat" if the document is in Full Standards or Almost Standards mode. Read only. designMode DOMString Set to "on" or "off" to enable or disable editing for the entire document at once. Roughly equivalent to
body.contentEdita...
...t to
body.contentEditable domain DOMString Initially the host name of the document's URL, but may be changed to the parent (but not top-level) domain in order to facilitate data exchange between documents from different sites in the same domain. embeds nsIDOMHTMLCollection Equivalent to getElementsByTagName("embed") Read only. fgColor DOMString Same as
body.text head nsIDOMHTMLHeadElement Returns the first child element of the HTML element that is a HEAD element, or null if there is no HTML or HEAD element. Read only. height long The height of the
body element. Read only. ...
...Read only. ...
...And 2 more matches
Request - Web APIs
in, navigate.) Request.redirect Read only Contains the mode for how redirects are handled. It may be one of follow, error, or manual. Request.referrer Read only Contains the referrer of the request (e.g., client). Request.referrerPolicy Read only Contains the referrer policy of the request (e.g., no-referrer). Request.url Read only Contains the URL of the request. ...
...he mode for how redirects are handled. It may be one of follow, error, or manual. Request.referrer Read only Contains the referrer of the request (e.g., client). Request.referrerPolicy Read only Contains the referrer policy of the request (e.g., no-referrer). Request.url Read only Contains the URL of the request. Request implements
Body, so it also inherits the following properties:
body Read only A simple getter used to expose a ReadableStream of the
body contents.
bodyUsed Read only Stores a Boolean that declares whether the
body has been used in a response yet. Methods Request.clone() Creates a copy of the current Request object. Request implements
Body, so it also has the following methods available to it:
Body.arrayBuffer() Returns a promise that resolves wi...
...adableStream of the
body contents.
bodyUsed Read only Stores a Boolean that declares whether the
body has been used in a response yet. Methods Request.clone() Creates a copy of the current Request object. Request implements
Body, so it also has the following methods available to it:
Body.arrayBuffer() Returns a promise that resolves with an ArrayBuffer representation of the request
body.
Body.blob() Returns a promise that resolves with a Blob representation of the request
body.
Body.formData() Returns a promise that resolves with a FormData representation of the request
body.
Body.json() Returns a promise that resolves with a JSON representation of the request
body.
Body.text() Returns a promise that resolves with an USVString (text) representation of the request
body. ...
...And 2 more matches
Using Service Workers - Web APIs
be rejected -- in this case return a 200 OK status or not -- and then call resolve on success, or reject on failure. The rest of the contents of this function is fairly standard XHR stuff, so we won't worry about that for now. ...
...urn a 200 OK status or not -- and then call resolve on success, or reject on failure. The rest of the contents of this function is fairly standard XHR stuff, so we won't worry about that for now. ...
... worry about that for now. ...
...And 2 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
() { nIntervId = setInterval(flashText, 1000); } function flashText() { var oElem = document.getElementById('my_box'); oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red'; // oElem.style.color == 'red' ? 'blue' : 'red' is a conditional or ternary operator. } function stopTextColor() { clearInterval(nIntervId); } </script> </head> <
body onload="changeColor();"> <div id="my_box"> <p>Hello World</p> </div> <button onclick="stopTextColor();">Stop</button> </
body> </html> Example 3: Typewriter simulation The following example simulates typewriter by first clearing and then slowly typing content into the NodeList that matches a specified group of selectors. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>...
...Example1.play(); oTWExample2.play(); }; </script> <style type="text/css"> span.intLink, a, a:visited { cursor: pointer; color: #000000; text-decoration: underline; } #info { width: 180px; height: 150px; float: right; background-color: #eeeeff; padding: 4px; overflow: auto; font-size: 12px; margin: 4px; border-radius: 5px; /* visibility: hidden; */ } </style> </head> <
body> <p id="copyleft" style="font-style: italic; font-size: 12px; text-align: center;">CopyLeft 2012 by <a href="https://developer.mozilla.org/" target="_blank">Mozilla Developer Network</a></p> <p id="controls" style="text-align: center;">[ <span class="intLink" onclick="oTWExample1.play();">Play</span> | <span class="intLink" onclick="oTWExample1.pause();">Pause</span> | <span class="intLink"...
...nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p> </div> </
body> </html> View this demo in action. See also: clearInterval(). Callback arguments As previously discussed, Internet Explorer versions 9 and below do not support the passing of arguments to the callback function in either setTimeout() or setInterval(). The following IE-specific code demonstrates a method for overcoming this limitation. To use, simply add the following code to the top of your sc...
...And 2 more matches
Web APIs
icatorResponse B BaseAudioContext BasicCardRequest BasicCardResponse BatteryManager BeforeInstallPromptEvent BeforeUnloadEvent BiquadFilterNode Blob BlobBuilder BlobEvent Bluetooth BluetoothAdvertisingData BluetoothCharacteristicProperties BluetoothDevice BluetoothRemoteGATTCharacteristic BluetoothRemoteGATTDescriptor BluetoothRemoteGATTServer BluetoothRemoteGATTService
Body BroadcastChannel BudgetService BudgetState BufferSource ByteLengthQueuingStrategy ByteString C CDATASection CSS CSSConditionRule CSSCounterStyleRule CSSGroupingRule CSSImageValue CSSKeyframeRule CSSKeyframesRule CSSKeywordValue CSSMathProduct CSSMathSum CSSMathValue CSSMediaRule CSSNamespaceRule CSSNumericValue CSSOMString CSSPageRule CSSPositionValue CSSPrimitiveValue ...
...t CanvasImageSource CanvasPattern CanvasRenderingContext2D CaretPosition ChannelMergerNode ChannelSplitterNode CharacterData ChildNode Client Clients Clipboard ClipboardEvent ClipboardItem CloseEvent Comment CompositionEvent ConstantSourceNode ConstrainBoolean ConstrainDOMString ConstrainDouble ConstrainULong ContentIndex ContentIndexEvent ConvolverNode CountQueuingStrategy CrashReport
Body Credential CredentialsContainer Crypto CryptoKey CryptoKeyPair CustomElementRegistry CustomEvent D DOMConfiguration DOMError DOMException DOMHighResTimeStamp DOMImplementation DOMImplementationList DOMLocator DOMMatrix DOMMatrixReadOnly DOMObject DOMParser DOMPoint DOMPointInit DOMPointReadOnly DOMQuad DOMRect DOMRectReadOnly DOMString DOMStringList DOMStringMap DOMTimeStam...
...or DOMException DOMHighResTimeStamp DOMImplementation DOMImplementationList DOMLocator DOMMatrix DOMMatrixReadOnly DOMObject DOMParser DOMPoint DOMPointInit DOMPointReadOnly DOMQuad DOMRect DOMRectReadOnly DOMString DOMStringList DOMStringMap DOMTimeStamp DOMTokenList DOMUserData DataTransfer DataTransferItem DataTransferItemList DedicatedWorkerGlobalScope DelayNode DeprecationReport
Body DeviceLightEvent DeviceMotionEvent DeviceMotionEventAcceleration DeviceMotionEventRotationRate DeviceOrientationEvent DeviceProximityEvent DirectoryEntrySync DirectoryReaderSync DisplayMediaStreamConstraints Document DocumentFragment DocumentOrShadowRoot DocumentTimeline DocumentTouch DocumentType DoubleRange DragEvent DynamicsCompressorNode E EXT_blend_minmax EXT_color_buffer_floa...
...And 2 more matches
ARIA: row role - Accessibility
use grid or treegrid instead. Note: Using the native HTML table element (<table>) along with the table row element (<tr>) whenever possible is strongly encouraged. Associated WAI-ARIA roles, states, and properties Context roles role="rowgroup" An optional contextual row parent, it establishes a relationship between descendant rows. It is a structural equivalent to the thead, tfoot, and t
body elements in an HTML table element. role="table" One of the three possible contexts (along with grid and treegrid) in which you'll find a row, it identifies the row as being part of a non-interactive table structure containing data arranged in rows and columns, similar to the native <table> HTML element. role="grid" One of the three possible contexts (along with table and treegrid) in which y...
...iv role="row" aria-rowindex="18"> <span role="cell">rowgroup</span> <span role="cell">thead</span> </div> <div role="row" aria-rowindex="24"> <span role="cell">term</span> <span role="cell">dt</span> </div> </div> </div> The above is a non-semantic ARIA table with five of 81 rows present in the DOM: One within a table header and four rows within the table
body. ...
...role="cell">term</span> <span role="cell">dt</span> </div> </div> </div> The above is a non-semantic ARIA table with five of 81 rows present in the DOM: One within a table header and four rows within the table
body. The header row, alone in a header rowgroup, has two column headers. The columns are sortable, but not currently sorted, as indicated by the aria-sort property. The table
body is in a separate rowgroup, with four rows currently in the DOM. Because not all the rows are in the DOM, we've included the aria-rowindex property on every row. Best practices Only use table, t
body, thead, tr, th, td, etc., for data table structure. You can add these ARIA roles to ensure accessibility should the native semantics of the table be removed, such as with CSS. A relevant use case for...
...And 2 more matches
Border-image generator - CSS: Cascading Style Sheets
label:hover { cursor: pointer; } .ui-checkbox > input:checked + label { background-image: url("https://mdn.mozillademos.org/files/5681/checked.png"); background-color: #379B4A; } /*************************************************************************************/ /*************************************************************************************/ /* * BORDER IMAGE GENERATOR TOOL */
body { width: 100%; margin: 0 auto; padding: 0 0 20px 0; font-family: "Segoe UI", Arial, Helvetica, sans-serif; /*background: url("https://mdn.mozillademos.org/files/6025/grain.png");*/ border: 1px solid #EEE; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none;...
...width: 100%; margin: 0 auto; padding: 0 0 20px 0; font-family: "Segoe UI", Arial, Helvetica, sans-serif; /*background: url("https://mdn.mozillademos.org/files/6025/grain.png");*/ border: 1px solid #EEE; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; }
body[data-move='X'] { cursor: w-resize !important; }
body[data-move='Y'] { cursor: s-resize !important; } #container { width: 100%; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } [data-draggable='true']:hover { cursor: move; } [data-draggable='true']:hover > * { cursor: default; } /*****************************************************************...
...rComponent(obj, sign) { var slider = document.createElement('div'); var startX = null; var start_value = 0; slider.addEventListener("click", function(e) { document.removeEventListener("mousemove", sliderMotion); setValue(obj.topic, obj.value + obj.step * sign); }); slider.addEventListener("mousedown", function(e) { startX = e.clientX; start_value = obj.value; document.
body.style.cursor = "e-resize"; document.addEventListener("mouseup", slideEnd); document.addEventListener("mousemove", sliderMotion); }); var slideEnd = function slideEnd(e) { document.removeEventListener("mousemove", sliderMotion); document.
body.style.cursor = "auto"; slider.style.cursor = "pointer"; }; var sliderMotion = function sliderMotion(e) { slider.style.cursor = "...
...And 2 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
position='left'] .ui-dropdown-list { left: -100%; top: 0; } .ui-dropdown[data-position='right'] .ui-dropdown-list { left: 100%; top: 0; } .ui-dropdown-list > div { width: 80%; height: 1.6em; margin: 0.3em 0; padding: 0.3em 10%; line-height: 1.6em; } .ui-dropdown-list > div:hover { background: #3490D2; color:#FFF; border-radius: 2px; cursor: pointer; } /* * COLOR PICKER TOOL */
body { width: 100%; height: 100%; margin: 0 auto; font-family: "Segoe UI", Arial, Helvetica, sans-serif; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; }
body[data-dragging="true"] { } /** * Resize Handle */ .resize-handle { width: 10px; height: 10px; background: url("images/resize.png") center center no-repeat; position: absolute; bott...
...rComponent(obj, sign) { var slider = document.createElement('div'); var startX = null; var start_value = 0; slider.addEventListener("click", function(e) { document.removeEventListener("mousemove", sliderMotion); setValue(obj.topic, obj.value + obj.step * sign); }); slider.addEventListener("mousedown", function(e) { startX = e.clientX; start_value = obj.value; document.
body.style.cursor = "e-resize"; document.addEventListener("mouseup", slideEnd); document.addEventListener("mousemove", sliderMotion); }); var slideEnd = function slideEnd(e) { document.removeEventListener("mousemove", sliderMotion); document.
body.style.cursor = "auto"; slider.style.cursor = "pointer"; }; var sliderMotion = function sliderMotion(e) { slider.style.cursor = "...
... var valueX = 0; var valueY = 0; var action = 0; var callback = typeof callback === "function" ? ...
...And 2 more matches
linear-gradient() - CSS: Cascading Style Sheets
dient(red, orange 10% 30%, yellow 50% 70%, green 90%); linear-gradient(red 0%, orange 10% 30%, yellow 50% 70%, green 90% 100%); By default, if there is no color with a 0% stop, the first color declared will be at that point. Similarly, the last color will continue to the 100% mark, or be at the 100% mark if no length has been declared on that last stop. ...
...reen 90%); linear-gradient(red 0%, orange 10% 30%, yellow 50% 70%, green 90% 100%); By default, if there is no color with a 0% stop, the first color declared will be at that point. Similarly, the last color will continue to the 100% mark, or be at the 100% mark if no length has been declared on that last stop. ...
...olor with a 0% stop, the first color declared will be at that point. Similarly, the last color will continue to the 100% mark, or be at the 100% mark if no length has been declared on that last stop. ...
...And 2 more matches
Rich-Text Editing in Mozilla - Developer guides
another site. They are not available at this time. --fumble 18:13, 24 Apr 2005 (PDT) Example 1 The first example is an HTML document setting its own designMode to "On". This makes the entire document editable in Mozilla 1.3. Internet Explorer, however, does not allow javascript to change the current document's designMode. For it to work in Internet Explorer, the contentEditable attribute of the
body tag needs to be set to "true". 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. The example page consists of an iframe, which will...
...nt.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. The example page consists of an iframe, which will be the rich editing area, as well as elements for basic editing commands such as bold/italics/text color. ...
...oc.innerHTML = oContent.toString(); } oDoc.contentEditable = true; } oDoc.focus(); } function printDoc() { if (!validateMode()) { return; } var oPrntWin = window.open("","_blank","width=450,height=470,left=400,top=100,menubar=yes,toolbar=no,location=no,scrollbars=yes"); oPrntWin.document.open(); oPrntWin.document.write("<!doctype html><html><head><title>Print<\/title><\/head><
body onload=\"print();\">" + oDoc.innerHTML + "<\/
body><\/html>"); oPrntWin.document.close(); } </script> <style type="text/css"> .intLink { cursor: pointer; } img.intLink { border: 0; } #toolBar1 select { font-size:10px; } #textBox { width: 540px; height: 200px; border: 1px #000000 solid; padding: 12px; overflow: scroll; } #textBox #sourceText { padding: 0; margin: 0; min-width: 498...
...And 2 more matches
<template>: The Content Template element - HTML: Hypertext Markup Language
DocumentFragment containing the DOM subtree which the template represents. Note that directly using the value of the content could lead to unexpected behavior, see Avoiding DocumentFragment pitfall section below. Examples First we start with the HTML portion of the example. <table id="producttable"> <thead> <tr> <td>UPC_Code</td> <td>Product_Name</td> </tr> </thead> <t
body> <!-- existing data could optionally be included here --> </t
body> </table> <template id="productrow"> <tr> <td class="record"></td> <td></td> </tr> </template> First, we have a table into which we will later insert content using JavaScript code. Then comes the template, which describes the structure of an HTML fragment representing a single table row. Now that the table has...
...created and the template defined, we use JavaScript to insert rows into the table, with each row being constructed using the template as its basis. // Test to see if the browser supports the HTML template element by checking // for the presence of the template element's content attribute. ...
... to insert rows into the table, with each row being constructed using the template as its basis. // Test to see if the browser supports the HTML template element by checking // for the presence of the template element's content attribute. ...
...And 2 more matches
HTML elements reference - HTML: Hypertext Markup Language
eta-related elements, like <base>, <link>, <script>, <style> or <title>. <style> The HTML <style> element contains style information for a document, or part of a document. <title> The HTML Title element (<title>) defines the document's title that is shown in a browser's title bar or a page's tab. Sectioning root Element Description <
body> The HTML <
body> Element represents the content of an HTML document. There can be only one <
body> element in a document. Content sectioning Content sectioning elements allow you to organize the document content into logical pieces. Use the sectioning elements to create a broad outline for your page content, including header and footer navigation, and heading elements to identify secti...
...h1>, <h2>, <h3>, <h4>, <h5>, <h6> The HTML <h1>-<h6> elements represent six levels of section headings. <h1> is the highest section level and <h6> is the lowest. <hgroup> The HTML <hgroup> element represents a multi-level heading for a section of a document. It groups a set of <h1>-<h6> elements. <main> The HTML <main> element represents the dominant content of the <
body> of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. <nav> The HTML <nav> element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections...
.... Common examples of navigation sections are menus, tables of contents, and indexes. <section> The HTML <section> element represents a standalone section -- which doesn't have a more specific semantic element to represent it -- contained within an HTML document. Text content Use HTML text content elements to organize blocks or sections of content placed between the opening <
body> and closing </
body> tags. Important for accessibility and SEO, these elements identify the purpose or structure of that content. Element Description <blockquote> The HTML <blockquote> Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation (see Notes for how to chan...
...And 2 more matches
HEAD - HTTP
The HTTP HEAD method requests the headers that would be returned if the HEAD request's URL was instead requested with the HTTP GET method. 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. A response to a HEAD method should not have a
body. ...
... The HTTP HEAD method requests the headers that would be returned if the HEAD request's URL was instead requested with the HTTP GET method. 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. A response to a HEAD method should not have a
body. ...
...ed if the HEAD request's URL was instead requested with the HTTP GET method. 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. A response to a HEAD method should not have a
body. If it has one anyway, that
body must be ignored: any entity headers that might describe the erroneous
body are instead assumed to describe the response which a similar GET request would have received. ...
...And 2 more matches
Arrow function expressions - JavaScript
) => { statements } (param1, param2, ..., paramN) => expression // equivalent to: => { return expression; } // Parentheses are optional when there's only one parameter name: (singleParam) => { statements } singleParam => { statements } // The parameter list for a function with no parameters should be written with a pair of parentheses. ...
...== window; // or the global object All other strict mode rules apply normally. CORRECTION: START NOTE: the previous statement seems false. Strict mode should prevent creating global variables when assigning to an undeclared identifier in a function. ...
...ect All other strict mode rules apply normally. CORRECTION: START NOTE: the previous statement seems false. Strict mode should prevent creating global variables when assigning to an undeclared identifier in a function. ...
...And 2 more matches
Default parameters - JavaScript
a pull request. Syntax function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { statements } Description In JavaScript, function parameters default to undefined. However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function
body and assign a value if they are undefined. 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. function multiply(a, b) { return a * b } multiply(5, 2) // 10 multiply(5) // NaN ! To guard against this, something like the second line would be used, where b is set to 1 if multipl...
...Now, you can assign 1 as the default value for b in the function head: function multiply(a, b = 1) { return a * b } multiply(5, 2) // 10 multiply(5) // 5 multiply(5, undefined) // 5 Examples Passing undefined vs. other falsy values In the second call in this example, even if the first argument is set explicitly to undefined (though not null o...
...":P", {value:"=^_^="}, arguments, "=^_^="] withoutDefaults.call({value: '=^_^='}); // [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] Scope Effects If default parameters are defined for one or more parameter, then a second scope (Environment Record) is created, specifically for the identifiers within the parameter list. This scope is a parent of the scope created for the function
body. This means that functions and variables declared in the function
body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time ReferenceError. It also means that variables declared inside the function
body using var will mask parameters of the same name, instead of the usual behavior of duplicate var declarations having no effect. The following fu...
...And 2 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
You can <a href="https:...
...a"> fork js13kPWA on GitHub</a> to check its source code.</p> <button id="notifications">Request dummy notifications</button> <section id="content"> // Content inserted in here </section> </main> <footer> <p>(C) js13kGames 2012-2018, created and maintained by <a href="http://end3r.com"> Andrzej Mazur</a> from <a href="http://enclavegames.com">Enclave Games</a>.</p> </footer> </
body> </html> The <head> section contains basic information about the app, including its title, description, and the needed references to its CSS file, web manifest, the main application JavaScript file (app.js, in which the app is initialized) as well as an additional JavaScript code file. The <
body> is split into the <header> (which displays an image) and the
body of the app, which is found inside...
...This script b...
...And 2 more matches
Understanding WebAssembly text format - WebAssembly
der described in the binary format: 0000000: 0061 736d ; WASM_BINARY_MAGIC 0000004: 0100 0000 ; WASM_BINARY_VERSION Adding functionality to your module Ok, that's not very interesting, let's add some executable code to this module. All code in a webassembly module is grouped into functions, which have the following pseudo-code structure: ( func <signature> <locals> <
body> ) The signature declares what the function takes (parameters) and returns (return values). The locals are like vars in JavaScript, but with explicit types declared. The
body is just a linear list of low-level instructions. So this is similar to functions in other languages, even if it looks different because it is an S-expression. Signatures and parameters The signature is a sequence of...
...eturns a 64-bit float would be written like this: (func (param i32) (param i32) (result f64) ... ) After the signature, locals are listed with their type, for example (local i32). Parameters are basically just locals that are initialized with the value of the corresponding argument passed by the caller. Getting and setting locals and parameters Locals/parameters can be read and written by the
body of the function with the local.get and local.set instructions. The local.get/local.set commands refer to the item to be got/set by its numeric index: parameters are referred to first, in order of their declaration, followed by locals in order of their declaration. So given the following function: (func (param i32) (param f32) (local f64) local.get 0 local.get 1 local.get 2) The instruct...
...prefixed by a dollar symbol ($) just before the type declaration. Thus you could rewrite our previous signature like so: (func (param $p1 i32) (param $p2 f32) (local $loc f64) ...) And then could write local.get $p1 instead of local.get 0, etc. (Note that when this text gets converted to binary, though, the binary will contain only the integer.) Stack machines Before we can write a function
body, we have to talk about one more thing: stack machines. Although the browser compiles it to something more efficient, wasm execution is defined in terms of a stack machine where the basic idea is that every type of instruction pushes and/or pops a certain number of i32/i64/f32/f64 values to/from a stack. For example, local.get is defined to push the value of the local it read onto the stack, and ...
...And 2 more matches
Communicating With Other Scripts - Archive of obsolete content
t script uses window.postMessage() to send the message to the page: // content-script (talk.js) window.postMessage("Message from content script", "http://my-domain.org/"); The second argument may be '*' which will allow communication with any domain. Finally, "listen.html" uses window.addEventListener() to listen for messages from the content script: <!DOCTYPE html> <html> <head></head> <
body> <script> window.addEventListener('message', function(event) { window.alert(event.data); // Message from content script }, false); </script> </
body> </html> Messaging From Page Script To Content Script Sending messages from the page script to the content script is just the same, but in reverse. Here "main.js" creates a page-mod that attaches "listen.js" to the w...
...isten.js" to the web page: var data = require("sdk/self").data; var pageMod = require("sdk/page-mod"); pageMod.PageMod({ include: "http://my-domain.org/talk.html", contentScriptFile: data.url("listen.js") }); The web page "talk.html" embeds a script that uses window.postMessage() to send the content script a message when the user clicks a button: <!DOCTYPE html> <html> <head></head> <
body> <script> function sendMessage() { window.postMessage("Message from page script", "http://my-domain.org/"); } </script> <button onclick="sendMessage()">Send Message</button> </
body> </html> Finally, the content script "listen.js" uses window.addEventListener() to listen for messages from the page script: // listen.js window.addEventListener('message', function...
..."); var mod = require("sdk/page-mod"); var self = require("sdk/self"); var pageUrl = self.data.url("page.html") var pageMod = mod.PageMod({ include: pageUrl, contentScriptFile: self.data.url("content-script.js"), contentScriptWhen: "ready" }) tabs.open(pageUrl); The target web page "page.html" includes a button and a page script: <html> <head> <meta charset="utf-8"> </head> <
body> <input id="message" type="button" value="Send a message"/> <script type="text/javascript" src="page-script.js"></script> </
body> </html> The content script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.getElementById("message"); messenger.addEventListener("click", sendCustomEvent, false); function s...
...t the page we are interested in: var data = require("sdk/self").data; var pageMod = require("sdk/page-mod"); pageMod.PageMod({ include: "http://my-domain.org/talk.html", contentScriptFile: data.url("listen.js") }); The web page "talk.html" creates and dispatches a custom DOM event, using initCustomEvent()'s detail parameter to supply the payload: <!DOCTYPE html> <html> <head></head> <
body> <script> function sendMessage() { var event = document.createEvent('CustomEvent'); event.initCustomEvent("addon-message", true, true, { hello: 'world' }); document.documentElement.dispatchEvent(event); } </script> <button onclick="sendMessage()">Send Message</button> </
body> </html> Finally, the content script "listen.js" listens for the new eve...
page-mod - Archive of obsolete content
If you supply the scripts as separate files in the "data" directory, you specify them using with a U...
...Note that this is a very naive implementation, created only for demonstration purposes, and will not work properly in many real-world cases. Attaching Con...
...Note that this is a very naive implementation, created only for demonstration purposes, and will not work properly in many real-world cases. Attaching Content Scripts to Tabs We've seen ...
...Note that this is a very naive implementation, created only for demonstration purposes, and will not work properly in many real-world cases. Attaching Content Scripts to Tabs We've seen that the page-mod API attaches content scripts to documents based on their URL. So...
Index - Archive of obsolete content
. 1899 rule XUL Elements, XUL Reference A rule is used in a template. The children of the rule are used to declare the conditions in which the rule matches and the content that is generated. A rule may contain where, binding and/or action elements. A condition is defined used a where element. For each result that matches all of the conditions, content within the rule's action
body is generated. The bindings element is optional and may specify additional variable bindings to be used. 1900 scale XUL Elements, XUL Reference A scale (sometimes referred to as a "slider") allows the user to select a value from a range. A bar displayed either horizontally or vertically allows the user to select a value by dragging a thumb on the bar. 1901 script ...
...he interfaces available via the tree's view property. The third column indicates whether treeitem element are used. 1937 treecell XUL Elements, XUL Reference A single cell in a tree. This element should be placed inside a treerow. You can set the text for the cell using the label attribute. 1938 treechildren XUL Elements, XUL Reference This element is the
body of the tree. For content trees, the content will be placed inside this element. This element is also used to define container rows in the tree. 1939 treecol XUL Elements, XUL Reference A column of a tree. It displays the column header and holds the size and other information about the column. You can also place splitter elements between the columns to allow column resizing. Y...
...iables. 1945 vbox XUL Elements, XUL Reference A container element which can contain any number of child elements. This is equivalent to the box element, except it defaults to vertical orientation. 1946 where XUL Elements, XUL Reference Indicate a condition that must match for a template result to be used. If the condition is true, the corresponding action
body is generated; otherwise the result is ignored and no content is generated. 1947 window XUL Elements, XUL Reference Describes the structure of a top-level window. It is the root node of a XUL document. It is by default a horizontally oriented box. As it is a box, all box attributes can be used. By default, the window will have a platform-specific frame around it. 1948 ...
...cy generator function statement declares legacy generator functions with the specified parameters. 2015 Legacy generator function expression JavaScript, Language feature, Legacy Iterator, Non-standard, Obsolete, Operator, Reference The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function
body should contain at least one yield expression. 2016 Microsoft JavaScript extensions JavaScript, JavaScript:Microsoft Extensions, Landing page, Non-standard, Reference Microsoft browsers (Internet Explorer, and in a few cases, Microsoft Edge) support a number of special Microsoft extensions to the otherwise standard JavaScript APIs. 2017 @cc_on JavaScript, JavaSc...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
alt attribute as a tooltip's content. The latest W3C HTML specification created the title attribute, which is meant to contain a detailed description of the link. Modern browsers will use the title attribute to display tooltips, and Mozilla only supports showing tooltips for that attribute and not the alt attribute. Entities HTML markup can contain several entities, which the W3C web standards
body has defined. You can reference entities through their numerical or character reference. For example, you can reference the non-breaking space character with   or with its equivalent character reference . Some older browsers, such as Internet Explorer, had such quirks as allowing you to use entities by replacing the ; (semi-colon) character at the end with regular text content:   ...
...ferent browsers execute JavaScript differently. For example, the following code assumes that the div node already exists in the DOM by the time the script block executes: ... <div id="foo">Loading...</div> <script> document.getElementById("foo").innerHTML = "Done."; </script> However, this is not guaranteed. To be sure that all elements exist, you should use the onload event handler on the <
body> tag: <
body onload="doFinish();"> <div id="foo">Loading...</div> <script> function doFinish() { var element = document.getElementById("foo"); element.innerHTML = "Done."; } </script> ... Such timing-related issues are also hardware-related -- slower systems can reveal bugs that faster systems hide. One concrete example is window.open, which opens a new window: <script> functio...
...t support true XHTML, it does not care if no units are specified. If the page is in strict standards mode, and no units are used, then Mozilla ignores the style: <DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>CSS and units example</title> </head> <
body> // works in strict mode <div style="width: 40px; border: 1px solid black;"> Text </div> // will fail in strict mode <div style="width: 40; border: 1px solid black;"> Text </div> </
body> </html> Since the above example has a strict doctype, the page is rendered in strict standards mode. The first div will have a width of 40px, since it uses units, but the ...
...been called, headers and status are available. 3 INTERACTIVE - Downloading, responseText holds the partial data. 4 COMPLETED - Finished with all operations. string responseText String containing the response. DOMDocument responseXML DOM Document containing the response. void send(variant
body) Initiates the request. If
body is defined, it is sent as the
body of the POST request.
body can be an XML document or a string serialized XML document. void setRequestHeader (string headerName, string headerValue) Sets an HTTP request header for use in the HTTP request. Has to be called after open() is called. string status The status code of the HTTP response. ...
Theme changes in Firefox 2 - Archive of obsolete content
utton:hover #print-button:hover:active #reload-button:hover #reload-button:hover:active #searchbar[empty="true"] .searchbar-textbox #stop-button:hover #stop-button:hover:active #urlbar-icons-spacer #urlbar-spacer #urlbar[level="high"] #lock-icon:active #urlbar[level="high"] #lock-icon:hover #urlbar[level="low"] #lock-icon:active #urlbar[level="low"] #lock-icon:hover .autocomplete-tree
body::-moz-tree-cell(suggesthint) .autocomplete-tree
body::-moz-tree-cell-text(suggestfirst, treecolAutoCompleteComment) .autocomplete-tree
body::-moz-tree-cell-text(suggesthint, treecolAutoCompleteComment) .bookmark-item[livemark] .openintabs-menuitem .toolbarbutton-icon .toolbarbutton-menubutton-dropmarker toolbar[iconsize="small"] #back-button .toolbarbutton-menubutton-dropmarker toolbar[icon...
...ds/addFeedReader.xul. #imageBox The box that displays the feed icon. #content Style information for the content area of the window. #siteLabel Style information for the site label. feeds/subscribe.css This is a new file in Firefox 2. It skins the window displayed to subscribe to an RSS feed, which is at browser/feeds/subscribe.xhtml. ...
... safebrowser/browser-protection.css This file, new to Firefox 2, skins browser protection features. The following styles must be implemented to support the window that appears when the user browses to a suspected phishing site: #safebrowsing-dim-area-canvas #safebrowsing-page-canvas #safebrowsing-palm-close #safebrowsing-palm-close-container #safebrowsing-palm-google-lo...
...ager.css The following style needs to be implemented. This file is new in Firefox 2. #engineList treechildren::-moz-tree-image(engineName) Changes in global about.css This is a new file for Firefox 2. It skins the Firefox about box, and needs to provide at least the following styles: #aboutLogoContainer #aboutPageContainer #version The default theme also skins the following styles:
body, html, img, ul, and ul > li. browser.css The following styles that were used in Firefox 1.5 are no longer used in Firefox 2 and have been removed: tab:focus tab[beforeselected="true"] > .tab-image-right tab[selected="true"] > .tab-image-left tab[selected="true"] > .tab-image-middle tab[selected="true"] > .tab-image-right The following styles are new in Firefox 2: .alltabs-item > .me...
Processing XML with E4X - Archive of obsolete content
ces new syntax that only works with E4X XML objects. The syntax is designed to be familiar to JavaScript programmers, but E4X does not provide a direct mapping from XML to native JavaScript objects; just the illusion of one. It is possible to interpolate variables into an XML literal to create an element name (or to create content). var h = 'html'; var text = "Here's some text"; var doc = <{h}><
body>{text}</
body></{h}>; alert(doc.toXMLString()); // Gives <html> <
body>Here's some text</
body> </html> Working with attributes XML literal syntax has a significant advantage over the XML constructor when you need to create markup dynamically. With E4X it is easy to embed dynamic values in markup. Variables and expressions can be used to create attribute values by simply wrapping them with brac...
...))).name); // Alerts Joe Handling namespaces E4X is fully namespace aware. Any XML object that represents a node or attribute provides a name() method which returns a QName object, allowing easy inspection of namespaced elements. ...
...ling namespaces E4X is fully namespace aware. Any XML object that represents a node or attribute provides a name() method which returns a QName object, allowing easy inspection of namespaced elements. ...
...t xml namespace = "http://www.w3.org/1999/xhtml"; // No need now to specify a namespace in the html tag var xhtml = <html><head><title></title></head><
body> <p>text</p></
body></html>; alert(xhtml.head); // No need to specify a namespace on subelements here either Non-default var xhtml = <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Embedded SVG demo</title> </head> <
body> <h1>Embedded SVG demo</h1> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="20" stroke="orange" stroke-width="2px" fill="yellow" /> </svg> </
body> </html>; alert(xhtml.name().localName); // Alerts "html" alert(xhtml.name().uri); // Alerts "http://www.w3.org/1999/xhtml" To access elements that are within a non-default na...
XForms Custom Controls Examples - Archive of obsolete content
to add your own examples. A full example showing a complete form can be found on XForms:Custom_Controls. ...
...mage" extends="chrome://xforms/content/xforms.xml#xformswidget-base"> <content> <html:div> <html:img anonid="content"/> </html:div> </content> <implementation implements="nsIXFormsUIWidget"> <method name="refresh"> <
body> var img = document.getAnonymousElementByAttribute(this, "anonid", "content"); img.setAttribute("src", this.stringValue); return true; </
body> </method> </implementation> </binding> Output Showing XHTML <binding id="output-xhtml" extends="chrome://xforms/content/xforms-xhtml.xml#xformswidget-output"> <content> <children includes="label"/> <xhtml:div class="xf-value" anonid="content"></xhtml:div> <children/> </content> <implementation implements="nsIXFormsUIWidget"> <field name="_domparser">null</field...
... var val = this.stringValue; var newdom = this.domparser.parseFromString(val, "text/xml"); var impnode = document.importNode(newdom.firstChild, true); // Get content node, clean it, and update it var content = document.getAnonymousElementByAttribute(this, "anonid", "content"); if (content.firstChild) { content.removeChild(content.firstChild); } c...
...= this.stringValue; var newdom = this.domparser.parseFromString(val, "text/xml"); var impnode = document.importNode(newdom.firstChild, true); // Get content node, clean it, and update it var content = document.getAnonymousElementByAttribute(this, "anonid", "content"); if (content.firstChild) { content.removeChild(content.firstChild); } content.appendChild(impnode); return true; </
body> </method> </implementation> </binding> ...
Building up a basic demo with Three.js - Game development
he latest Firefox or Chrome. Create a directory to store your experiments in. Save a copy of the latest minimized Three.js library inside your directory. Open the Three.js documentation in a separate tab -- it is useful to refer to. ...
... of the latest minimized Three.js library inside your directory. Open the Three.js documentation in a separate tab -- it is useful to refer to. ...
...he HTML structure we will use: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MDN Games: Three.js demo</title> <style>
body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <
body> <script src="three.min.js"></script> <script> var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; /* all our JavaScript code goes here */ </script> </
body> </html> It contains some basic information like the document <title>, and some CSS to set the width and height of the <canvas> element, that Three.js will insert on the page to 100% to fill the entire available viewport space. The first <script> element includes the Three.js library in the page, and we will write our example code inside the second. There are two helper variables already includ...
...lementation will implement differently than the CSS one. Despite the variety of ways they achieve the goal, the experience will look the same for the user. Thanks to this approach, a fallback can be used, if a desired technology is not supported by the browser. var renderer = new THREE.WebGLRenderer({antialias:true}); renderer.setSize(WIDTH, HEIGHT); renderer.setClearColor(0xDDDDDD, 1); document.
body.appendChild(renderer.domElement); We are creating a new WebGL renderer, setting its size to fit the whole available space on the screen, and appending the DOM structure to the page. You might have noticed the antialias parameter in the first line -- this renders the edges of shapes more smoothly. The setClearColor() method sets our background to a light gray colour, instead of the default black...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
aracters (which would otherwise be interpreted as HTML code), and invisible characters (like non-breaking spaces). You can also use them in place of other characters that are difficult to type with a standard keyboard. 134 Entity header Glossary, WebMechanics An entity header is an HTTP header that can be used in an HTTP request or response, and describes the content of the
body of themessage. Headers like Content-Length, Content-Language, Content-Encoding are entities headers. 135 Event CodingScripting, Glossary Events are assets generated by DOM elements, which can be manipulated by a Javascript code. 136 Exception Beginner, CodingScripting, Glossary An exception is a condition that interrupts normal code execution. In JavaScri...
...r of hypermedia documents on the Web, typically between a browser and a server so that humans can read them. The current version of the HTTP specification is called HTTP/2. 197 HTTP header Glossary, HTTP Header, WebMechanics An HTTP header is a field of an HTTP request or response that passes additional information, altering or precising the semantics of the message or of the
body. Headers are case-insensitive, begins at the start of a line and are immediately followed by a ':' and a value depending of the header itself. The value finish at the next CRLF or at the end of the message. 198 HTTP/2 Glossary, HTTP, Infrastructure, Reference, Web Performance, l10n:priority HTTP/2 is a major revision of the HTTP network protocol 199 HTTP/3 HTTP...
... SOAP Glossary, Infrastructure, SOAP, WebMechanics SOAP (Simple Object Access Protocol) is a protocol for transmitting data in XML format. Firefox removed support for SOAP in 2008. 391 SPA (Single-page application) Glossary, SPA, single-page app An SPA (Single-page application) is a web app implemention that loads only a single web document, and then updates the
body content of that single document via JavaScript APIs such as XMLHttpRequest and Fetch when different content is to be shown. 392 SQL CodingScripting, Database, Glossary, Sql SQL (Structured Query Language) is a descriptive computer language designed for updating, retrieving, and calculating data in table-based databases. 393 SQL Injection Glossary, Security, Sql...
...ol) networks. Common VoIP packages include Skype, Msn Messenger, Yahoo and many more. Everything transferrred through VoIP is digital. It is also known as IP telephony, or broadband telephony. The main reason for using VoIP technology is because of cost. 485 W3C Community, Consortium, Glossary, Intro, W3C, Web consortium The World Wide Web Consortium (W3C) is an international
body that maintains Web-related rules and frameworks. 486 WAI Accessibility, Glossary WAI or Web Accessibility Initiative is an effort by the World Wide Web Consortium (W3C) to improve accessibility for people with various challenges, who may need a nonstandard browser or devices. 487 WCAG Accessibility, Glossary, WCAG, Web Guidelines Web Content Accessibility...
Styling web forms - Learn web development
sitioning. 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. The legend contents will still be spoken in the same way; it is just the visual position that has changed. Note: You could also use the transform property to help you with po...
... Organizing your assets This is where the fun begins! Before we start coding, we need three additional assets: The postcard background -- download this image and save it in the same directory as your working HTML file. A typewriter font: The "Secret Typewriter" font from fontsquirrel.com -- download the TTF file into the same directory as above. A handdrawn font: The "Journal"...
...rectory as before. We are using two different files for each font to maximise browser compatibility; see our Web fonts article for a lot more information. The CSS Now we can dig into the CSS for the example. Add all the code blocks shown below inside the <style> element, one after another. Overall layout First, we prepare by defining our @font-face rules, and all the basic styles set on the <
body> and <form> elements. If the fontsquirrel output was different to what we described above, you can find the correct @font-face blocks inside your downloaded webfont kit, in the stylesheet.css file (you'll need to replace the below @font-face blocks with them, and update the paths to the font files): @font-face { font-family: 'handwriting'; src: url('fonts/journal-webfont.woff2') format('...
...rl('fonts/journal-webfont.woff2') format('woff2'), url('fonts/journal-webfont.woff') format('woff'); font-weight: normal; font-style: normal; } @font-face { font-family: 'typewriter'; src: url('fonts/veteran_typewriter-webfont.woff2') format('woff2'), url('fonts/veteran_typewriter-webfont.woff') format('woff'); font-weight: normal; font-style: normal; }
body { font : 1.3rem sans-serif; padding : 0.5em; margin : 0; background : #222; } form { position : relative; width : 740px; height : 498px; margin : 0 auto; padding: 1em; box-sizing: border-box; background : #FFF url(background.jpg); /* we create our grid */ display : grid; grid-gap : 20px; grid-template-columns : repeat(2, 1fr); grid-template-rows : 10em 1em...
Document and website structure - Learn web development
m/css?family=Open+Sans+Condensed:300|Sonsie+One" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="style.css"> <!-- the below three lines are a fix to get HTML5 semantic elements working in old versions of Internet Explorer--> <!--[if lt IE 9]> <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script> <![endif]--> </head> <
body> <!-- Here is our main header that is used across all the pages of our website --> <header> <h1>Header</h1> </header> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">Our team</a></li> <li><a href="#">Projects</a></li> <li><a href="#">Contact</a></li> </ul> <!-- A Search form is another commmon non-linear way to n...
...f="#">Oh I do like to be beside the sea</a></li> <li><a href="#">Although in the North of England</a></li> <li><a href="#">It never stops raining</a></li> <li><a href="#">Oh well...</a></li> </ul> </aside> </main> <!-- And here is our main footer that is used across all the pages of our website --> <footer> <p>(C)Copyright 2050 by no
body. All rights reversed.</p> </footer> </
body> </html> Take some time to look over the code and understand it -- the comments inside the code should also help you to understand it. We aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound HTML structure, and then laying it out with CSS. We'll wait for this until you start to stu...
...g of all the HTML sectioning elements in detail -- this is something you'll work on gradually as you start to get more experience with web development. You can find a lot of detail by reading our HTML element reference. For now, these are the main definitions that you should try to understand: <main> is for content unique to this page. Use <main> only once per page, and put it directly inside <
body>. Ideally this shouldn't be nested within other elements. <article> encloses a block of related content that makes sense on its own without the rest of the page (e.g., a single blog post). <section> is similar to <article>, but it is more for grouping together a single part of the page that constitutes one single piece of functionality (e.g., a mini map, or a set of article headlines and summar...
...t you can break <article>s up into different <section>s, or <section>s up into different <article>s, depending on the context. <aside> contains content that is not directly related to the main content but can provide additional information indirectly related to it (glossary entries, author biography, related links, etc.). <header> represents a group of introductory content. If it is a child of <
body> it defines the global header of a webpage, but if it's a child of an <article> or <section> it defines a specific header for that section (try not to confuse this with titles and headings). <nav> contains the main navigation functionality for the page. Secondary links, etc., would not go in the navigation. <footer> represents a group of end content for a page. Non-semantic wrappers Sometime...
A first splash into JavaScript - Learn web development
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. See if you can guess it in 10 turns or fewer. We'll tell you if your...
... lowOrHi.textContent = 'Last guess was too high!'; } } guessCount++; guessField.value = ''; } guessSubmit.addEventListener('click', checkGuess); function setGameOver() { guessField.disabled = true; guessSubmit.disabled = true; resetButton = document.createElement('button'); resetButton.textContent = 'Start new game'; document.
body.append(resetButton); resetButton.addEventListener('click', resetGame); } function resetGame() { guessCount = 1; const resetParas = document.querySelectorAll('.resultParas p'); for(let i = 0 ; i < resetParas.length ; i++) { resetParas[i].textContent = ''; } resetButton.parentNode.removeChild(resetButton); guessField.disabled = false; ...
... Let's imagine your boss has given you the following brief for creating this game: I want you to create a simple guess the number type game. It should choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. After each turn the player should be told if they ...
...lete the example functionality. Finishing the game functionality Let's add that setGameOver() function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript: function setGameOver() { guessField.disabled = true; guessSubmit.disabled = true; resetButton = document.createElement('button'); resetButton.textContent = 'Start new game'; document.
body.append(resetButton); resetButton.addEventListener('click', resetGame); } The first two lines disable the form text input and button by setting their disabled properties to true. This is necessary, because if we didn't, the user could submit more guesses after the game is over, which would mess things up. The next three lines generate a new <button> element, set its text label to "Start new ...
Getting started with Svelte - Learn web development
velte. We'll talk about this more in the last article. src: This directory is where the source code for your application lives -- where you'll be creating the code for your app. App.svelte: This is the top-level component of your app. So far it just renders the 'Hello World!' message. main.js: The entry point to our application. It just instantiates the App component and binds it to the
body of our html page. public: This directory contains all the files that will be published in production. favicon.png: This is the favicon for your app. Currently, it's the Svelte logo. index.html: This is the main page of your app. Initially it's just an empty HTML5 page that loads the css files and js bundles generated by Svelte. global.css: This file contains unscoped styles. It'...
...plex reconciliation mechanism. Note the use of : in on:click. That's Svelte's syntax for listening to DOM events. Inspecting main.js: the entry point of our app Let's open src/main.js, which is where the App component is being imported and used. This file is the entry point for our app, and it initially looks like this: import App from './App.svelte'; const app = new App({ target: document.
body, props: { name: 'world' } }); export default app; main.js starts by importing the Svelte component that we are going to use. Then in line 3 it instantiates it, passing an option object with the following properties: target: The DOM element inside which we want the component to be rendered, in this case the <
body> element. props: the values to assign to each prop of the App component...
...As you can see, bundle.js is the only JavaScript file referenced by index.html. There are no other libraries loaded into the web page. This is a much smaller footprint than compiled bundles from other fra...
...As you can see, bundle.js is the only JavaScript file referenced by index.html. There are no other libraries loaded into the web page. This is a much smaller footprint than compiled bundles from other frameworks.
Implementing feature detection - Learn web development
ls. You can look at the different effects these two files have by manually changing the CSS file referred to by the second <link> element, but let's instead implement some JavaScript to automatically swap them as needed. First, remove the contents of the second <link> element's href attribute. We will fill this in dynamically later on. Next, add a <script></script> element at the bottom of your
body (just before the closing </
body> tag). Give it the following contents: const conditional = document.querySelector('.conditional'); const testElem = document.createElement('div'); if (testElem.style.flex !== undefined && testElem.style.flexFlow !== undefined) { conditional.setAttribute('href', 'flex-layout.css'); } else { conditional.setAttribute('href', 'float-layout.css'); } Here we a...
...nt, which is attaching the Google Maps API to the page. Next, fill in the YOUR-API-KEY placeholder text in the second <script> element (as it is now) with a valid Google Maps API key. To get a key, sign in to a Google account, go to the Get a Key/Authentication page, then click the blue Get a Key button and follow the instructions. ...
...he Google Maps API to the page. Next, fill in the YOUR-API-KEY placeholder text in the second <script> element (as it is now) with a valid Google Maps API key. To get a key, sign in to a Google account, go to the Get a Key/Authentication page, then click the blue Get a Key button and follow the instructions. ...
...If it is, we run some code that gets your device's current location, and plots it on a Google Map. Summary This article covered feature detection in a reasonable amount of detail, going through the main concepts and showing you how to both i...
Debugging Frame Reflow
S" \ ./obj-ff-dbg/dist/NightlyDebug.app/Contents/MacOS/firefox-bin > logfile.txt After loading your testcase, the log file will contain the promised information. ...
...Debug.app/Contents/MacOS/firefox-bin > logfile.txt After loading your testcase, the log file will contain the promised information. ...
... After loading your testcase, the log file will contain the promised information. ...
...After loading your testcase, the log file will contain the promised information. ...
IME handling guide
Then, it sends the events and the event target to IMEStateManager. mozilla::IMEStateManager IMEStateManager looks for a TextComposition instance whose native IME con...
...ally in parent process. When IMEStateManager in parent process receives eCompositionStart, it creates TextComposition instance normally. However, if the event target has remote contents, TextComposition::DispatchCompositionEvent() directly sends the event to the remote process instead of dispatching the event into the target DOM tree in the process. That means that even in a parent process, any
body can retrieve TextComposition instance, but it just does nothing in parent process. IMEStateManager works more complicated because IMEStateManagers in each processe need to negotiate about owner ship of managing input context. When a remote process gets focus, temporarily, IMEStateManager in parent process disables IME in the widget. After that, IMEStateManager in the remote process will set pro...
...othing. Therefore, IMEContentObserver is never created while a remote process has focus. When a remote process loses focus, IMEStateManager in parent process notifies IMEStateManager in the remote process of "Stop IME state management". When IMEStateManager::StopIMEStateManagement() is called in the remote process by this, the IMEStateManager forgets all focus information (i.e., that indicates no
body has focus). When IMEStateManager in parent process is notified of pseudo focus move from or to menubar while a remote process has focus, it notifies the remote process of "Menu keyboard listener installed". Then, TabChild calls IMEStateManager::OnInstalledMenuKeyboardListener() in the remote process. Style of each clause The style of each IME selection is managed by LookAndFeel class per platf...
...ause it's not a character which the user wanted to input but we commit it as is. The reason is, inputting an ideographic space causes a composition. Therefore, we cannot distinguish if committing composition is unexpected. If the user uses such old Chinese IME, "intl.ime.remove_placeholder_character_at_commit" pref may be useful but we don't support them anymore in default settings (except if some
body will find a good way to fix this issue). The composition is committed synchronously but with empty string This case may occur on Linux or with some IME on other platforms. If a web application implements autocomplete, committing with different strings especially an empty string it might cause confusion. In this case, TextComposition overwrites the commit string of eCompositionChange event disp...
Mozilla Quirks Mode Behavior
n inside bullet (bug 1049). Add padding if the very first node in an LI is another UL or OL (bug 98636). Obsolete since Gecko 50 List bullets do not inherit the font size of the list (bug 97351). Removed in Firefox 50 (bug 648331). Don't inherit font properties into tables except for font-family. Make TABLE borders gray rather than using the foreground color. Collapse top margin of
BODY and TD and bottom margin of TD. Collapse the bottom or top margins of empty elements (bug 97361). Support <PRE wrap>, <PRE cols>, <PRE width>. Orphaned DD has generated content :before instead of margin (bug 5119). Indent nested DL elements (bug 8749). MAP acts like an inline, not a block. Give floated IMG a 3px margin (bug 58899). Residual style tags' size info does not take...
...y have distinct meaning, and except in shorthands). In quirks mode, the CSS parser allows {} around the contents of style attributes (bug 99554). This behavior is being removed in Firefox 27, for interoperability. (bug 915053) An empty string for the background attribute sets the background URL to empty only in quirks mode. The topmargin, bottommargin, leftmargin, and rightmargin attributes on
BODY are supported only in quirks mode (bug 9258). Obsolete since Gecko 35 (Firefox 35.0 / Thunderbird 35.0 / SeaMonkey 2.32) (bug 95530) This quirk is now HTML5 conform and has been adopted in standards mode. The scrollLeft, scrollTop, scrollWidth, and scrollHeight properties are relative to
BODY in quirks mode (instead of HTML) (bug 211030). HTML (1-7) and CSS (xx-small - xx-large) font sizes a...
...e flow directly in a table cell (no blocks in between), it is assumed that it is not possible to break before and after an image (when otherwise it would be). Obsolete since Gecko 8.0 Prior to Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5) text-decoration in quirks mode had line thickness and position adjusted on descendant text to match the descendant. Tables TD, TH, TR, THEAD, T
BODY, and TFOOT elements have the document background (and color?) applied to them (when the document background is specified in certain ways?) (see also bug 70831). [This may have been an accurate description when written in June 2001, but no longer appears accurate. Should look into TableQuirkColorRule, re-describe, and figure out when it changed.] Obsolete since Gecko 37 The empty-cells property d...
...dle and absmiddle in table cells work in all modes now. In quirks mode, percentage values are supported on the cellspacing attribute, but treated as pixels (bug 106336). Obsolete since Gecko 13.0 (Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10) This quirk has been adopted in standards mode now. Frames In quirks mode marginwidth and marginheight on a FRAME are propagated to the contained
BODY. In a FRAMESET cols/rows specification 0* is treated as 1* (see bug 40383). Obsolete The scrolling attribute on FRAME is handled differently. HTML Parser In quirks mode, we parsed HTML comments in a non-SGML way compatible with other browsers instead of treating "--" as the comment start and end delimiter. Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This quirk ...
Encrypt Decrypt MAC Keys As Session Objects
CK_MECHANISM_TYPE type) { return CryptInit(dk, iv, ivLen, type, CKA_DECRYPT); } /* * Read cryptographic parameters from the header file */ SECStatus ReadFromHeaderFile(const char *fileName, HeaderType type, SECItem *item, PRBool isHexData) { SECStatus rv; PRFileDesc* file; SECItem filedata; SECItem outbuf; unsigned char *non
body; unsigned char *
body; char header[40]; char trailer[40]; outbuf.type = siBuffer; file = PR_Open(fileName, PR_RDONLY, 0); if (!file) { PR_fprintf(PR_STDERR, "Failed to open %s\n", fileName); return SECFailure; } switch (type) { case SYMKEY: strcpy(header, ENCKEY_HEADER); strcpy(trailer, ENCKEY_TRAILER); ...
...(trailer, MACKEY_TRAILER); break; case IV: strcpy(header, IV_HEADER); strcpy(trailer, IV_TRAILER); break; case MAC: strcpy(header, MAC_HEADER); strcpy(trailer, MAC_TRAILER); break; case PAD: strcpy(header, PAD_HEADER); strcpy(trailer, PAD_TRAILER); break; } rv = FileToItem(&filedata, file); non
body = (char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body) ...
...char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(non
body, '\r'); /* maybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); return SECFailure; } } else {
body = non
body; } cleanu...
...ybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); return SECFailure; } } else {
body = non
body; } cleanup: PR_Close(file); HexToBuf(
body, item, isHexData); return SECSuccess; } /* * EncryptAndMac */ SECStatus EncryptAndMac(PRFileDesc *inFile, PRFileDesc *headerFile, PRFileDesc *encFile, PK11SymKey *ek, PK11SymKey *mk, unsigned char *iv, unsigned int ivLen, PRBool ascii) { SECStatus rv; unsigned char ptext[BLOCKSIZE]; unsign...
Encrypt and decrypt MAC using token
CK_MECHANISM_TYPE type) { return CryptInit(dk, iv, ivLen, type, CKA_DECRYPT); } /* * Read cryptographic parameters from the header file */ SECStatus ReadFromHeaderFile(const char *fileName, HeaderType type, SECItem *item, PRBool isHexData) { SECStatus rv; PRFileDesc* file; SECItem filedata; SECItem outbuf; unsigned char *non
body; unsigned char *
body; char header[40]; char trailer[40]; outbuf.type = siBuffer; file = PR_Open(fileName, PR_RDONLY, 0); if (!file) { PR_fprintf(PR_STDERR, "Failed to open %s\n", fileName); return SECFailure; } switch (type) { case SYMKEY: strcpy(header, ENCKEY_HEADER); strcpy(trailer, ENCKEY_TRAILER); ...
...(trailer, MACKEY_TRAILER); break; case IV: strcpy(header, IV_HEADER); strcpy(trailer, IV_TRAILER); break; case MAC: strcpy(header, MAC_HEADER); strcpy(trailer, MAC_TRAILER); break; case PAD: strcpy(header, PAD_HEADER); strcpy(trailer, PAD_TRAILER); break; } rv = FileToItem(&filedata, file); non
body = (char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body) ...
...char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(non
body, '\r'); /* maybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); return SECFailure; } } else {
body = non
body; } cleanu...
...ybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); return SECFailure; } } else {
body = non
body; } cleanup: PR_Close(file); HexToBuf(
body, item, isHexData); return SECSuccess; } /* * EncryptAndMac */ SECStatus EncryptAndMac(PRFileDesc *inFile, PRFileDesc *headerFile, PRFileDesc *encFile, PK11SymKey *ek, PK11SymKey *mk, unsigned char *iv, unsigned int ivLen, PRBool ascii) { SECStatus rv; unsigned char ptext[BLOCKSIZE]; unsign...
Enc Dec MAC Output Public Key as CSR
nsigned int ivLen, CK_MECHANISM_TYPE type) { return CryptInit(dk, iv, ivLen, type, CKA_DECRYPT); } /* * Read cryptographic parameters from the header file */ SECStatus ReadFromHeaderFile(const char *fileName, HeaderType type, SECItem *item, PRBool isHexData) { SECStatus rv; SECItem filedata; SECItem outbuf; unsigned char *non
body; unsigned char *
body; char *header; char *trailer; PRFileDesc *file = NULL; outbuf.type = siBuffer; file = PR_Open(fileName, PR_RDONLY, 0); if (!file) { PR_fprintf(PR_STDERR, "Failed to open %s\n", fileName); return SECFailure; } switch (type) { case PUBKEY: header = PUBKEY_HEADER; trailer = PUBKEY_TRAIL...
...; break; case MAC: header = MAC_HEADER; trailer = MAC_TRAILER; break; case PAD: header = PAD_HEADER; trailer = PAD_TRAILER; break; case LAB: header = LAB_HEADER; trailer = LAB_TRAILER; break; default: PR_Close(file); return SECFailure; } rv = FileToItem(&filedata, file); non
body = (char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ char *trail = NULL; if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); ...
...)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ char *trail = NULL; if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(non
body, '\r'); /* maybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); return SECFailure; } } else { /* headers ...
...T_Strchr(non
body, '\r'); /* maybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); return SECFailure; } } else { /* headers didn't exist */
body = non
body; if (
body) { trail = strstr(++
body, trailer); if (trail != NULL) { PR_fprintf(PR_STDERR, "input has no header but has trailer\n"); PORT_Free(filedata.data); return SECFailure; } } } cleanup: PR_Close(file); ATOB_ConvertAsciiToItem(item,
body); return S...
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
tf(outFile, "%s\n\n", trailer); return SECSuccess; } /* * Read cryptographic parameters from the header file */ SECStatus ReadFromHeaderFile(const char *fileName, HeaderType type, SECItem *item, PRBool isHexData) { SECStatus rv = SECSuccess; PRFileDesc* file = NULL; SECItem filedata; SECItem outbuf; unsigned char *non
body; unsigned char *
body; char *header; char *trailer; outbuf.type = siBuffer; file = PR_Open(fileName, PR_RDONLY, 0); if (!file) { PR_fprintf(PR_STDERR, "Failed to open %s\n", fileName); rv = SECFailure; goto cleanup; } switch (type) { case PUBKEY: header = PUBKEY_HEADER; trailer = PUBKEY_TRAI...
..._ENC_HEADER; trailer = NS_CERT_ENC_TRAILER; break; case CERTVFY: header = NS_CERT_VFY_HEADER; trailer = NS_CERT_VFY_TRAILER; break; case SIG: header = NS_SIG_HEADER; trailer = NS_SIG_TRAILER; break; default: rv = SECFailure; goto cleanup; } rv = FileToItem(&filedata, file); non
body = (char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body...
...data.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(non
body, '\r'); /* maybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } } else { ...
...f (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } } else { /* headers didn't exist */ char *trail = NULL;
body = non
body; if (
body) { trail = strstr(++
body, trailer); if (trail != NULL) { PR_fprintf(PR_STDERR, "input has no header but has trailer\n"); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } } } HexToBuf(
body, item, isHexData); cleanup: if (file) {...
NSS Sample Code Sample_3_Basic Encryption and MACing
CK_MECHANISM_TYPE type) { return CryptInit(dk, iv, ivLen, type, CKA_DECRYPT); } /* * Read cryptographic parameters from the header file */ SECStatus ReadFromHeaderFile(const char *fileName, HeaderType type, SECItem *item, PRBool isHexData) { SECStatus rv; PRFileDesc* file; SECItem filedata; SECItem outbuf; unsigned char *non
body; unsigned char *
body; char header[40]; char trailer[40]; outbuf.type = siBuffer; file = PR_Open(fileName, PR_RDONLY, 0); if (!file) { PR_fprintf(PR_STDERR, "Failed to open %s\n", fileName); return SECFailure; } switch (type) { case SYMKEY: strcpy(header, ENCKEY_HEADER); strcpy(trailer, ENCKEY_TRAILER); ...
...(trailer, MACKEY_TRAILER); break; case IV: strcpy(header, IV_HEADER); strcpy(trailer, IV_TRAILER); break; case MAC: strcpy(header, MAC_HEADER); strcpy(trailer, MAC_TRAILER); break; case PAD: strcpy(header, PAD_HEADER); strcpy(trailer, PAD_TRAILER); break; } rv = FileToItem(&filedata, file); non
body = (char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body) ...
...char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(non
body, '\r'); /* maybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); return SECFailure; } } else {
body = non
body; } cleanu...
...ybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); return SECFailure; } } else {
body = non
body; } cleanup: PR_Close(file); HexToBuf(
body, item, isHexData); return SECSuccess; } /* * EncryptAndMac */ SECStatus EncryptAndMac(PRFileDesc *inFile, PRFileDesc *headerFile, PRFileDesc *encFile, PK11SymKey *ek, PK11SymKey *mk, unsigned char *iv, unsigned int ivLen, PRBool ascii) { SECStatus rv; unsigned char ptext[BLOCKSIZE]; unsign...
sample2
e; } PR_fprintf(outFile, "%s\n", header); PrintAsHex(outFile, buf, len); PR_fprintf(outFile, "%s\n\n", trailer); return SECSuccess; } /* * Read cryptographic parameters from the header file */ SECStatus ReadFromHeaderFile(const char *fileName, HeaderType type, SECItem *item, PRBool isHexData) { SECStatus rv = SECSuccess; PRFileDesc* file = NULL; SECItem filedata; SECItem outbuf; unsigned char *non
body; unsigned char *
body; char *header; char *trailer; outbuf.type = siBuffer; file = PR_Open(fileName, PR_RDONLY, 0); if (!file) { PR_fprintf(PR_STDERR, "Failed to open %s\n", fileName); rv = SECFailure; goto cleanup; } switch (type) { case PUBKEY: header = PUBKEY_HEADER; trailer = PUBKEY_TRAILER; break; case SYMKEY: header = ENCKEY_HEADER; trailer = ENCKEY_TRAILER; break; case MACKEY: header = MACK...
... trailer = PAD_TRAILER; break; case LAB: header = LAB_HEADER; trailer = LAB_TRAILER; break; case CERTENC: header = NS_CERT_ENC_HEADER; trailer = NS_CERT_ENC_TRAILER; break; case CERTVFY: header = NS_CERT_VFY_HEADER; trailer = NS_CERT_VFY_TRAILER; break; case SIG: header = NS_SIG_HEADER; trailer = NS_SIG_TRAILER; break; default: rv = SECFailure; goto cleanup; } rv = FileToItem(&filedata, file); non
body = (char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(non
body, '\r'); /* maybe this is a MAC file */ if (
body) trail...
...iledata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(non
body, '\r'); /* maybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } } else { /* headers didn't exist */ char *trail = NULL;
body = non
body; if (
body) { trail = strstr(++
body, trailer); if (trail != NULL) { PR_fprintf(PR_STDERR, "input has no header but has trailer\n"); PORT_Free(filedata.dat...
...else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } } else { /* headers didn't exist */ char *trail = NULL;
body = non
body; if (
body) { trail = strstr(++
body, trailer); if (trail != NULL) { PR_fprintf(PR_STDERR, "input has no header but has trailer\n"); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } } } HexToBuf(
body, item, isHexData); cleanup: if (file) { PR_Close(file); } return rv; } /* * Generate the private key */ SECKEYPrivateKey * GeneratePrivateKey(KeyType keytype, PK11SlotInfo *slot, int size, int publicExponent, const char *noise, SECKEYPublicKey **pubkeyp, const char *pqgFile, secuPWData *pwdata) { CK_MECHANISM_TYPE mechanism; SECOidTag algtag; PK11RSAGenParams rsaparams; void *params; SECKEYPrivat...
JS_CompileFunction
Obsolete since JSAPI 36This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Creates a JavaScript function from a text string. Syntax JSFunction * JS_CompileFunction(JSContext *cx, JSObject *obj, const char *name, unsigned int nargs, const char **argnames, const char *
body, size_t length, const char *filename, unsigned int lineno); JSFunction * JS_CompileUCFunction(JSContext *cx, JSObject *obj, const char *name, unsigned int nargs, const char **argnames, const jschar *
body, size_t length, const char *filename, unsigned int lineno); Name Type Description cx JSContext * The context in which to compile the function. Require...
...DSAFE build, the caller must be in a request on this JSContext. obj JSObject * Object with which the function is associated. name const char * Name to assign the newly compiled function. nargs unsigned int Number of arguments to pass to the function. argnames const char ** Names to assign to the arguments passed to the function.
body const char * or const jschar * String containing the
body of the function to compile. length size_t The length, in characters, of
body. filename const char * Name of file or URL containing the function. Used to report filename or URL in error messages. lineno unsigned int Line number. Used to report the offending line in the file or URL if an err...
...ptionally associates it with a JS object, obj. JS_CompileUCFunction is the Unicode version of the function. name is the name to assign to the newly created function. nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument. The number of argument names should match the number of arguments specified in nargs.
body is a string containing the source code of the function. length is the length of the source code in characters. filename is the name of the file (or URL) containing the function. This information is used in error messages if an error occurs during compilation. Similarly, lineno is used to report the line number where an error occurred during compilation. If both obj and name are non-null, the ne...
...ect as its value.) On success, JS_CompileFunction and JS_CompileUCFunction return a pointer to the newly compiled function. ...
nsIEditor
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, Output
BodyOnly = 8, // OutputPreformatted = 16, OutputWrap = 32, // OutputFormatFlowed = 64, OutputAbsoluteLinks = 258, // OutputEncodeW3CEntities = 256, OutputCRLineBreak = 512, // OutputLFLineBreak = 1024, OutputNoScriptContent = 2048, // OutputNoFramesContent = 4096, OutputNoFormattingInPre = 8192, // OutputEncodeBasicEntities=16384, OutputEncodeLatin1Entities=32768, // Output...
...= 256, OutputCRLineBreak = 512, // OutputLFLineBreak = 1024, OutputNoScriptContent = 2048, // OutputNoFramesContent = 4096, OutputNoFormattingInPre = 8192, // OutputEncodeBasicEntities=16384, OutputEncodeLatin1Entities=32768, // OutputEncodeHTMLEntities=65536, OutputPersistNBSP=131072 editorAPI.outputToString('text/html', 2); editorAPI.outputToString('text/plain', 4); // output the
body tag,
body children and the html end tag (</html>). // tag name are in lower case with <br>. editorAPI.outputToString('text/html', 8); // XML: all in xml with _moz_dirty="" in new tags, HTML tags are in upper case // application/xhtml+xml format do the same editorAPI.outputToString('text/xml', 2); // the
body is not recognized, everything is printed void outputToStream(in nsIOutput...
...is not marked read-only. isSelectionEditable boolean Read only. true if the current selection anchor is editable; otherwise false. This helps to support cases where only parts of the document are editable, by letting you see if the current selection is in an editable section. rootElement nsIDOMElement Read only. The root editable element, which for a document is its
body. selection nsISelection Read only. The selection/caret for this editor. In the case of a design mode document, this is the same as the window's selection. selectionController nsISelectionController Read only. The selection controller for the current presentation. Methods Native code only!init Initializes the editor's services. [noscript] void init( in ...
...r aSelCon, in unsigned long aFlags ); Parameters doc The document to observe. shell Obsolete since Gecko 5.0 The nsIPresShellPtr representing the presentation shell displaying the document. This parameter was removed in Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2). aRoot The root of the editable section of this document; if it's null, the editor gets its root from document.
body. aSelCon The nsISelectionController object used to get selection location information. This should be null for HTML editors. aFlags A bit mask of flags controlling the editor's behavior. Need to document what the possible values are. ...
nsIMsgCompFields
<< XPCOM API Reference Summary The nsIMsgCompFields interface provides properties for an composition of an outgoing message. ...
...y The nsIMsgCompFields interface provides properties for an composition of an outgoing message. ...
...rcePlainText PRBool from AString hasRecipients PRBool readonly New in Thunderbird 23 Indicates whether something is filled in in the to, cc, or bcc attribute. (bug 68784) messageId char * needToCheckCharset PRBool Indicates whether we need to check if the current DocumentCharset can represent all the characters in the message
body. It should be initialized to true and set to false when 'Send Anyway' is selected by a user. (bug 249530) newsgroups AString newshost char * newspostUrl char * organization AString otherRandomHeaders AString No longer exists - see https://groups.google.com/forum/#!topic/mozilla.dev.apps.thunderbird/s4oFmM8_B28 ...
...oraryFiles OBSOLETE, DO NOT USE ANYMORE to AString useMultipartAlternative PRBool uuEncodeAttachments PRBool Methods Utility Methods PRBool checkCharsetConversion ( out char * fallbackCharset ); nsIMsgRecipientArray SplitRecipients ( in PRUnichar * recipients, in PRBool emailAddressOnly ); void Convert
BodyToPlainText ( ); Attachment Handling Methods void addAttachment ( in nsIMsgAttachment attachment ); void removeAttachment ( in nsIMsgAttachment attachment ); void removeAttachments ( ); Header Methods void setHeader(char* name, char* value); References This interface is the type of the following properties: nsIMsgCompose.compFields, ...
nsISmsDatabaseService
Last changed in Gecko 15.0 (Firefox 15.0 / Thunderbird 15.0 / SeaMonkey 2.12) Implemented by: @mozilla.org/sms/smsdatabaseservice;1. ...
...mozilla.org/sms/smsdatabaseservice;1. ...
...aBo...
...ned long long processId); void clearMessageList(in long listId); void markMessageRead(in long messageId, in boolean value, in long requestId, [optional] in unsigned long long processId) Methods saveReceivedMessage() void saveReceivedMessage( in DOMString aSender, in DOMString a
Body, in unsigned long long aDate ); Parameters aSender A DOMString with the sender of the text message. a
Body A DOMString containing the
body text of the message. aDate The timestamp of the message. saveSentMessage() void saveSentMessage( in DOMString a Receiver, in DOMString a
Body, in unsigned long long aDate ); Parameters aReceiver A DOMString with the receiver of the text message. a
Body A DOMString containing the
body text of the message. aDate The timestamp of the message. getMessage() void...
XPIDL Syntax
are not processed by xpidl. Unlike the C preprocessor, when a file is included multiple times, it acts as if the subsequent includes did not happen; this prevents the need for include guards. XPIDL Syntax (ABNF) The root production here is idl_file. ...
...is included multiple times, it acts as if the subsequent includes did not happen; this prevents the need for include guards. XPIDL Syntax (ABNF) The root production here is idl_file. ...
...s Variable arguments (that makes the ABNF get more wonky) Sequence types Max-length strings Fixed-point numbers "any" and "long double" types. ...
...et more wonky) Sequence types Max-length strings Fixed-point numbers "any" and "long double" types. ...
Web Console remoting - Firefox Developer Tools
To see how the debugger is used in the Web Console code, look in browser/devtools/webconsole/webconsole.js, and search for WebConsoleConnectionProxy. The new Web Console actors are: The WebConsoleActor allows JS evaluation, autocomplete, start/stop listeners, etc. The NetworkEventActor is used for each new network request. The client can request further network event details - like response
body or request headers. To attach to the WebConsoleActor, follow these steps: connectToServer() // the usual listTabs() pickTheTabYouWant() debuggerClient.attachConsole(tab.consoleActor, listeners, onAttachConsole) The listeners argument is an array which specifies listeners you want to start in the web console. These can be: page errors, window.console API messages, network activity, and file a...
...We change the arguments array - we create ObjectActor instances for each object passed as an argument - ...
...amples: { "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, "discardRequest
Body": false }, { "from": "conn0.netEvent14", "type": "networkEventUpdate", "updateType": "responseStart", "response": { "httpVersion": "HTTP/1.1", "status": "304", "statusText": "Not Modified", "headersSize": 194, "discardResponse
Body": true } }, { "from": "conn0.netEvent14", "type": "networkEventUpdate", "updateType": "eventTimings", "totalTime": 1 }, { "from"...
... The getRequestHeaders and other packets To get more details about a network event you can use the following packet requests (and replies). The getRequestHeaders packet: { "to": "conn0.netEvent15", "type": "getRequestHeaders" } { "from": "conn0.netEvent15", "headers": [ { "name": "Host", "value": "localhost" ...
Ambient Light Events - Web APIs
ow object level by using the addEventListener method (using the devicelight event name) or by attaching an event handler to the window.ondevicelight property. Once captured, the event object gives access to the light intensity expressed in lux through the DeviceLightEvent.value property. ...
...dEventListener method (using the devicelight event name) or by attaching an event handler to the window.ondevicelight property. Once captured, the event object gives access to the light intensity expressed in lux through the DeviceLightEvent.value property. ...
...ht event name) or by attaching an event handler to the window.ondevicelight property. Once captured, the event object gives access to the light intensity expressed in lux through the DeviceLightEvent.value property. ...
... handler to the window.ondevicelight property. Once captured, the event object gives access to the light intensity expressed in lux through the DeviceLightEvent.value property. 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 event not supported'); } Specifications Specification Status Comment Ambient Light SensorThe definition of 'Ambient Light Events' in that specification. Candidate Recommendation Initial...
DOMImplementation.createHTMLDocument() - Web APIs
lementation.createHTMLDocument() method creates a new HTML Document. Syntax const newDoc = document.implementation.createHTMLDocument(title) Parameters title Optional (except in IE) A DOMString containing the title to give the new HTML document. Example This example creates a new HTML document and inserts it into an <iframe> in the current document. ...
...itle Optional (except in IE) A DOMString containing the title to give the new HTML document. Example This example creates a new HTML document and inserts it into an <iframe> in the current document. ...
...e 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.documentElement); } The code in lines 4-12 handle creating the new HTML document and inserting some conte...
...ocument into which we'll be injecting the new content. The next two lines handle importing the contents of our new document into the new document's context. Finally, line 20 actually replaces the contents of the frame with the new document's contents. 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. Living Standard Initial definition. ...
Document.createElement() - Web APIs
ning a single property named is, whose value is the tag name of a custom element previously defined via customElements.define(). See Web component example for more details. Return value The new Element. Examples Basic example This creates a new <div> and inserts it before the element with the ID "div1". ...
...ment previously defined via customElements.define(). See Web component example for more details. Return value The new Element. Examples Basic example This creates a new <div> and inserts it before the element with the ID "div1". ...
...ments.define(). See Web component example for more details. Return value The new Element. Examples Basic example This creates a new <div> and inserts it before the element with the ID "div1". ...
...In this case, our custom element extends the HTMLUListElement, which represents the <ul> element. // Create a class for the element class ExpandingList extends HTMLUListElement { constructor() { // Always call super first in ...
Document.getElementById() - Web APIs
(id); Parameters id The ID of the element to locate. The ID is case-sensitive string which is unique within the document; only one element may have any given ID. Return value An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document. ...
...ave any given ID. Return value An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document. Example HTML <html> <head> <title>getElementById example</title> </head> <
body> <p id="para">Some text here</p> <button onclick="changeColor('blue');">blue</button> <button onclick="changeColor('red');">red</button> </
body> </html> JavaScript function changeColor(newColor) { var elem = document.getElementById('para'); elem.style.color = newColor; } Result Usage notes The capitalization of "Id" in the name of this method must be correct for the code to function; getElementByID() is not valid and will not work, however natural it may seem. Unlike some other element-lookup methods such as Document.querySel...
...and Document.querySelectorAll(), getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function. ...
...Note that the id parameter is case-sensitive, so document.getElementById("Main") will return null instead of the element <div id="main"> because "M" and "m" are different for the purposes of this method. Elements not in the document are not searched by getElementById(). When creating an element and assigning it an ID...
Document.hasFocus() - Web APIs
ctive element in the document has focus. Example This example checks whether the document has focus every 300 milliseconds. To test the functionality of hasFocus(), click on the button to open a new window, and try switching between the two pages. ...
...as focus. Example This example checks whether the document has focus every 300 milliseconds. To test the functionality of hasFocus(), click on the button to open a new window, and try switching between the two pages. ...
...k on the button to open a new window, and try switching between the two pages. ...
...check.</p> <button onclick="openWindow()">Open a new window</button> JavaScript function checkPageFocus() { let
body = document.querySelector('
body'); let log = document.getElementById('log'); if (document.hasFocus()) { log.textContent = 'This document has the focus.';
body.style.background = '#fff'; } else { log.textContent = 'This document does not have the focus.';
body.style.background = '#ccc'; } } function openWindow() { window.open('https://developer.mozilla.org/', 'MDN', 'width=640,height=320,left=150,top=150'); } // Check page focus every 300 milliseconds setInterval(checkPageFocus, 300); Result Specification Specification Status Comment HTML Living StandardThe definition of 'Document.hasFocus()' in that specification...
Document - Web APIs
It provides functionality globally to the document, like how to obtain the page's URL and create new elements in the document. ...
...cuments, served with the "text/html" content type, also implement the HTMLDocument interface, whereas XML and SVG documents implement the XMLDocument interface. Constructor Document() Creates a new Document object. Properties This interface also inherits from the Node and EventTarget interfaces. Document.anchorsRead only Returns a list of all of the anchors in the document. Document.
body Returns the <
body> or <frameset> node of the current document. Document.characterSetRead only Returns the character set being used by the document. Document.compatMode Read only Indicates whether the document is rendered in quirks or strict mode. Document.contentType Read only Returns the Content-Type from the MIME Header of the current document. Document.doctypeRead only Returns t...
...ty started. GlobalEventHandlers.ontransitionstart An EventHandler called when a transitionstart event is sent, indicating that a CSS transition has started transitioning. GlobalEventHandlers.onwaiting Is an EventHandler representing the code to be called when the waiting event is raised. Deprecated properties Document.alinkColor Returns or sets the color of active links in the document
body. Document.all Provides access to all elements in the document -- it returns an HTMLAllCollection rooted at the document node. This is a legacy, non-standard property and should not be used. Document.applets Read only Returns an ordered list of the applets within a document. Document.bgColor Gets/sets the background color of the current document. Document.charset Read only Alias ...
...ird 14 / SeaMonkey 2.11). Internet Explorer notes Microsoft defines some non-standard properties: Document.fileSize* Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See MSDN. Internet Explorer does not support all methods from the Node interface in the Document interface: Document.contains As a work-around, document.
body.contains() can be used. Specifications Specification Status Comment DOMThe definition of 'Document' in that specification. Living Standard Intend to supersede DOM 3 HTML Living StandardThe definition of 'Document' in that specification. Living Standard Turn the HTMLDocument interface into a Document extension. CSS Object Model (CSSOM) V...
Using the W3C DOM Level 1 Core - Web APIs
upported in all major browsers, including Mozilla Firefox and Microsoft Internet Explorer, and serves as a base for scripting on the web. What is a DOM tree? A DOM tree is a kind of tree whose nodes represent an HTML or XML document's contents. Each HTML or XML document has a unique DOM tree representation. 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 uses it to display the document. What does the DOM Level 1 Core let me do? The ...
...ay for web page authors to edit the DOM of a document is to use JavaScript to access the document property of the global object. This document object implements the Document interface from the W3C's DOM Level 1 spec. A simple example Suppose the author wants to change the header of the above document and write two paragraphs instead of one. ...
...e global object. This document object implements the Document interface from the W3C's DOM Level 1 spec. A simple example Suppose the author wants to change the header of the above document and write two paragraphs instead of one. The following script would do the job: HTML Content <
body> <input type="button" value="Change this document." onclick="change()"> <h2>Header</h2> <p>Paragraph</p> </
body> JavaScript Content function change() { // document.getElementsByTagName("H2") returns a NodeList of the <h2> // elements in the document, and the first is number 0: var header = document.getElementsByTagName("H2").item(0); // the firstChild of the header is a Text node: header.firstChild.data = "A dynamic document"; // now the header is "A dynamic document". va...
... How can I learn more? Now that you are familiar with the basic concepts of the DOM, you may want to learn about the DOM Level 1 fundamental methods. See also the DOM Level 1 Core specification from the W3C. It's a reasonably clear spec, although it is formal. The mai...
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
nts in the original document are represented in the DOM. This is needed internally so that the editor can preserve formatting of documents. This means that: There will be some text nodes that contain only whitespace, and Some text nodes will have whitespace at the beginning or end. 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 through nodes in the DOM. We'll look at these, and some solutions, later on. How...
...formatting contexts Above we just looked at elements that contain inline elements, and inline formatting contexts. If an element contains at least one block element, then it instead establishes what is called a block formatting context. Within this context, whitespace is treated very differently. Let's take a look at an example to explain how. We've marked the whitespace characters as before. ...
...tain inline elements, and inline formatting contexts. If an element contains at least one block element, then it instead establishes what is called a block formatting context. Within this context, whitespace is treated very differently. Let's take a look at an example to explain how. We've marked the whitespace characters as before. ...
... context, whitespace is treated very differently. Let's take a look at an example to explain how. We've marked the whitespace characters as before. <
body>? ?<div>ooHellooo</div>? ? ooo<div>ooWorld!oo</div>oo? </
body> We have 3 text nodes that contain only whitespace, one before the first <div>, one between the 2 <divs>, and one after the second <div>. This renders like so: Hidden example 2 <
body> <div> Hello </div> <div> World! </div> </
body> We can summarize how the whitespace here is handled as follows (the may be some slight differences in exact behavior between browsers, but this basically works): Because we're inside a block formatting context, everything must be a block, so our 3 text nodes also become blocks, just like the 2 <div>s. Blocks occupy the full widt...
EventTarget.removeEventListener() - Web APIs
nt actions. An EventListener will not be invoked for the event it was registered for after being removed. However, it can be reattached. Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. Example This example shows how to add a mouseover-based event listener that removes a click-based event listener. ...
...ll not be invoked for the event it was registered for after being removed. However, it can be reattached. Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. Example This example shows how to add a mouseover-based event listener that removes a click-based event listener. ...
...e EventTarget has no effect. Example This example shows how to add a mouseover-based event listener that removes a click-based event listener. ...
...ow to add a mouseover-based event listener that removes a click-based event listener. ...
Using files from web applications - Web APIs
d does not include any path information. size The size of the file in bytes as a read-only 64-bit integer. type The MIME type of the file as a read-only string or "" if the type couldn't be determined. ...
...You can do this by styling the input element with display:none and calling the click() method on the <input> element. Consider this HTML: <input type="file"...
... In Firefox, t...
... In Firefox, to have the PDF appear embedded in the iframe (rather than proposed as a downloaded file), the preference pdfjs.disabled must be set to false . <iframe id="viewer"...
HTMLFormElement - Web APIs
image" are omitted for historical reasons) <object> <output> <select> <textarea> No other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. ...
...ut> <select> <textarea> No other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. ...
...info'].value = info; // document.forms["formA"]['form-info'].value would also work } function setFormInfo(f){ // Argument should be a form element reference. ...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement' in that specification. Living Standard The following method has been added: reque...
Web-based protocol handlers - Web APIs
such as in the example below. Example <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <title>Web Protocol Handler Sample - Register</title> <script type="text/javascript"> navigator.registerProtocolHandler("web+burger", "http://www.google.co.uk/?uri=%s", "Burger handler"); </script> </head> <
body> <h1>Web Protocol Handler Sample</h1> <p>This web page will install a web protocol handler for the <code>web+burger:</code> protocol.</p> </
body> </html> Activating Now, anytime the user activates a link that uses the registered protocol, the browser will route the action to the URL supplied when the web application registered. Firefox will, by default, prompt the user before handing off t...
...> Activating Now, anytime the user activates a link that uses the registered protocol, the browser will route the action to the URL supplied when the web application registered. Firefox will, by default, prompt the user before handing off the action. Example <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <title>Web Protocol Handler Sample - Test</title> </head> <
body> <p>Hey have you seen <a href="web+burger:cheeseburger">this</a> before?</p> </
body> </html> Handling The next phase is handling the action. The browser extracts the href from the activated link, combines it with the URL template supplied during handler registration and performs an HTTP GET on the URL. So, using the above examples, the browser would perform a GET on this URL: http://www.goo...
...the desired action. Note:The server side code is passed the entire contents of the href. This means the server side code will have to parse out the protocol from the data. ...
...["value"]; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <title>Web Protocol Handler Sample</title> </head> <
body> <h1>Web Protocol Handler Sample - Handler</h1> <p>This web page is called when handling a <code>web+burger:</code> protocol action. The data sent:</p> <textarea> <?php echo(htmlspecialchars($value, ENT_QUOTES, 'UTF-8')); ?> </textarea> </
body> </html> References http://www.w3.org/TR/2011/WD-html5-20110525/timers.html#custom-handlers See also window.navigator.registerContentHandler nsIProtocolHandler (XUL only) RegisterProtocolHandler Enhancing the Federated Web at Mozilla Webdev Register a custom protocolHandler at Google Developers. ...
Report - Web APIs
all reports in an observer's report queue, and then empties the queue. Via the reports parameter of the callback function passed into the ReportingObserver() constructor upon creation of a new observer instance. This contains the list of reports currently contained in the observer's report queue. By sending requests to the endpoints defined via the Report-To HTTP header. Properties Report.
body Read only The
body of the report, which is a Report
Body object containing the detailed report information. Report.type Read only The type of report generated, e.g. deprecation or intervention. Report.url Read only The URL of the document that generated the report. Methods This interface has no methods defined on it. Events This interface has no events that fire on it. Examples In o...
...We loop over each report using a basic for loop, then iterate over each entry of in the repo...
... Specif...
... let innerListItem = document.createElement('li'); let keyValue = reports[i].
body[key]; innerListItem.textContent = key + ': ' + keyValue; innerList.appendChild(innerListItem); } } } The reports parameter contains an array of all the reports in the observer's report queue. We loop over each report using a basic for loop, then iterate over each entry of in the report's
body using a for...in structure, displaying each key/value pair inside a list item. Specifications Specification Status Comment Reporting APIThe definition of 'Report' in that specification. Editor's Draft ...
Response - Web APIs
tatus code. (e.g., OK for 200). Response.trailers A Promise resolving to a Headers object, associated with the response with Response.headers for values of the HTTP Trailer header. Response.type Read only The type of the response (e.g., basic, cors). Response.url Read only The URL of the response. Response.useFinalURL A boolean indicating whether this is the final URL of the response.
Body Interface Properties Response implements
Body, so it also has the following properties available to it:
Body.
body Read only A simple getter exposing a ReadableStream of the
body contents.
Body.
bodyUsed Read only Stores a Boolean that declares whether the
body has been used in a response yet. Methods Response.clone() Creates a clone of a Response object. Response.error() Returns a...
... only A simple getter exposing a ReadableStream of the
body contents.
Body.
bodyUsed Read only Stores a Boolean that declares whether the
body has been used in a response yet. Methods Response.clone() Creates a clone of a Response object. Response.error() Returns a new Response object associated with a network error. Response.redirect() Creates a new response with a different URL.
Body Interface Methods Response implements
Body, so it also has the following methods available to it:
Body.arrayBuffer() Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer.
Body.blob() Takes a Response stream and reads it to completion. ...
...) Creates a new response with a different URL.
Body Interface Methods Response implements
Body, so it also has the following methods available to it:
Body.arrayBuffer() Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer.
Body.blob() Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob.
Body.formData() Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object.
Body.json() Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the
body text as JSON.
Body.text() Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text).
...ompletion. It returns a promise that resolves with a USVString (text). 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. The fetch() call returns a promise, which resolves to the Response object associated with the resource fetch operation. You'll notice that since we are requesting an image, we need to run
Body.blob (Response implements
Body) to give the response its correct MIME type. const image = document.querySelector('.my-image'); fetch('flowers.jpg').then(function(response) { return response.blob(); }).then(function(blob) { const objectURL = URL.createObjectURL(blob); image.src = objectURL; }); You can also use the Response.Response() constructor to create your own custom Response object: ...
Using Web Workers - Web APIs
leWorker('my_task.js'); // your custom "listeners" myTask.addListener('printStuff', function (result) { document.getElementById('firstLink').parentNode.appendChild(document.createTextNode('The difference is ' + result + '!')); }); myTask.addListener('doAlert', function (time, unit) { alert('Worker waited for ' + time + ' ' + unit + ' :-)'); }); </script> </head> <
body> <ul> <li><a id="firstLink" href="javascript:myTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a></li> <li><a href="javascript:myTask.sendQuery('waitSomeTime');">Wait 3 seconds</a></li> <li><a href="javascript:myTask.terminate();">terminate() the Worker</a></li> </ul> </
body> </html> my_task.js (the worker): var queryableFunctions = { // exampl...
...tent; }),{type: 'text/javascript'}); // Creating a new document.worker property containing all our "text/js-worker" scripts. document.worker = new Worker(window.URL.createObjectURL(blob)); document.worker.onmessage = function(oEvent) { pageLog('Received: ' + oEvent.data); }; // Start the worker. window.onload = function() { document.worker.postMessage(''); }; </script> </head> <
body><div id="logDisplay"></div></
body> </html> The embedded worker is now nested into a new custom document.worker property. It is also worth noting that you can also convert a function into a Blob, then generate an object URL from that blob. For example: function fn2workerURL(fn) { var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'}) return URL.createObjectURL(blob...
...onmessage will define global properties with those names, but they will not register the function to receive messages sent by the web page that created the worker). This starts the recursion, spawning new copies of itself to handle each iteration of the calculation. ...
...After spawning the worker, the onmessage handler is configured to display the results by setting the contents of the div element, and the onerror handler is set to dump the error message. Finally, a message is sent to the worker to start it. Try this example live. P...
Window: unload event - Web APIs
will happen before child frame unload (see example below). ...
...w). ...
... Specifications Specification Status Comment UI EventsThe definition of 'unload' in that specification. ...
... Specifications Specification Status Comment UI EventsThe definition of 'unload' in that specification. Working Draft ...
XRView.eye - Web APIs
during gameplay. When rendering that eye, if the flag is true, that view is skipped instead of being rendered. ...
...g is true, that view is skipped instead of being rendered. ...
...ndered. ...
...l.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer); gl.clearColor(0,0, 0, 1.0); gl.clearDepth(1.0); gl.clear(gl.COLOR_BUFFER_BIT, gl.DEPTH_BUFFER_BIT); for (let view of xrPose.views) { let skipView = false; if (view.eye == "left" &&
body.leftEye.injured) || skipView = updateInjury(
body.leftEye); } else if (view.eye == "right" &&
body.rightEye.injured) { skipView = updateInjury(
body.rightEye); } if (!skipView) { let viewport = glLayer.getViewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); renderScene(gl, view); } } For each of the views, the value of eye is checked and if it's either left or right, we check to see if the
body.leftEye.injured or
body.rightEye.injured property is true; if so, we call a function updateInjur...
ARIA: cell role - Accessibility
is a row of cells within a tabular structure. A row contains one or more cells, grid cells, column headers, or row headers within a grid, table or treegrid, and optionally within a rowgroup. role="rowgroup" Row is a required cell parent. Rowgroup is an optional contextual row parent. It establishes a relationship between descendant rows. It is a structural equivalent to the thead, tfoot, and t
body elements in an HTML table element. role="table" One of the three possible contexts (along with grid and treegrid) in which you'll find a row containing cells. Table identifies the cell as being part of a non-interactive table structure containing data arranged in rows and columns, similar to the native HTML <table> element. role="grid" One of the three possible contexts (along with table and...
...l" aria-rowindex="18">rowgroup</span> <span role="cell" aria-rowindex="18">thead</span> </div> <div role="row"> <span role="cell" aria-rowindex="24">term</span> <span role="cell" aria-rowindex="24">dt</span> </div> </div> </div> The above is a non-semantic ARIA table with five of 81 rows present in the DOM: one within a table header and four rows within the table
body. Because not all the rows are in the DOM, we've included the aria-rowindex property on every cell. If no cells spanned more than one row or column, the aria-rowindex could have been placed on the row rather than the row's individual cells. Best practices Only use table, t
body, thead, tr, th, td, etc., for data table structure. You can add ARIA roles to ensure accessibility should the native sem...
...ble_desc" aria-rowcount="81"> <caption id="semantic_elements_table_desc">Semantic Elements to use instead of ARIA's roles</caption> <thead role="rowgroup"> <tr role="row"> <th role="columnheader" aria-sort="none" aria-rowindex="1">ARIA Role</th> <th role="columnheader" aria-sort="none" aria-rowindex="1">Semantic Element</th> </tr> </thead> <t
body role="rowgroup"> <tr role="row"> <td role="cell" aria-rowindex="11">header</td> <td role="cell" aria-rowindex="11">h1</td> </tr> <tr role="row"> <td role="cell" aria-rowindex="16">header</td> <td role="cell" aria-rowindex="16">h6</td> </tr> <tr role="row"> <td role="cell" aria-rowindex="18">rowgroup</td> <td role="cell"...
...The ARIA roles are not necessary if the native semantics of the table, and therefore the table rows, have not been altered, such as through the display property. Added benefits none Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'ARIA Cell Role' in that spe...
:not() - CSS: Cascading Style Sheets
this pseudo-class. For example, :not(*) matches any element which is not an element, which is obviously nonsense, so the accompanying rule will never be applied. This pseudo-class can increase the specificity of a rule. For example, #foo:not(#bar) will match the same element as the simpler #foo, but has a higher specificity. :not(.foo) will match anything that isn't .foo, including <html> and <
body>. This selector only applies to one element; you cannot use it to exclude all ancestors. For instance,
body :not(table) a will still apply to links inside of a table, since <tr> will match with the :not() part of the selector. 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; } /*...
... still apply to links inside of a table, since <tr> will match with the :not() part of the selector. ...
... Working Draft Extends its argument ...
...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` */ /* Note that this syntax is not well supported yet. */
body :not(.crazy, .fancy) { font-family: sans-serif; } Result Specifications Specification Status Comment Selectors Level 4The definition of ':not()' in that specification. Working Draft Extends its argument to allow some non-simple selectors. Selectors Level 3The definition of ':not()' in that specification. Recommendation Initial definition. ...
@page - CSS: Cascading Style Sheets
s, orphans, widows, and page breaks of the document. Attempts to change any other CSS properties will be ignored. The @page at-rule can be accessed via the CSS object model interface CSSPageRule. Note: The W3C is discussing how to handle viewport-related <length> units, vh, vw, vmin, and vmax. Meanwhile do not use them within a @page at-rule. ...
...o change any other CSS properties will be ignored. The @page at-rule can be accessed via the CSS object model interface CSSPageRule. Note: The W3C is discussing how to handle viewport-related <length> units, vh, vw, vmin, and vmax. Meanwhile do not use them within a @page at-rule. ...
... will be ignored. The @page at-rule can be accessed via the CSS object model interface CSSPageRule. Note: The W3C is discussing how to handle viewport-related <length> units, vh, vw, vmin, and vmax. Meanwhile do not use them within a @page at-rule. ...
...e can be accessed via the CSS object model interface CSSPageRule. Note: The W3C is discussing how to handle viewport-related <length> units, vh, vw, vmin, and vmax. Meanwhile do not use them within a @page at-rule. ...
Color picker tool - CSS: Cascading Style Sheets
epeat; } .ui-input-slider-name { width: 90px; padding: 0 10px 0 0; text-align: right; text-transform: lowercase; } .ui-input-slider-btn-set { width: 25px; background-color: #2C9FC9; border-radius: 5px; color: #FFF; font-weight: bold; line-height: 14px; text-align: center; } .ui-input-slider-btn-set:hover { background-color: #379B4A; cursor: pointer; } /* * COLOR PICKER TOOL */
body { max-width: 1000px; margin: 0 auto; font-family: "Segoe UI", Arial, Helvetica, sans-serif; box-shadow: 0 0 5px 0 #999; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; } /** * Resize Handle */ .resize-handle { width: 10px; height: 10px; background...
...rComponent(obj, sign) { var slider = document.createElement('div'); var startX = null; var start_value = 0; slider.addEventListener("click", function(e) { document.removeEventListener("mousemove", sliderMotion); setValue(obj.topic, obj.value + obj.step * sign); }); slider.addEventListener("mousedown", function(e) { startX = e.clientX; start_value = obj.value; document.
body.style.cursor = "e-resize"; document.addEventListener("mouseup", slideEnd); document.addEventListener("mousemove", sliderMotion); }); var slideEnd = function slideEnd(e) { document.removeEventListener("mousemove", sliderMotion); document.
body.style.cursor = "auto"; slider.style.cursor = "pointer"; }; var sliderMotion = function sliderMotion(e) { slider.style.cursor = "...
... parent ==========*/ var UIComponent = (function UIComponent() { function makeResizable(elem, axis) { var valueX = 0; var valueY = 0; var action = 0; var resizeStart = function resizeStart(e) { e.stopPropagation(); e.preventDefault(); if (e.button !== 0) return; valueX = e.clientX - elem.clientWidth; valueY = e.clientY - elem.clientHeight; document.
body.setAttribute('data-resize', axis); document.addEventListener('mousemove', mouseMove); document.addEventListener('mouseup', resizeEnd); }; var mouseMove = function mouseMove(e) { if (action >= 0) elem.style.width = e.clientX - valueX + 'px'; if (action <= 0) elem.style.height = e.clientY - valueY + 'px'; }; var resizeEnd = function resizeEnd(e) { if (e.b...
...document.addEventListener('mousemove', mouseMove); document.addEventListener('mouseup', resizeEnd); }; var mouseMove = function mouseMove(e) { if (action >= 0) elem.style.width = e.clientX - valueX + 'px'; if (action <= 0) elem.style.height = e.clientY - valueY + 'px'; }; var resizeEnd = function resizeEnd(e) { if (e.button !== 0) return; document.
body.removeAttribute('data-resize', axis); document.removeEventListener('mousemove', mouseMove); document.removeEventListener('mouseup', resizeEnd); }; var handle = document.createElement('div'); handle.className = 'resize-handle'; if (axis === 'width') action = 1; else if (axis === 'height') action = -1; else axis = 'both'; handle.className = 'resize-handle'; handle...
Challenge solutions - Developer guides
ng"); } Lists Lower Roman numerals Challenge Add a rule to your stylesheet, to number the oceans using Roman numerals from i to v. Solution Define a rule for list items to use the lower-roman list style: li { list-style: lower-roman; } Capital letters Challenge Change your stylesheet to identify the headings with capital letters in parentheses. ...
...n Define a rule for list items to use the lower-roman list style: li { list-style: lower-roman; } Capital letters Challenge Change your stylesheet to identify the headings with capital letters in parentheses. Solution Add a rule to the
body element (parent of the headings) to reset a new counter, and one to display and increment the counter on the headings: /* numbered headings */
body {counter-reset: headnum;} h3:before { content: "(" counter(headnum, upper-latin) ") "; counter-increment: headnum; } Boxes Ocean border Challenge Add one rule to your stylesheet, making a wide border all around the oceans in a color that reminds you of the sea. Solution The following rule achieves this effect: ul { border: 10px solid lightblue; width: 100px; } Layout ...
... Challenge Add one rule to your stylesheet, making a wide border all around the oceans in a color that reminds you of the sea. Solution The following rule achieves this effect: ul { border: 10px solid lightblue; width: 100px; } Layout Default image position Fixed image position Challenge Change your sample document, doc2.html, adding this tag to it near the end, just before </
BODY>: <IMG id="fixed-pin" src="Yellow-pin.png" alt="Yellow map pin"> Predict where the image will appear in your document. Then refresh your browser to see if you were correct. Solution The image appears to the right of the second list. Challenge Add a rule to your stylesheet that places the image in the top right of your document. Solution The following rule achieves the desired result: #f...
...s the image in the top right of your document. Solution The following rule achieves the desired result: #fixed-pin { position:fixed; top: 3px; right: 3px; } Tables Borders on data cells only Challenge Change the stylesheet to make the table have a green border around only the data cells. Solution The following rule puts borders around only <td> elements that are inside the <t
body> element of the table with id=demo-table: #demo-table t
body td { border:1px solid #7a7; } Media Separate print style file Challenge Move the print-specific style rules to a separate CSS file and import them into your style4.css stylesheet. Solution Cut and paste the lines between /* print only */ and /* end print only */ into a file named style4_print.css. In style4.css, add the fo...
<a>: The Anchor element - HTML: Hypertext Markup Language
URLs Email addresses with mailto: URLs While web browsers may not support other URL schemes, web sites can with registerProtocolHandler() hreflang Hints at the human language of the linked URL. No built-in functionality. Allowed values are the same as the global lang attribute. ping A space-separated list of URLs. When the link is followed, the browser will send POST requests with the
body PING to the URLs. Typically for tracking. referrerpolicy How much of the referrer to send when following the link. See Referrer-Policy for possible values and their effects. rel The relationship of the linked URL as space-separated link types. target Where to display the linked URL, as the name for a browsing context (a tab, window, or <iframe>). The following keywords have special meaning...
...can use href="#top" or the empty fragment (href="#") to link to the top of the current page, as defined in the HTML specification. Linking to an email address To create links that open in the user's email program to let them send a new message, use the mailto: scheme: <a href="mailto:nowhere@mozilla.org">Send email to nowhere</a> For details about mailto: URLs, such as including a subject or
body, see Email links or RFC 6068. Linking to telephone numbers <a href="tel:+49.157.0156">+49 157 0156</a> <a href="tel:+1(555)5309">(555) 5309</a> tel: link behavior varies with device capabilities: Cellular devices autodial the number. Most operating systems have programs that can make calls, like Skype or FaceTime. Websites can make phone calls with registerProtocolHandler, such as web.sky...
... </header> <main id="content"> <!-- The skip link jumps to here --> .skip-link { position: absolute; top: -3em; background: #fff; } .skip-link:focus { top: 0; } Skip links let keyboard use...
...nd Hypertext - Hypertext Links MDN / Understanding WCAG, Guideline 3.2 G200: Opening new windows and tabs from a link only when necessary G201: Giving users advanced warning when opening a new window Skip links A skip link is a link placed as early as possible in <
body> content that points to the beginning of the page's main content. Usually, CSS hides a skip link offscreen until focused. <
body> <a href="#content">Skip to main content</a> <header> ... </header> <main id="content"> <!-- The skip link jumps to here --> .skip-link { position: absolute; top: -3em; background: #fff; } .skip-link:focus { top: 0; } Skip links let keyboard users bypass content repeated throughout multiple pages, such as header navigation. Skip links are especially useful for people who...
<main> - HTML: Hypertext Markup Language
The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. The source for this interactive example is stored in a GitHub repository. If 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 document mustn't have more than one <main> element that doesn't have the hidden attribute specified. Content categories Flow content, palpable content. Permitted content Flow content. ...
...notes The content of a <main> element should be unique to the document. Content that is repeated across a set of documents or document sections such as sidebars, navigation links, copyright information, site logos, and search forms shouldn't be included unless the search form is the main function of the page. <main> doesn't contribute to the document's outline; that is, unlike elements such as <
body>, headings such as <h2>, and such, <main> doesn't affect the DOM's concept of the structure of the page. It's strictly informative. 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>... </p> ...
... legacy browser support concerns. Skip navigation Skip navigation, also known as "skipnav", is a technique that allows an assistive technology user to quickly bypass large sections of repeated content (main navigation, info banners, etc.). This lets the user access the main content of the page faster. Adding an id attribute to the <main> element lets it be a target of a skip navigation link. ...
...rge sections of repeated content (main navigation, info banners, etc.). This lets the user access the main content of the page faster. Adding an id attribute to the <main> element lets it be a target of a skip navigation link. <
body> <a href="#main-content">Skip to main content</a> <!-- navigation and header content --> <main id="main-content"> <!-- main page content --> </main> </
body> WebAIM: "Skip Navigation" Links Reader mode Browser reader mode functionality looks for the presence of the <main> element, as well as heading and content sectioning elements when converting content into a specialized reader view. Building websites for Safari Reader Mode and other reading apps. Specifications Specification Status Comment HTML Living Stand...
<nextid>: The NeXT ID element (Obsolete) - HTML: Hypertext Markup Language
inue its naming convention. Imagine the web author opens the document for further editing. They want to add a couple new sections after the second section, appending four more sections at the end. When opening the document, the NeXT editor finds and reads this <NEXTID N="z8"> tag, and now knows to give the first of these new sections the name of z8 in the Table of Contents, and z14 to the content
body. This might look like this: <HTML> <HEAD> <TITLE> ... whatever ... </TITLE> <LINK, META, BASE, etc. as applicable for the head of this document> <NEXTID N="z20"> </HEAD> <
BODY> <A NAME="z0" HREF="#z4">FIRST SECTION HEADING</A> <A NAME="z1" HREF="#z5">SECOND SECTION HEADING</A> <A NAME="z8" HREF="#z14">NEWLY INSERTED THIRD SECTION HEADI...
... (NOW SIXTH) SECTION HEADING</A></H1><P> ... whatever ... </P> <H2><A NAME="z16">SEVENTH SECTION HEADING</A></H1><P> ... whatever ... </P> <H2><A NAME="z17">EIGHTH SECTION HEADING</A></H1><P> ... whatever ... </P> <H2><A NAME="z18">NINTH SECTION HEADING</A></H1><P> ... whatever ... </P> <H2><A NAME="z19">TENTH SECTION HEADING</A></H1><P> ... whatever ... </P> </
BODY> </HTML> They then forward a copy of this document to someone with a NeXT editor, and they delete sections z7 and z19, add ten more, z20 through z29, and then delete paragraphs z24 and z29. So then the NEXTID value is z30 when it's returned modified: <HTML> <HEAD> <TITLE> ... whatever ... </TITLE> <LINK, META, BASE, etc. as applicable for the head of this document> ...
...y of this document to someone with a NeXT editor, and they delete sections z7 and z19, add ten more, z20 through z29, and then delete paragraphs z24 and z29. So then the NEXTID value is z30 when it's returned modified: <HTML> <HEAD> <TITLE> ... whatever ... </TITLE> <LINK, META, BASE, etc. ...
...ON HEADING</A></H1><P> ... whatever ... </P> <H2><A NAME="z25">NEW NINTH SECTION HEADING</A></H1><P> ... whatever ... </P> <H2><A NAME="z26">NEW TENTH SECTION HEADING</A></H1><P> ... whatever ... </P> <H2><A NAME="z27">NEW ELENENTH SECTION HEADING</A></H1><P> ... whatever ... </P> <H2><A NAME="z28">NEW TWELFTH SECTION HEADING</A></H1><P> ... whatever ... </P> </
BODY> </HTML> HTML Reference Working NEXTID Tag Element Example 5.2.6. Next Id: NEXTID ...
Content-Disposition - HTTP
In a regular HTTP response, the Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally. In a multipart/form-data
body, the HTTP Content-Disposition general header is a header that can be used on the subpart of a multipart
body to give information about the field it applies to. The subpart is delimited by the boundary defined in the Content-Type header. Used on the
body itself, Content-Disposition has no effect. The Content-Disposition header is defined in the larger context of MIME messages for e-mail, but only a subset of the possible parameters apply to HTTP forms and POST requests. Only the value form-data, as wel...
...on the
body itself, Content-Disposition has no effect. The Content-Disposition header is defined in the larger context of MIME messages for e-mail, but only a subset of the possible parameters apply to HTTP forms and POST requests. Only the value form-data, as well as the optional directive name and filename, can be used in the HTTP context. ...
... The Content-Disposition header is defined in the larger context of MIME messages for e-mail, but only a subset of the possible parameters apply to HTTP forms and POST requests. Only the value form-data, as well as the optional directive name and filename, can be used in the HTTP context. Header type Response header (for the main
body) General header (for a subpart of a multipart
body) Forbidden header name no Syntax As a response header for the main
body The first parameter in the HTTP context is either inline (default value, indicating it can be displayed inside the Web page, or as the Web page) or attachment (indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the filename parameters if present). ...
...ine (default value, indicating it can be displayed inside the Web page, or as the Web page) or attachment (indicating it should be downloaded; most browsers presenting a 'Save as' dialog, prefilled with the value of the filename parameters if present). Content-Disposition: inline Content-Disposition: attachment Content-Disposition: attachment; filename="filename.jpg" As a header for a multipart
body The first parameter in the HTTP context is always form-data. Additional parameters are case-insensitive and have arguments that use quoted-string syntax after the '=' sign. Multiple parameters are separated by a semi-colon (';'). Content-Disposition: form-data Content-Disposition: form-data; name="fieldName" Content-Disposition: form-data; name="fieldName"; filename="filename.jpg" Directives ...
DELETE - HTTP
A 204 (No Content) status code if the action has been enacted and no further information is to be supplied. ...
... A 204 (No Content) status code if the action has been enacted and no further information is to be supplied. ...
... A 202 (Accepted) status code if the action will likely succeed but has not yet been enacted. A 204 (No Content) status code if the action has been enacted and no further information is to be supplied. ...
...he action will likely succeed but has not yet been enacted. A 204 (No Content) status code if the action has been enacted and no further information is to be supplied. ...
PATCH - HTTP
side-effects on other resources. To find out whether a server supports PATCH, a server can advertise its support by adding it to the list in the Allow or Access-Control-Allow-Methods (for CORS) response headers. Another (implicit) indication that PATCH is allowed, is the presence of the Accept-Patch header, which specifies the patch document formats accepted by the server. ...
... whether a server supports PATCH, a server can advertise its support by adding it to the list in the Allow or Access-Control-Allow-Methods (for CORS) response headers. Another (implicit) indication that PATCH is allowed, is the presence of the Accept-Patch header, which specifies the patch document formats accepted by the server. 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 t...
... HTTP/1.1 204 No Content Content-Location: /file.txt ETag: "e0023aa4f" Specifications Specification Title RFC 5789: PATCH PATCH Method for HTTP ...
... HTTP/1.1 204 No Content Content-Location: /file.txt ETag: "e0023aa4f" Specifications Specification Title RFC 5789: PATCH PATCH Method for HTTP ...
POST - HTTP
The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect (that is no side effect), where successive identical POST may have additional effects, like passing an order several times. A POST request is typically sent via an HTML form and results in a change on the server. ...
...ements: application/x-www-form-urlencoded: the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. Non-alphanumeric characters in both keys and values are percent encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead) multipart/form-data: each value is sent as a block of data ("
body part"), with a user agent-defined delimiter ("boundary") separating each part. The keys are given in the Content-Disposition header of each part. text/plain When the POST request is sent via a method other than an HTML form -- like via an XMLHttpRequest -- the
body can take any type. As described in the HTTP 1.1 specification, POST is designed to allow a uniform method to cover the following f...
...low a uniform method to cover the following functions: Annotation of existing resources Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; Adding a new user through a signup modal; Providing a block of data, such as the result of submitting a form, to a data-handling process; Extending a database through an append operation. ...
...unctions: Annotation of existing resources Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; Adding a new user through a signup modal; Providing a block of data, such as the result of submitting a form, to a data-handling process; Extending a database through an append operation. ...
A re-introduction to JavaScript (JS tutorial) - JavaScript
ditional statements are supported by if and else; you can chain them together if you like: var name = 'kittens'; if (name == 'puppies') { name += ' woof'; } else if (name == 'kittens') { name += ' meow'; } else { name += '!'; } name == 'kittens meow'; JavaScript has while loops and do-while loops. The first is good for basic looping; the second for loops where you wish to ensure that the
body of the loop is executed at least once: while (true) { // an infinite loop! } var input; do { input = get_input(); } while (inputIsNotValid(input)); JavaScript's for loop is the same as that in C and Java: it lets you provide the control information for your loop on a single line. for (var i = 0; i < 5; i++) { // Will execute 5 times } JavaScript also contains two other prominent for ...
... and replacing it with more items. a.reverse() Reverses the array. Functions Along with objects, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler: function add(x, y) { var total = x + y; return total; } This demonstrates a basic function. A JavaScript function can take 0 or more named parameters. The function
body can contain as many statements as you like and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined. The named parameters turn out to be more like guidelines than anything else. You can call a function...
...lse. You can call a function without passing the parameters it expects, in which case they will be set to undefined. add(); // NaN // You can't perform addition on undefined You can also pass in more arguments than the function is expecting: add(2, 3, 4); // 5 // added the first two; 4 was ignored That may seem a little silly, but functions have access to an additional variable inside their
body called arguments, which is an array-like object holding all of the values passed to the function. Let's re-write the add function to take as many values as we want: function add() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; } return sum; } add(2, 3, 4, 5); // 14 That's really not any more useful than writing 2 + 3 + 4 + 5 though. Let's c...
... count = 0; for (var i = 0, child; child = elm.childNodes[i]; i++) { count += countChars(child); } return count; } This highlights a potential problem with anonymous functions: how do you call them recursively if they don't have a name? JavaScript lets you name function expressions for this. You can use named IIFEs (Immediately Invoked Function Expressions) as shown below: var charsIn
Body = (function counter(elm) { if (elm.nodeType == 3) { // TEXT_NODE return elm.nodeValue.length; } var count = 0; for (var i = 0, child; child = elm.childNodes[i]; i++) { count += counter(child); } return count; })(document.
body); The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the e...
async function - JavaScript
ored in a GitHub repository. 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. Syntax async function name([param[, param[, ...param]]]) { statements } Parameters name The function's name. param The name of an argument to be passed to the function. statements The statements comprising the
body of the function. The await mechanism may be used. Return value A Promise which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function. Description Async functions can contain zero or more await expressions. Await expressions suspend progress through an async function, yielding control and subsequently...
...tly resuming progress only when an awaited promise-based asynchronous operation is either fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression. Use of async / await enables the use of ordinary try / catch blocks around asynchronous code. The await keyword is only valid inside async functions. If you use it outside of an async function's
body, you will get a SyntaxError. The purpose of async/await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async/await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. For example, the following: async fun...
... promise-based APIs. The behavior of async/await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. 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. Top-level code, up to and including the first await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function
body, however, the async function will always complete asynchronously. ...
... => undefined) } Code after each await expression can be thought of as existing in a .then callback. In this way a promise chain is progressively constructed with each reentrant step through the function. The return value forms the final link in the chain. In the following example, we successively await two promises. Progress moves through function foo in three stages. The first line of the
body of function foo is executed synchronously, with the await expression configured with the pending promise. Progress through foo is then suspended and control is yielded back to the function that called foo. Some time later, when the first promise has either been fulfilled or rejected, control moves back into foo. The result of the first promise fulfilment (if it was not rejected) is returned from...
Progressive web app structure - Progressive web apps (PWAs)
You can <a href="https://github.com/md...
... The app's only job is to list all th...
...n> <footer> <p>(C) js13kGames 2012-2018, created and maintained by <a href="http://end3r.com">Andrzej Mazur</a> from <a href="http://enclavegames.com">Enclave Games</a>.</p> </footer> </
body> </html> The <head> section contains some basic info like title, description and links to CSS, web manifest, games content JS file, and app.js -- that's where our JavaScript application is initialized. The <
body> is split into the <header> (containing linked image), <main> page (with title, description and place for a content), and <footer> (copy and links). The app's only job is to list all the A-Frame entries from the js13kGames 2017 competition. As you can see it is a very ordinary, one page website -- the point is to have something simple so we can focus on the implementation of the actual PWA featu...
... Notification.requestPermission().then(function(result) { if(result === 'granted') { randomNotification(); } }); }); The last block creates notifications that display a randomly-selected item from the games list: function randomNotification() { var randomItem = Math.floor(Math.random()*games.length); var notifTitle = games[randomItem].name; var notif
Body = 'Created by '+games[randomItem].author+'.'; var notifImg = 'data/img/'+games[randomItem].slug+'.jpg'; var options = {
body: notif
Body, icon: notifImg } var notif = new Notification(notifTitle, options); setTimeout(randomNotification, 30000); } The service worker The last file we will quickly look at is the service worker: sw.js -- it first imports data from...
stroke-linecap - SVG: Scalable Vector Graphics
te is a presentation attribute defining the shape to be used at the end of open subpaths when they are stroked. Note: As a presentation attribute stroke-linecap can be used as a CSS property. ...
...oke --> <path d="M1,1 h4 M1,3 h4 M1,5 h4" stroke="pink" stroke-width="0.025" /> </svg> Usage notes Value butt | round | square Default value butt Animatable Yes butt The butt value indicates that the stroke for each subpath does not extend beyond its two endpoints. On a zero length subpath, the path will not be rendered at all. ...
..."1" r="0.05" fill="pink" /> <circle cx="5" cy="1" r="0.05" fill="pink" /> <circle cx="3" cy="3" r="0.05" fill="pink" /> </svg> round The round value indicates that at the end of each subpath the stroke will be extended by a half circle with a diameter equal to the stroke width. On a zero length subpath, the stroke consists of a full circle centered at the subpath's point. ...
... cy="3" r="0.05" fill="pink" /> </svg> square The square value indicates that at the end of each subpath the stroke will be extended by a rectangle with a width equal to half the width of the stroke and a height equal to the width of the stroke. On a zero length subpath, the stroke consists of a square with its width equal to the stroke width, centered at the subpath's point. ...
Using templates and slots - Web Components
can still be referenced using JavaScript. Let's look at a trivial quick example: <template id="my-paragraph"> <p>My paragraph</p> </template> This won't appear in your page until you grab a reference to it with JavaScript and then append it to the DOM, using something like the following: let template = document.getElementById('my-paragraph'); let templateContent = template.content; document.
body.appendChild(templateContent); Although trivial, you can already start to see how this could be useful. Using templates with web components Templates are useful on their own, but they work even better with web components. Let's define a web component that uses our template as the content of its shadow DOM. We'll call it <my-paragraph>: customElements.define('my-paragraph', class extends HTML...
... references the "attributes" named slot using a <dl> element with <dt> and <dd> children. Adding a final bit of style As a finishing touch, we'll add a tiny bit more CSS for the <dl>, <dt>, and <dd> elements in our doc: dl { margin-left: 6px; } dt { font-weight: bold; color: #217ac0; font-size: 110% } dt { font-family: Consolas, "Liberation Mono", Courier } dd { margin-left: 16px }
body { margin-top: 47px } Result Finally let's put all the snippets together and see what the rendered result looks like. ScreenshotLive sample Notice the following points about this rendered result: Even though the instances of the <element-details> element in the document do not directly use the <details> element, they get rendered using <details> because the shadow root causes them to get p...
...ent for that named slot gets filled with the default content for it from the shadow root. ...
... <script> customElements.define('element-details', class extends HTMLElement { constructor() { super(); const template = document .getElementById('element-details-template') .content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(template.cloneNode(true)); } }) </script> </
body> </html> ...
Basic Example - XSLT: Extensible Stylesheet Language Transformations
tscape Gecko article. The XML file describes an article and the XSL file formats the information for display. Figure 4 : XML file <?xml version="1.0"?> <myNS:Article xmlns:myNS="http://devedge.netscape.com/2002/de"> <myNS:Title>My Article</myNS:Title> <myNS:Authors> <myNS:Author company="Foopy Corp.">Mr. Foo</myNS:Author> <myNS:Author>Mr. ...
...s the information for display. Figure 4 : XML file <?xml version="1.0"?> <myNS:Article xmlns:myNS="http://devedge.netscape.com/2002/de"> <myNS:Title>My Article</myNS:Title> <myNS:Authors> <myNS:Author company="Foopy Corp.">Mr. Foo</myNS:Author> <myNS:Author>Mr. Bar</myNS:Author> </myNS:Authors> <myNS:
Body> The <b>rain</b> in <u>Spain</u> stays mainly in the plains. ...
... xmlns:myNS="http://devedge.netscape.com/2002/de"> <xsl:output method="html" /> <xsl:template match="/"> <html> <head> <title> <xsl:value-of select="/myNS:Article/myNS:Title"/> </title> <style type="text/css"> .myBox {margin:10px 155px 0 50px; border: 1px dotted #639ACE; padding:0 5px 0 5px;} </style> </head> <
body> <p class="myBox"> <span class="title"> <xsl:value-of select="/myNS:Article/myNS:Title"/> </span> <br /> Authors: <br /> <xsl:apply-templates select="/myNS:Article/myNS:Authors/myNS:Author"/> </p> <p class="myBox"> <xsl:apply-templates select="//myNS:
Body"/> </p> </
body> </html> </x...
...The .xsl file is the...
context-menu - Archive of obsolete content
her to show the menu item, then this is the actual node clicked. If you did use SelectorContext, then this is the node that matched your selector. For example, suppose your add-on looks like this: var script = "self.on('click', function (node, data) {" + " console.log('clicked: ' + node.nodeName);" + "});"; var cm = require("sdk/context-menu"); cm.Item({ label: "
body context", context: cm.SelectorContext("
body"), contentScript: script }); This add-on creates a context-menu item that uses SelectorContext to display the item whenever the context menu is activated on any descendant of the <
BODY> element. When clicked, the item just logs the nodeName property for the node passed to the click handler. If you run this add-on you'll see that it always logs "BO...
... context-menu item that uses SelectorContext to display the item whenever the context menu is activated on any descendant of the <
BODY> element. When clicked, the item just logs the nodeName property for the node passed to the click handler. ...
...Note that when you have a hierarchy of menu items the click event will be sent to the content script of the item clicked and all ancestors so be sure to verify ...
page-worker - Archive of obsolete content
exports a constructor function Page, which constructs a new page worker. A page worker may be destroyed, after which its memory is freed, and you must create a new instance to load another page. You specify the page to load using the contentURL option to the Page() constructor. ...
...ontentScript: "console.log(document.
body.innerHTML);", contentURL: "http://en.wikipedia.org/wiki/Internet" }); It can also point to an HTML file which you've packaged with your add-on. To do this, save the file in your add-on's data directory and create the URL using the data.url() method of the self module: pageWorker = require("sdk/page-worker").Page({ contentScript: "console.log(document.
body.innerHTML);", contentURL: require("sdk/self").data.url("myFile.html") }); From Firefox 34, you can use "./myFile.html" as an alias for self.data.url("myFile.html"). ...
...odule: pageWorker = require("sdk/page-worker").Page({ contentScript: "console.log(document.
body.innerHTML);", contentURL: require("sdk/self").data.url("myFile.html") }); From Firefox 34, you can use "./myFile.html" as an alias for self.data.url("myFile.html"). So you can rewrite the above code like this: pageWorker = require("sdk/page-worker").Page({ contentScript: "console.log(document.
body.innerHTML);", contentURL: "./myFile.html" }); You can load a new page by setting the page worker's contentURL property. 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);" + ...
tabs - Archive of obsolete content
Attaching stylesheets New in Firefox 34. You can't attach style sheets to a tab using tab.attach(), but from Firefox 34 onwards you c...
...In particular, your code might not work with m...
...h(options) Attach one or more scripts to the document loaded in the tab. Note that by attaching inside ready event, this becomes tab-centric: if the user navigates to a new page in the same tab, then the content scripts will be reattached to the new page. Example var tabs = require("sdk/tabs"); tabs.on('ready', function(tab) { var worker = tab.attach({ contentScript: 'document.
body.style.border = "5px solid red";' }); }); Parameters options : object Optional options: Name Type contentScriptFile string,array The local file URLs of content scripts to load. Content scripts specified by this option are loaded before those specified by the contentScript option. Optional. contentScript string,array A string or...
widget - Archive of obsolete content
hosting an array of buttons to control play/pause/stop functions. We can then use a content script to listen for clicks on those buttons. But because content scripts can't use the SDK's APIs, we'll want the content script to send messages to the main add-on code, which can then implement the media player functions using the SDK. The widget's content is specified using HTML like this: <html> <
body> <img src="play.png" id="play-button"> <img src="pause.png" id="pause-button"> <img src="stop.png" id="stop-button"> </
body> </html> We just include three icons, and assign an ID to each one. This HTML file, and the icon files it references, are saved in the add-on's data directory. Next, we write a content script that listens for click events on each icon and sends the correspond...
...entById("pause-button"); pause_button.onclick = function() { addon.port.emit("pause"); } var stop_button = document.getElementById("stop-button"); stop_button.onclick = function() { addon.port.emit("stop"); } } Next, add a script tag to reference "button-script.js", and call its init() function on load: <html> <head> <script src="button-script.js"></script> </head> <
body onLoad="init()"> <img src="play.png" id="play-button"> <img src="pause.png" id="pause-button"> <img src="stop.png" id="stop-button"> </
body> </html> Finally, remove the line attaching the content script from "main.js": const widgets = require("sdk/widget"); const data = require("sdk/self").data; var player = widgets.Widget({ id: "player", width: 72, label: "Player", cont...
...function() { this.contentURL = "http://www.bing.com/favicon.ico"; }, onMouseout: function() { this.contentURL = "http://www.yahoo.com/favicon.ico"; } }); // A widget that updates content on a timer. widgets.Widget({ id: "auto-update-widget", label: "Widget that updates content on a timer", content: "0", contentScript: 'setTimeout(function() {' + ' document.
body.innerHTML++;' + '}, 2000)', contentScriptWhen: "ready" }); // A widget created with a specified width, that grows. var myWidget = widgets.Widget({ id: "widget-effect", label: "Wide widget that grows wider on a timer", content: "I'm getting longer.", width: 50, }); require("sdk/timers").setInterval(function() { myWidget.width += 10; }, 1000); // A widget communicatin...
dev/panel - Archive of obsolete content
However, it can receive messages from the add-on that created it, and the add-on can pass it the debuggee so it can communicate with the debugger server the developer tools are targeting. Communicating with the panel document T...
...However, it can receive messages from the add-on that created it, and the add-on can pass it the debuggee so it can communicate with the debugger server the developer tools are targeting. Communicating with the panel document The main add-on code can't directly access...
...olcan.js does not support the complete remote debugging protocol. We're still working on documenting exactly which messages are supported by volcan.js. To use volcan.js, you can just include it from your panel's HTML like this: <html> <head> <meta charset="utf-8"> <link href="./my-panel.css"rel="stylesheet"></link> <script src="resource://sdk/dev/volcan.js"></script> </head> <
body> <div id = "content"></div> </
body> <script src="./my-panel.js"></script> </html> Here's a script that uses volcan.js to get the selected tab and display its URL: // my-panel.js var content = document.getElementById("content"); window.addEventListener("message", function(event) { var debuggee = event.ports[0]; volcan.connect(debuggee). then(listTabs). then(writeTabList);...
ui/sidebar - Archive of obsolete content
bar = 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. <!DOCTYPE HTML> <html> <head> <link href="stuff.css" type="text/css" rel="stylesheet"> </head> <
body> <script type="text/javascript" src="stuff.js"></script> </
body> </html> You can update the sidebar's content by setting the sidebar's url property. This will change the sidebar's content across all windows. Communicating with sidebar scripts You can't directly access your sidebar's content from your main add-on code, but you can send messages between your main add-on code and scripts l...
...d yet, so you can't reliably send messages to the sidebar script right away: however, you can start listening to messages from the script. Here's a simple but complete add-on that shows how to set up communication between main.js and a script in a sidebar, in the case where the sidebar script initiates communication: The HTML file includes just a script, "sidebar.js": <!DOCTYPE HTML> <html> <
body> Content for my sidebar <script type="text/javascript" src="sidebar.js"></script> </
body> </html> The "sidebar.js" file sends a ping message to main.js using port.emit() as soon as it loads, and adds a listener to the pong message. addon.port.emit("ping"); addon.port.on("pong", function() { console.log("sidebar script got the reply"); }); The "main.js" file creates a sidebar obje...
...essages to the sidebar script and be confident that they will not be lost. Listen to this event if your add-on initiates the conversation. Here's a simple but complete add-on that shows how to set up communication between main.js and a script in a sidebar, in the case where the main.js script initiates communication: The HTML file includes just a script, "sidebar.js": <!DOCTYPE HTML> <html> <
body> Content for my sidebar <script type="text/javascript" src="sidebar.js"></script> </
body> </html> The "sidebar.js" file listens to the ping message from main.js, and responds with a pong message. addon.port.on("ping", function() { console.log("sidebar script got the message"); addon.port.emit("pong"); }); The "main.js" file creates a sidebar object and adds a listener to its att...
Storing annotations - Archive of obsolete content
inds a click handler to the links which will send the URL to the add-on. Save this file in data/list as annotation-list.js. ...
... http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Saved annotations</title> <link rel="stylesheet" type="text/css" href="annotation-list.css" /> </head> <
body> <div id="annotation-list"> </div> <div id="template"> <div class="annotation-details"> <a class="url"></a> <div class="selection-text"></div> <div class="annotation-text"></div> </div> </div> </
body> </html> Here's the corresponding CSS: #annotation-list .annotation-details { padding: 10px; margin: 10px; border: solid 3px #EEE; background-color: white; } #annotation-list .url, .selection-text, .annotation-text { padding: 5px; margin: 5px; } #annotation-list .selection-text,#annotation-list .annotation-text { border: solid 1px #EEE; } #annotation-list .annotat...
... Updating main.js Here's the code to create the panel, which can go in the main function. var annotationList = panels.Panel({ width: 420, heig...
Display a Popup - Archive of obsolete content
rom the // main add-on code. It means that the panel's about // to be shown. // // Set the focus to the text area so the user can // just start typing. ...
...wn. // // Set the focus to the text area so the user can // just start typing. ...
... typing. ...
Embedding SVG - Archive of obsolete content
use the right namespace when embedding. Notice the template and example use XHTML to handle the namespacing. ...
... the template and example use XHTML to handle the namespacing. ...
...nk="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" fill="red"/> <svg:circle cx="50" cy="50" r="30" fill="blue"/> </svg:svg> <p>world</p> </
body> </html> Embedding into XUL Make sure you use the right namespace when embedding <?xml version="1.0"?> <?xml-stylesheet href="chrome://global...
Interaction between privileged and non-privileged pages - Archive of obsolete content
}, false); document.head.appendChild(request); var event = document.createEvent("HTMLEvents"); event.initEvent("something-query", true, false); request.dispatchEvent(event); }, callback: function(response) { return alert("response: " + (response ? ...
...)">send {foo: 1} with callback</button> <button onclick="return something.send_request({baz: 3}, something.callback)">send {baz: 3} with callback</button> <button onclick="return something.send_request({mozilla: 3})">send {mozilla: 3} without callback</button> <button onclick="return something.send_request({firefox: 4}, something.callback)">send {firefox: 4} with callback</button> </
body> </html> Overlay on browser.xul in your extension: var something = { listen_request: function(callback) { // analogue of chrome.extension.onRequest.addListener document.addEventListener("something-query", function(event) { var node = event.target; if (!node || node.nodeType != Node.TEXT_NODE) return; var doc = node.ownerDocument; callback(JSON.parse(node.
...g| object as E4X XML somethingXML.@id = something.id; somethingXML.@weight = something.weight; sendMsg("sendSomething", somethingXML); } /** * Send msgs from chrome to the page * @param type {String} the event type. The receiver needs to use that * when doing addEventListener(type, ...) * @param dataXML {E4X} the data or detail */ function sendMsg(type, dataXML) { var el = targetDoc.
body; el.setAttribute("eventDataToPage", dataXML ? dataXML.toString() : ""); var event = targetDoc.createEvent("Event") event.initEvent(type, true, true); el.dispatchEvent(event); } /** * Verifies that the event is indeed coming from our page * as expected, and returns the data for that event. * @returns {E4X} the (unchecked) detail data from the page. * You must check the data. * @see <...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
In most cases, .text() should be used instead of the latter. When using the jQuery constructor, only empty tags should...
...ble to use its builtin DOM building functions for templating, though care must be taken when passing non-static strings to methods such as .append() and .html(). In most cases, .text() should be used instead of the latter. When using the jQuery constructor, only empty tags should be specified in order to avoid invoking the DOM parser. var href = "http://www.google.com/"; var text = "Google"; $("
body").append( $("<div>", { class: "foo" }) .append($("<a>", { href: href, text: text }) .click(function (event) { alert(event.target.href) })) .append($("<span>").text("Foo"))); innerHTML with HTML Escaping This method is a last resort which should be used only as a temporary measure in established code bases. It is safe, though inefficient, to assign dynamic...
...er.SanitizerAllowStyle : 0, !!isXML, baseURI, doc.documentElement); } return Cc["@mozilla.org/feed-unescapehtml;1"] .getService(Ci.nsIScriptableUnescapeHTML) .parseFragment(html, !!isXML, baseURI, doc.documentElement); } The returned fragment may be appended to any element in the given document. ...
Creating reusable content with CSS and XBL - Archive of obsolete content
ore details For more information about XBL bindings, see the XBL page in this wiki. Action: An XBL demonstration Make a new HTML document, doc6.html. Copy and paste the content from here: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <HTML> <HEAD> <TITLE>Mozilla CSS Getting Started - XBL demonstration</TITLE> <LINK rel="stylesheet" type="text/css" href="style6.css"> </HEAD> <
BODY> <H1>XBL demonstration</H1> <DIV id="square">Click Me</DIV> </
BODY> </HTML> Make a new CSS file, style6.css. This stylesheet contains the document style. Copy and paste the content from here: /*** XBL demonstration ***/ #square { -moz-binding: url("square.xbl#square"); } Make a new text file, square.xbl. This file contains the XBL binding. Copy and paste the content from here: <?xml ...
...l:button anonid="button" type="button"> <children/> </xul:button> </content> <implementation> <field name="square"><![CDATA[ document.getAnonymousElementByAttribute(this, "anonid", "square") ]]></field> <field name="button"><![CDATA[ document.getAnonymousElementByAttribute(this, "anonid", "button") ]]></field> <method name="doDemo"> <
body><![CDATA[ this.square.style.backgroundColor = "#cf4" this.square.style.marginLeft = "20em" this.button.setAttribute("disabled", "true") setTimeout(this.clearDemo, 2000, this) ]]></
body> </method> <method name="clearDemo"> <parameter name="me"/> <
body><![CDATA[ me.square.style.backgroundColor = "transparent" me.square.s...
....style.marginLeft = "20em" this.button.setAttribute("disabled", "true") setTimeout(this.clearDemo, 2000, this) ]]></
body> </method> <method name="clearDemo"> <parameter name="me"/> <
body><![CDATA[ me.square.style.backgroundColor = "transparent" me.square.style.marginLeft = "0" me.button.removeAttribute("disabled") ]]></
body> </method> </implementation> <handlers> <handler event="click" button="0"><![CDATA[ if (event.originalTarget == this.button) this.doDemo() ]]></handler> </handlers> </binding> </bindings> Make a new CSS file, bind6.css. This separate stylesheet contains style for the binding. Copy and paste the content from here: /*** XBL demonstration ***/ [anonid="square"...
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
in the IFRAME and inside this page (requested data), set the onload event to callback a function notifying the parent document (originator). This sample is using the second approach. To demonstrate how the callback mechanism is implemented, imagine the following HTML page loaded into the IFRAME as a result of a request (retrieveData method requested the HTML file in to be loaded in the IFRAME): <
body onload="top.iframeCallback(document);" > <mydata> This is the content that comes from the server </mydata> </
body> Note that when the page is loaded into the IFRAME, the onload event is fired and the parent.iframeCallBack function is called in the context of the parent document (the originator). Here, iframeCallback is considered the Data Binder, so it is responsible for getting the content from ...
...style.backgroundColor="white"; } ele.style.backgroundColor="#ddeeff"; previousEle=ele; } var previousEle=null; </script> <style> .tab { position:relative;top:1px; border: 1px solid #dddddd; color:white; background-color:white; padding-left: 5px; border-bottom:white;padding-right: 5px; padding-top:3px; text-decoration:none;} .tab:hover { background-color:#ddeeff; } </style> </head> <
body > <h2>Latest Headlines - Inner-Browsing Example </h2> <p>Click the tabbed menu to dynamically load the headlines into this web page.</p> <br /> <!-- ***** This code dynamically creates the Tabbed Menu if the browser has support to XMLHTTPRequest, since the mechanism used here is XMLHTTPRequest ***** --> <script type="text/javascript" language="javascript"> //// /// Object detection // ...
...All rights reserved. Note: This reprinted article was originally part of the DevEdge site. ...
JXON - Archive of obsolete content
ument */ var oMyHTMLStruct = { "html": { "head": { "meta": { "@http-equiv": "Content-Type", "@content": "text/html; charset=UTF-8" }, "title": "My HTML Document", "script": { "@type": "text/javascript", "keyValue": "alert(\"Welcome!\");" }, "style": "p:first-letter {\n font: italic bold 30px Georgia, serif;\n}" }, "
body": { "h1": "My HTML Document", "p": "Hello world!!" } } }; /* Create the document */ var oMyHTMLDoc = JXON.unbuild(oMyHTMLStruct, "http://www.w3.org/1999/xhtml"); ...And here is the output of alert((new XMLSerializer()).serializeToString(oMyHTMLDoc)): <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>My HTML Document</title> <scr...
...For ...
...For instance, a bidirectional conversion of the following HTML ...
Example Sticky Notes - Archive of obsolete content
notes.html All parts are made and commented by VK [schools_ring@yahoo.com]. All rights are given to the world. 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, Inc. fax - respond today.</p></div> <div class="sticker"><p>Don't forget ...
... The others are only needed if you plan to handle XUL (XML User Interface Language) or...
...A[ // "val" in setter contains the assignment value. // Here we simply echoing it back: return val; ]]></setter> </property> <method name="setBorder"> <!-- New method for the bound element. Unlike virtual property it is called in function context: this.setBorder(arg) You also may define any amount of named arguments using <parameter name="argumentName"/> --> <parameter name="arg"/> <
body><![CDATA[ this.style.border = arg; ]]></
body> </method> </implementation> <handlers> <!-- Event handlers. Mouse events sent to bindings are refactored, so event.target / event.relatedTarget always points to the bound element, even if it was originated to/from a child. --> <handler event="click"><![CDATA[ if (this.priority == 'normal') { this.priority = 'high'; this.setBorde...
Index - Archive of obsolete content
. 1168 rule XUL Elements, XUL Reference A rule is used in a template. The children of the rule are used to declare the conditions in which the rule matches and the content that is generated. A rule may contain where, binding and/or action elements. A condition is defined used a where element. For each result that matches all of the conditions, content within the rule's action
body is generated. The bindings element is optional and may specify additional variable bindings to be used. 1169 scale XUL Elements, XUL Reference A scale (sometimes referred to as a "slider") allows the user to select a value from a range. A bar displayed either horizontally or vertically allows the user to select a value by dragging a thumb on the bar. 1170 script ...
...he interfaces available via the tree's view property. The third column indicates whether treeitem element are used. 1206 treecell XUL Elements, XUL Reference A single cell in a tree. This element should be placed inside a treerow. You can set the text for the cell using the label attribute. 1207 treechildren XUL Elements, XUL Reference This element is the
body of the tree. For content trees, the content will be placed inside this element. This element is also used to define container rows in the tree. 1208 treecol XUL Elements, XUL Reference A column of a tree. It displays the column header and holds the size and other information about the column. You can also place splitter elements between the columns to allow column resizing. Y...
...iables. 1214 vbox XUL Elements, XUL Reference A container element which can contain any number of child elements. This is equivalent to the box element, except it defaults to vertical orientation. 1215 where XUL Elements, XUL Reference Indicate a condition that must match for a template result to be used. If the condition is true, the corresponding action
body is generated; otherwise the result is ignored and no content is generated. 1216 window XUL Elements, XUL Reference Describes the structure of a top-level window. It is the root node of a XUL document. It is by default a horizontally oriented box. As it is a box, all box attributes can be used. By default, the window will have a platform-specific frame around it. 1217 ...
Actions - Archive of obsolete content
de the <xul:template> element after the query is defined. This action contains only one element, but you can put as many or as few elements as you need. In this case, a button will be created for each result. There are three results, so three buttons will be created. 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. The uri attribute on the button is used to specify the ending or member variable. In this example, there's only one variable to use, ?relateditem, since ?start is the starting point and the start and end points cannot be the same. There are a number of things that will happen for each result. Let's look at the results again: (?start = http://www.xulplanet.com/r...
...utton id="http://www.xulplanet.com/rdf/C" label="http://www.xulplanet.com/rdf/C"/> <button id="http://www.xulplanet.com/rdf/D" label="http://www.xulplanet.com/rdf/D"/> </vbox> Since the template tag is hidden, the effect will be like in the image, three buttons with the labels of the data in the datasource. Additional Content The previous example generated only a set of buttons, but the action
body may contain additional content. For instance, you might want to add a label to each item. <action> <hbox uri="?relateditem"> <label value="Related Item:"/> <button label="?relateditem"/> </hbox> </action> In this example, the hbox will be generated for each result, assigned an id of the value of the ?relateditem, and the label and button will be added inside it. The button's label wi...
... of the value of the ?relateditem, and the label and button will be added inside it. The button's label will be the value of the ?relateditem variable. You would only use the uri attribute on a single element since only one of the generated elements should be given a particular id. Although the uri attribute should only be on one element, it does not have to be the outermost element in the action
body. You can place other elements outside this to serve as containers for all the results. One difference is that this content is only generated once, not for every result. Only the content at the element with the uri attribute and below is copied for each result. For example, if the example were modified to the following: <action> <toolbar> <button uri="?relateditem" label="?relateditem"/> <...
Additional Template Attributes - Archive of obsolete content
to the root node, in this example the listbox, not inside the template. Declaring the Container and Member Variables Normally, the container and member variables are determined by the template builder automatically. The container or starting node variable is specified in the <content> tag inside a query, while the member variable is determined by the value of the uri attribute inside the action
body. ...
...You might also use these attributes just to make the code clearer when using very complex queries. One possible advantage is when using the simple RDF query syntax where you don't specify variables; instead you use the special 'rdf:*' syntax for the member variable and the container is implied. ...
...om/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). This may make the code clearer as to its function. We could use the container variable ?start in the action
body also. If you are using the simple syntax and want to use the container variable in the content, you must use the container attribute since there is no other way to refer to it. Note also that a rule element is needed here, otherwise the builder will think the container and member attributes are conditions to check. << PreviousNext >> ...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
ndency, it can be worked around easily. ...
... easily. ...
...eed: 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(url,
body); req.Action = ns + '#' + method; SOAPClient.SendRequest(req, callback); Diff between jqSOAPClient.js and saSOAPClient.js 42c42 < var jsOut = $.xmlToJSON(xData.responseXML); --- > var jsOut = XMLObjectifier.xmlToJSON(xData.responseXML); 46,60c46,62 < $.ajax({ < type: "POST", < url: SOAPClie...
-ms-filter - Archive of obsolete content
rogid: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. Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_s.htm <
body> <p>Click the image to start the filter.</p> // Call the function. <div id="filterFrom" style="position: absolute; width: 200px; height: 250px; background-color: white; filter: revealTrans()"> <img id="imageFrom" style="position: absolute; top: 20px; left: 20px;" src="sphere.jp...
.../javascript"> let filterImg = document.querySelector('#filterFrom'); filterImg.addEventListener('click', doFilter); function doFilter () { filterFrom.filters.item(0).Apply(); // 12 is the dissolve filter. ...
...zero value to make the gradient horizontal (equivalent to linear-gradient(to right, ...)) StartColor The end color, supports only opaque colors in the #RRGGBB notation. StartColorStr The end color, supports both opaque colors (#RRGGBB) and colors with alpha opacity using the #AARRGGBB notation. ...
VBArray.dimensions - Archive of obsolete content
sions in a specified VBArray. The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JavaScript code that determines the number of dimensions in the safe array and the upper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <
BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k k = k + 1 Next Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function VBArrayTest(vba) { var i; var a = new VBArray(vba); v...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
VBArray.getItem - Archive of obsolete content
of dimensions in the VBArray. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JavaScript code that iterates the Visual Basic safe array and prints out the contents of each element. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <
BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(i, j) = k document.writeln(k) k = k + 1 Next document.writeln("<BR>") Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function Get...
...Not supported in Windows 8.x Store apps. See Version Information. Applies To:...
...Not supported in Windows 8.x Store apps. See Version Information. Applies To: VBArray Object ...
VBArray.lbound - Archive of obsolete content
de to create a Visual Basic safe array. The second part is JavaScript code that determines the number of dimensions in the safe array and the lower bound of each dimension. Since the safe array is created in VBScript rather than Visual Basic, the lower bound will always be zero. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <
BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k k = k + 1 Next Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function VBArrayTest(vba){ var i; var a = new VBArray(vba); va...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
VBArray.toArray - Archive of obsolete content
no way to convert a JavaScript array into a VBArray. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JavaScript code that converts the Visual Basic safe array to a JavaScript array. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <
BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k document.writeln(k) k = k + 1 Next document.writeln("<BR>") Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function VB...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
VBArray.ubound - Archive of obsolete content
out of range" error. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JavaScript code that determines the number of dimensions in the safe array and the upper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <
BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k k = k + 1 Next Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function VBArrayTest(vba) { var i; var a = new VBArray(vba); v...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
...Not supported in Windows 8.x Store apps. Applies To: VBArray Object ...
VBArray - Archive of obsolete content
retrieve the range of indices used by each dimension. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JavaScript code that converts the Visual Basic safe array to a JavaScript array. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JavaScript code that goes in the <
BODY> section to run the other two parts. <head> <script type="text/vbscript"> <!-- Function CreateVBArray() Dim i, j, k Dim a(2, 2) k = 1 For i = 0 To 2 For j = 0 To 2 a(j, i) = k document.writeln(k) k = k + 1 Next document.writeln("<br />") Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function ...
... Methods VBArray.dimensions Returns the number of dimensions in a VBArray. VBArray.getItem Returns the item at the specified location. VBArray.lbound Returns the lowest index value used in the specified dimension of a VBArray. VBArray.toArray Re...
...ment.writeln("<br />") Next CreateVBArray = a End Function --> </script> <script type="text/javascript"> <!-- function VBArrayTest(vbarray){ var a = new VBArray(vbarray); var b = a.toArray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <
body> <script type="text/javascript"> <!-- VBArrayTest(CreateVBArray()); --> </script> </
body> Properties The VBArray object has no properties. Methods VBArray.dimensions Returns the number of dimensions in a VBArray. VBArray.getItem Returns the item at the specified location. VBArray.lbound Returns the lowest index value used in the specified dimension of a VBArray. VBArray.toArray Returns a standard JavaScript array converted from a VBArray. VBArray.ubound Returns the hig...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
h a slight offset. I then set up a thicker double border on the left, a one-pixel border the rest of the way around, and set the background to match the rest of the design. Thus: div.card {float: left; width: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; margin: 4px 0 0 0; border: 1px solid #339;} div.card h3 {border: 1px solid #339; border-left: 5px double #339; background: #EEC url(
body-bg-tan.jpg) bottom left no-repeat fixed; color: #339;} Finishing the Style Adding the background to the heading containing the name of the fish created three problems: The double border was completely covered up by the image. The text of the h3 was basically touching the right side of the floated image... ...or it would have been, except in some browsers the heading was drawn over the fl...
... fish image and fish name. With just a few simple margin and padding changes, this was possible. div.card {float: left; width: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; position: relative; z-index: 10; margin: 4px 0 0 0; border: 1px solid #339;} div.card h3 {margin: 0 0 0 4px; padding: 0.2em 0 1px 150px; border: 1px solid #339; border-left: 5px double #339; background: #EEC url(
body-bg-tan.jpg) bottom left no-repeat fixed; color: #339;} Note how the image is pushed downward four pixels, while the h3 is pushed rightward four pixels. At the same time, the heading's padding was set to that it had 150 pixels of left padding. Thus, the text starts 159 pixels from the leftmost edge of the card (4px left margin plus 5px left border plus 150px left padding). Since all the fish im...
... word would wrap under an image. It's better to keep the text as if it's in a column of its own. div.card {float: left; width: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; position: relative; z-index: 10; margin: 4px 0 0 0; border: 1px solid #339;} div.card h3 {margin: 0 0 0 4px; padding: 0.2em 0 1px 150px; border: 1px solid #339; border-left: 5px double #339; background: #EEC url(
body-bg-tan.jpg) bottom left no-repeat fixed; color: #339;} div.card p {margin: 0.5em 0.5em 0.5em 160px;} And voila! The cards are done. Conclusion Redesigning a classic is something like being asked to reviseMoby Dick for modern audiences: you're thrilled at the opportunity, but afraid of doing injustice to the original. I'd like to think that the final result was in keeping with the original sp...
XForms Custom Controls - Archive of obsolete content
care to make sure that the embedded XForms controls are able to work with the data type of the instance node that your control is bound to. To give you an idea of what we are talking about, it could look something like this: <content> <xf:input xbl:inherits="ref=ref1" anonid="ref1"/> <xf:input xbl:inherits="ref=ref2" anonid="ref2"/> </content> <implementation> <method name="refresh"> <
body> // Here we should refresh custom control. </
body> </method> <constructor> // We should redirect calls of input's 'refresh' method to custom control 'refresh' method. var control = this; var refreshStub = function() { control.refresh(); } this.ref1.refresh = refreshStub; this.ref2.refresh = refreshStub; </constructor> <property name="ref1" readon...
... <bindings id="xformsBindings" xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml"> <binding id="output-image" extends="chrome://xforms/content/xforms.xml#xformswidget-base"> <content> <html:div> <html:img anonid="content"/> </html:div> </content> <implementation implements="nsIXFormsUIWidget"> <method name="refresh"> <
body> <!-- set the src attribute on the html:img to be the simpleContent of the instance node bound to this control --> var img = document.getAnonymousElementByAttribute(this, "anonid", "content"); img.setAttribute("src", this.stringValue); return true; </
body> </method> </implementation> </binding> </b...
... <img label="Bugzilla">http://www.mozilla.org/images/p-bugz.gif</img> <img label="Mozilla">http://www.mozilla.org/images/mozhead-80x64.gif</img> </data> </xf:instance> </xf:model> <style type="text/css"> @namespace xf url(http://www.w3.org/2002/xforms); xf|output[mediatype="image/*"] { -moz-binding: url('#output-image'); } </style> </head> <
body> <h1>Custom Control Sample</h1> <xf:select1 ref="curimg"> <xf:label>Select image to display: </xf:label> <xf:itemset nodeset="../img"> <xf:label ref="@label"/> <xf:value ref="."/> </xf:itemset> </xf:select1> <xf:output ref="curimg" mediatype="image/*"/> </
body> </html> ...
Fixing Table Inheritance in Quirks Mode - Archive of obsolete content
y: When in quirks mode, Gecko-based browsers will appear to ignore inheritance of font styles into tables from parent elements. Find out why this happens and how to fix it in documents that have to remain in quirks mode. In version 4 browsers such as Netscape Navigator 4.x and Internet Explorer 4.x, tables generally "broke" the inheritance of font styling. 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. This led to a number of workarounds which were designed to cater to these bugs, and also to Gecko-based browsers emulating the behavior in some cases. Fortunately, the behavior can be overcome in all cases with a single CSS2 rule. Tables and Inheritance In CSS terms, tables are like an...
...or in some cases. Fortunately, the behavior can be overcome in all cases with a single CSS2 rule. Tables and Inheritance In CSS terms, tables are like any other element when it comes to inheritance. If a CSS property can be inherited, then table elements and their components (tr, td, etc.) should inherit just as any other element would. 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. Browsers from the version-four era, however, treated tables differently. In these browsers, a table's text would be the same size as the user's default settings, regardless of the CSS assigned to ancestor elements such as
body. This represented a violation of CSS inheritance rules, and led many aut...
...ells should also be 11 pixels in size. Browsers from the version-four era, however, treated tables differently. In these browsers, a table's text would be the same size as the user's default settings, regardless of the CSS assigned to ancestor elements such as
body. This represented a violation of CSS inheritance rules, and led many authors to create workarounds such as: <style type="text/css">
body, table, td {font-size: 11px;} </style> Recreating Legacy Behavior To avoid "breaking" older pages that were authored with old-browser behaviors in mind, Mozilla and related browsers will mimic old browsers when in "quirks" mode. To do this, the Gecko rendering engine uses the following rule in the quirk.css user agent file: /* Quirk: cut off all font inheritance in tables and captions except f...
Building up a basic demo with A-Frame - Game development
ev builds). Open the A-Frame documentation in a separate tab -- it is useful to refer to. HTML structure The first step is to create an HTML document -- inside your project directory, create a new index.html file, and save the follow HTML inside it: <!doctype html> <html> <head> <meta charset="utf-8"> <title>MDN Games: A-Frame demo</title> <script src="aframe.min.js"></script> </head> <
body> <!-- HTML goes here --> </
body> </html> This contains some basic information like the document charset and <title>. The <script> element includes the A-Frame framework in the page; we will write our example code inside the <
body> element. Initializing the scene A scene is the place where everything happens. When creating new objects in the demo, we will be adding them all to the scene to ma...
...e everything happens. When creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen. In A-Frame, the scene is reperesented by a Scene entity. Note: An Entity is any element -- it can be an object like a box, cylinder or cone, but it can also be a camera, light or sound source. Let's create the scene by adding an <a-scene> element inside the <
body> element: <a-scene> </a-scene> Adding a cube Adding the cube to the scene is done by adding a simple <a-box> element inside the <a-scene> element. Add it now: <a-box color="#0095DD" position="0 1 0" rotation="20 40 0"> </a-box> It contains a few parameters already defined: color, position and rotation -- these are fairly obvious, and define the base color of the cube, the position in...
...up the color of the material, then its roughness (a rougher material will scatter reflected light in more directions than a smooth material) and metalness (how metallic the material is). Adding some JavaScript to the mix It is possible to populate the scene with entities created using JavaScript too, so let's use it to add a third shape, a cylinder. ...
Building up a basic demo with Babylon.js - Game development
rome. Creating a directory to store your experiments in. Saving a copy of the latest Babylon.js engine inside your directory. Opening the Babylon.js documentation in a separate tab -- it is useful to refer to. ...
...ne inside your directory. Opening the Babylon.js documentation in a separate tab -- it is useful to refer to. ...
... <meta charset="utf-8"> <title>MDN Games: Babylon.js demo</title> <style> html,
body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; } </style> </head> <
body> <script src="babylon.js"></script> <canvas id="render-canvas"></canvas> <script> var canvas = document.getElementById("render-canvas"); /* all our JavaScript code goes here */ </script> </
body> </html> It contains some basic information like the document <title>, and some CSS to set the width and height of the <canvas> element (which Babylon.js will use to render the content on) to fill the entire available viewport space. The first <script> element includes the Babylon.js library in the page; we will write our example code in the second one. There is one helper variable already incl...
Building up a basic demo with the PlayCanvas engine - Game development
or Chrome. Creating a directory to store your experiments in. Saving a copy of the latest PlayCanvas engine inside your directory. Opening the PlayCanvas documentation in a separate tab -- it is useful to refer to. HTML structure Here's the HTML structure we will use. ...
...vas engine inside your directory. Opening the PlayCanvas documentation in a separate tab -- it is useful to refer to. HTML structure Here's the HTML structure we will use. ...
...et="utf-8"> <title>MDN Games: PlayCanvas demo</title> <style>
body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <
body> <script src="playcanvas-latest.js"></script> <canvas id="application-canvas"></canvas> <script> var canvas = document.getElementById("application-canvas"); /* all our JavaScript code goes here */ </script> </
body> </html> It contains some basic information like the document <title>, and some CSS to set the width and height of the <canvas> element that PlayCanvas will use to 100% so that it will fill the entire available viewport space. The first <script> element includes the PlayCanvas library in the page; we will write our example code in the second one. There is one helper variable already included, w...
Async scripts for asm.js - Game development
(starting in Firefox 28). To see the difference, toggle javascript.options.parallel_parsing in about:config. ...
...rc = "file.js"; document.
body.appendChild(script); (Scripts created from script default to async.) The default HTML shell Emscripten generates produces the latter. When is async not async? Two common situations in which a script is *not* async (as defined by the HTML spec) are: <script async>code</script> and var script = document.createElement('script'); script.innerHTML = "code"; document.
body.appendChild(script); Both are counted as 'inline' scripts and get compiled and then run immediately. What if your code is in a JS string? Instead of using eval or innerHTML, both of which trigger synchronous compilation, you should use a Blob with an object URL: var blob = new Blob([codeString]); var script = document.createElement('script'); var url = URL.createObjectURL(blob); script.onload ...
...n immediately. What if your code is in a JS string? Instead of using eval or innerHTML, both of which trigger synchronous compilation, you should use a Blob with an object URL: var blob = new Blob([codeString]); var script = document.createElement('script'); var url = URL.createObjectURL(blob); script.onload = script.onerror = function() { URL.revokeObjectURL(url); }; script.src = url; document.
body.appendChild(script); The setting of src rather than innerHTML is what makes this script async. ...
Build the brick field - Game development
n a group. Now we need to add some code inside the nested loop stucture to draw each brick. ...
... The problem currently is that we're painting all the bricks in one place, at coordinates (0,0). ...
... Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: Next steps Somethi...
Physics - Game development
irst line inside the function), as shown below: game.physics.startSystem(Phaser.Physics.ARCADE); Next, we need to enable our ball for the physics system -- Phaser object physics is not enabled by default. Add the following line at the bottom of the create() function: game.physics.enable(ball, Phaser.Physics.ARCADE); Next, if we want to move our ball on the screen, we can set velocity on its
body. Add the following line, again at the bottom of create(): ball.
body.velocity.set(150, 150); Removing our previous update instructions Remember to remove our old method of adding values to x and y from the update() function: function update() { ball.x += 1; ball.y += 1; } we are now handling this properly, with a physics engine. Final code check The latest code should look like th...
...At the moment, the physics engine has gravity and friction set to zero. Adding gravity would result in the ball falling down while friction would eventually stop the ball. Fun with physics You can do much more with physics, for example by adding b...
...ocity.set(150, 150); } function update() { } Try reloading index.html again -- The ball should now be moving constantly in the given direction. At the moment, the physics engine has gravity and friction set to zero. Adding gravity would result in the ball falling down while friction would eventually stop the ball. 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. As a result it will be launched upwards, but then fall due to the effects of gravity pulling it down. This kind of functionality is just the tip of the iceberg -- there are various functions and variables that can help you manipulate the physics objects. Check out the official physics documentation and see the huge collection of exa...
Practical positioning examples - Learn web development
such as XMLHttpRequest. At this point in your learning however we want to keep things as simple as possible. There is some JavaScript later on, but only a tiny bit. To start with, we'd like you to make a local copy of the starting HTML file -- info-box-start.html. Save this somewhere sensible on your local computer, and open it up in your text editor. Let's look at the HTML contained within the
body: <section class="info-box"> <ul> <li><a href="#" class="active">Tab 1</a></li> <li><a href="#">Tab 2</a></li> <li><a href="#">Tab 3</a></li> </ul> <div class="panels"> <article class="active-panel"> <h2>The first tab</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque turpis nibh, porttitor nec venenatis eu, pulvinar in augue. Vestibul...
...t this stage, but you should think about learning some basic JavaScript as soon as possible -- the more complex your UI features become, the more likely it is that you'll need some JavaScript to implement your desired functionality. General setup To begin with, add the following between your opening and closing <style> tags: html { font-family: sans-serif; } * { box-sizing: border-box; }
body { margin: 0; } This is just some general setup to set a sans-serif font on our page, use the border-box box-sizing model, and get rid of the default <
body> margin. Next, add the following just below your previous CSS: .info-box { width: 450px; height: 400px; margin: 0 auto; } This sets a specific width and height on the content, and centers it on the screen using the old margin: 0 aut...
... Check it out to get an idea of what you will be building in this section of the article. As a starting point, you can use your completed example from the first section of the article, or make a local copy of info-box.html from our Github repo. HTML additions First of all, we need some additional HTML to represent the web site main content. Add the following <section> just below your opening <
body> tag, just before the existing section: <section class="fake-content"> <h1>Fake content</h1> <p>This is fake content. Your main web page contents would probably go here.</p> <p>This is fake content. Your main web page contents would probably go here.</p> <p>This is fake content. Your main web page contents would probably go here.</p> <p>This is fake content. Your main web page contents...
Getting started with CSS - Learn web development
to an HTML file, and be able to do simple text formatting with CSS. Starting with some HTML Our starting point is an HTML document. You can copy the code from below if you want to work on your own computer. Save the code below as index.html in a folder on your machine. ...
... Adding CSS to our document The very first thing we need to do is to tell the HTML document that we have some CSS rules we want it to use. ...
...t is worth noting that you can combine multiple selectors and combinators together. For example: /* selects any <span> that is inside a <p>, which is inside an <article> */ article p span { ... } /* selects any <p> that comes directly after a <ul>, which comes directly after an <h1> */ h1 + ul + p { ... } You can combine multiple types together, too. Try adding the following into your code:
body h1 + p .special { color: yellow; background-color: black; padding: 5px; } This will style any element with a class of special, which is inside a <p>, which comes just after an <h1>, which is inside a <
body>. Phew! In the original HTML we provided, the only element styled is <span class="special">. Don't worry if this seems complicated at the moment -- you'll soon start to get the hang of...
Client-side form validation - Learn web development
utions using maxlength, can be used to provide this Constraining the values of your entries For number fields (i.e. <input type="number">), the min and max attributes can be used to provide a range of valid values. If the field contains a value outside this range, it will be invalid. Let's look at another example. Create a new copy of the fruit-start.html file. ...
...nreader users. Note: A key point here is that setting the novalidate attribute on the form is what stops the form from showing its own error message bubbles, and allows us to instead display the custom error messages in the DOM in some manner of our own choosing. ...
...pan> </label> </p> <!-- Some legacy browsers need to have the `type` attribute explicitly set to `submit` on the `button`element --> <button type="submit">Submit</button> </form> Similarly, the CSS doesn't need to change very much; we've just turned the :invalid CSS pseudo-class into a real class and avoided using the attribute selector that doesn't work on Internet Explorer 6. ...
Sending forms through JavaScript - Learn web development
ere is not, delay the execution of the function if( !file.binary && file.dom.files.length > 0 ) { setTimeout( sendData, 10 ); return; } // To construct our multipart form data request, // We need an XMLHttpRequest instance const XHR = new XMLHttpRequest(); // We need a separator to define each part of the request const boundary = "blob"; // Store our
body request in a string. let data = ""; // So, if the user has selected a file if ( file.dom.files[0] ) { // Start a new part in our
body's request data += "--" + boundary + "\r\n"; // Describe it as form data data += 'content-disposition: form-data; ' // Define the name of the form data + 'name="' + file.dom.name + '"; ' ...
... + 'name="' + file.dom.name + '"; ' // Provide the real name of the file + 'filename="' + file.dom.files[0].name + '"\r\n'; // And the MIME type of the file data += 'Content-Type: ' + file.dom.files[0].type + '\r\n'; // There's a blank line between the metadata and the data data += '\r\n'; // Append the binary data to our
body's request data += file.binary + '\r\n'; } // Text data is simpler // Start a new part in our
body's request data += "--" + boundary + "\r\n"; // Say it's form data, and name it data += 'content-disposition: form-data; name="' + text.name + '"\r\n'; // There's a blank line between the metadata and the data data += '\r\n'; // Append the text data to our ...
...'s request data += file.binary + '\r\n'; } // Text data is simpler // Start a new part in our
body's request data += "--" + boundary + "\r\n"; // Say it's form data, and name it data += 'content-disposition: form-data; name="' + text.name + '"\r\n'; // There's a blank line between the metadata and the data data += '\r\n'; // Append the text data to our
body's request data += text.value + "\r\n"; // Once we are done, "close" the
body's request data += "--" + boundary + "--"; // Define what happens on successful data submission XHR.addEventListener( 'load', function( event ) { alert( 'Yeah! Data sent and response loaded.' ); } ); // Define what happens in case of error XHR.addEventListener( 'error', function( e...
Advanced text formatting - Learn web development
gether. Coffee The drink that gets the world running in the morning. ...
...o Eliminate Negative Self Talk (as mentioned in Affirmations for Positive Thinking.)</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); const code = textarea.value; const userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('c...
...="input" style="min-height: 50px; width: 95%"> <p>NASA sure does some exciting work.</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); const code = textarea.value; const userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('c...
Debugging HTML - Learn web development
of HTML code. First, download our debug-example demo and save it locally. This demo is deliberately written with some built-in errors for us to explore (the HTML markup is said to be badly-formed, as opposed to well-formed). Next, open it in a browser. You will see something like this: This immediately doesn't look great; let's look at the source code to see if we can work out why (only the
body contents are shown): <h1>HTML debugging examples</h1> <p>What causes errors in HTML? <ul> <li>Unclosed elements: If an element is <strong>not closed properly, then its effect can spread to areas you didn't intend <li>Badly nested elements: Nesting elements properly is also very important for code behaving correctly. <strong>strong <em>strong emphasised?</strong> what is...
... To specify the HTML to validate, you can provide a web address, upload an HTML file, or directly input some HTML code. Active learning: Validating an HTML document Let's try this with our sample document. First, load the Markup Validation Service in one browser tab, if it isn't already open. Switch to the Validate by Direct Input tab. Copy all of the sample document's code (not just the
body) and paste it into the large text area shown in the Markup Validation Service. Press the Check button. This should give you a list of errors and other information. Interpreting the error messages The error messages are usually helpful, but sometimes they are not so helpful; with a bit of practice you can work out how to interpret these to fix your code. Let's go through the error messages ...
...d of file seen and there were open elements": This is a bit ambiguous, but basically refers to the fact there are open elements that need to be properly closed. The line numbers point to the last few lines of the file, and this error message comes with a line of code that points out an example of an open element: example: <a href="https://www.mozilla.org/>link to Mozilla homepage</a> ? </ul>? </
body>?</html> Note: An attribute missing a closing quote can result in an open element because the rest of the document is interpreted as the attribute's content. "Unclosed element ul": This is not very helpful, as the <ul> element is closed correctly. This error comes up because the <a> element is not closed, due to the missing closing quote mark. If you can't work out what every error ...
Images in HTML - Learn web development
lose if your image doesn't show up: Decoration. You should use CSS background images for decorative images, but if you must use HTML, add a blank alt="". If the image isn't part of the content, a screen reader shouldn't waste time reading it. Content. If your image provides significant information, provide the same information in a brief alt text - or even better, in the main text which every
body can see. Don't write redundant alt text. How annoying would it be for a sighted user if all paragraphs were written twice in the main content? If the image is described adequately by the main text
body, you can just use alt="". Link. If you put an image inside <a> tags, to turn an image into a link, you still must provide accessible link text. In such cases you may, either, write it inside the s...
...er).</p> <textarea id="code" class="input" style="min-height: 100px; width: 95%"> <img> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', funct...
...haracter).</p> <textarea id="code" class="input" style="min-height: 100px; width: 95%"> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', funct...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
probably use CSS animations to run this kind of simple animation. However, this kind of example is very useful to demonstrate requestAnimationFrame() usage, and you'd be more likely to use this kind of technique when doing something more complex such as updating the display of a game on each frame. Grab a basic HTML template (such as this one). Put an empty <div> element inside the <
body>, then add a ? character inside it. This circular arrow character will act as our spinner for this example. Apply the following CSS to the HTML template (in whatever way you prefer). This sets a red background on the page, sets the <
body> height to 100% of the <html> height, and centers the <div> inside the <
body>, horizontally and vertically. html { background-color: white; height: ...
...dd a ? character inside it. This circular arrow character will act as our spinner for this example. Apply the following CSS to the HTML template (in whatever way you prefer). This sets a red background on the page, sets the <
body> height to 100% of the <html> height, and centers the <div> inside the <
body>, horizontally and vertically. html { background-color: white; height: 100%; }
body { height: inherit; background-color: red; margin: 0; display: flex; justify-content: center; align-items: center; } div { display: inline-block; font-size: 10rem; } Insert a <script> element just above the closing </
body> tag. Insert the following JavaScript inside your <script> element. Here, you're storing a reference to the <div> inside a constant, setting a rotate...
...ncelAnimationFrame(rAF); Active learning: Starting and stopping our spinner In this exercise, we'd like you to test out the cancelAnimationFrame() method by taking our previous example and updating it, adding an event listener to start and stop the spinner when the mouse is clicked anywhere on the page. Some hints: A click event handler can be added to most elements, including the document <
body>. It makes more sense to put it on the <
body> element if you want to maximize the clickable area -- the event bubbles up to its child elements. You'll want to add a tracking variable to check whether the spinner is spinning or not, clearing the animation frame if it is, and calling it again if it isn't. Note: Try this yourself first; if you get really stuck, check out of our live example and ...
Making decisions in your code — conditionals - Learn web development
owing live example shows a simple theme chooser where the styling for the site is applied using a ternary operator. <label for="theme">Select theme: </label> <select id="theme"> <option value="white">White</option> <option value="black">Black</option> </select> <h1>This is my website</h1> const select = document.querySelector('select'); const html = document.querySelector('html'); document.
body.style.padding = '10px'; function update(bgColor, textColor) { html.style.backgroundColor = bgColor; html.style.color = textColor; } select.onchange = function() { ( select.value === 'black' ) ? update('black','white') : update('white','black'); } Here we've got a <select> element to choose a theme (black or white), plus a simple <h1> to display a website title. We also have a function...
...div> .output * { box-sizing: border-box; } .output ul { padding-left: 0; } .output li { display: block; float: left; width: 25%; border: 2px solid white; padding: 5px; height: 40px; background-color: #4A2DB6; color: white; } html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea...
..., textColor) { html.style.backgroundColor = bgColor; html.style.color = textColor; }</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea...
Useful string methods - Learn web development
eElement('li'); listItem.textContent = input; list.appendChild(listItem); } } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea...
...t.createElement('li'); listItem.textContent = result; list.appendChild(listItem); } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea...
...t.createElement('li'); listItem.textContent = result; list.appendChild(listItem); } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textare...
Server-side web frameworks - Learn web development
ber>[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. An HTTP GET request to get files or data from the server may encode what data is required in URL parameters or within the URL structure. An HTTP POST request to update a resource on the server will instead include the update information as "POST data" within the
body of the request. The HTTP request may also include information about the current session or user in a client-side cookie. Web frameworks provide programming-language-appropriate mechanisms to access this information. For example, the HttpRequest object that Django passes to every view function contains methods and properties for accessing the target URL, the type of request (e.g. an HTTP GET), GE...
...le from the previous section, the HTML template is passed a list variable called youngest_teams by the view. Inside the HTML skeleton we have an expression that first checks if the youngest_teams variable exists, and then iterates it in a for loop. On each iteration the template displays the team's team_name value in a list item. ...
... exists, and then iterates it in a for loop. On each iteration the template displays the team's team_name value in a list item. #best/templates/best/index.html <!DOCTYPE html> <html lang="en"> <
body> {% if youngest_teams %} <ul> {% for team in youngest_teams %} <li>{{ team.team_name }}</li> {% endfor %} </ul> {% else %} <p>No teams are available.</p> {% endif %} </
body> </html> How to select a web framework Numerous web frameworks exist for almost every programming language you might want to use (we list a few of the more popular frameworks in the following section). With so many choices, it can become difficult to work out what framework provides the best starting point for your new web application. Some of the factors that may affect your decision are: ...
Accessibility in React - Learn web development
Edit <span className="visually-hidden">{props.name}</span> </button> Focusing on our refs with useEffect To use our refs for their intended purpose, we need to import another React hook: useEffect(). useEffect() is so named because it runs after React renders a given component, and will run any side-effects that we'd like to add to the render process, which we can't run inside the main function
body. useEffect() is useful in the current situation because we cannot focus on an element until after the <Todo /> component renders and React knows where our refs are. Change the import statement of Todo.js again to add useEffect: import React, { useEffect, useRef, useState } from "react"; useEffect() takes a function as an argument; this function is executed after the component renders. Let's se...
... after the <Todo /> component renders and React knows where our refs are. Change the import statement of Todo.js again to add useEffect: import React, { useEffect, useRef, useState } from "react"; useEffect() takes a function as an argument; this function is executed after the component renders. Let's see this in action; put the following useEffect() call just above the return statement in the
body of Todo(), and pass into it a function that logs the words "side effect" to your console: useEffect(() => { console.log("side effect"); }); To illustrate the difference between the main render process and code run inside useEffect(), add another log - put this one below the previous addition: console.log("main render"); Now, open the app in your browser. You should see both messages in your...
...ed it. Try doing this as an exercise once you've got to the end. Using useEffect() to control our heading focus Now that we've stored how many tasks we previously had, we can set up a useEffect() hook to run when our number of tasks changes, which will focus the heading if the number of tasks we have now is less than with it previously was -- i.e. we deleted a task! Add the following into the
body of your App() function, just below your previous additions: useEffect(() => { if (tasks.length - prevTaskLength === -1) { listHeadingRef.current.focus(); } }, [tasks.length, prevTaskLength]); We only try to focus on our list heading if we have fewer tasks now than we did before. The dependencies passed into this hook ensure it will only try to re-run when either of those values (the num...
MathML Torture Test
msub><mi>S</mi><mi>n</mi></msub></mrow></munder><mrow><mi>?</mi><mo stretchy="false">(</mo><mi>?</mi><mo stretchy="false">)</mo></mrow><mrow><munderover><mo>?</mo><mrow><mi>i</mi><mo>=</mo><mn>1</mn></mrow><mi>n</mi></munderover><msub><mi>a</mi><mrow><mi>i</mi><mo>,</mo><msub><mi>?</mi><mi>i</mi></msub></mrow></msub></mrow></mrow></math></td> </tr> </table> CSS Content /* Table style */
body { text-align: center; } table { border: solid thin; border-collapse: collapse; margin-left: auto; margin-right: auto; } th { background-color: #ddf; border: solid thin; color: black; padding: 5px; } td { border: solid thin; padding: 5px; text-align: center; } .Asana math { font-family: Asana Math; } .Cambria math { font-family: Cambria Math; } ...
... addEventListener("change", updateMathFont, false) } window.addEventListener("load", load, false); The following test contains sample TeX formulas from Knuth's TeX book and equivalent MathML representations. It compares the renderi...
... addEventListener("change", updateMathFont, false) } window.addEventListener("load", load, false); The following test contains sample TeX formulas from Knuth's TeX book and equivalent MathML representations. It compares the rendering by the XeTeX engine using the default Latin Modern M...
NSS Sample Code Utilities_1
; PRFileDesc *inFile = NULL; inFile = PR_Open(inFileName, PR_RDONLY, 0); if (!inFile) { PR_fprintf(PR_STDERR, "Failed to open file \"%s\" (%ld, %ld).\n", inFileName, PR_GetError(), PR_GetOSError()); rv = SECFailure; goto cleanup; } if (ascii) { /* First convert ascii to binary */ SECItem filedata; char *asc, *
body; /* Read in ascii data */ rv = FileToItem(&filedata, inFile); asc = (char *)filedata.data; if (!asc) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(asc, "-----BEGIN")) != NULL) { ...
...ileToItem(&filedata, inFile); asc = (char *)filedata.data; if (!asc) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(asc, "-----BEGIN")) != NULL) { char *trailer = NULL; asc =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(asc, '\r'); /* maybe this is a MAC file */ if (
body) trailer = strstr(++
body, "-----END"); if (trailer != NULL) { *trailer = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); ...
...C file */ if (
body) trailer = strstr(++
body, "-----END"); if (trailer != NULL) { *trailer = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } } else {
body = asc; } /* Convert to binary */ rv = ATOB_ConvertAsciiToItem(der,
body); if (rv) { PR_fprintf(PR_STDERR, "error converting ascii to binary %s\n", PORT_GetError()); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } PORT_Free(filedata.data); } else { /* Rea...
EncDecMAC using token object - sample 3
text * DecryptInit(PK11SymKey *dk, unsigned char *iv, unsigned int ivLen, CK_MECHANISM_TYPE type) { return CryptInit(dk, iv, ivLen, type, CKA_DECRYPT); } /* * Read cryptographic parameters from the header file */ SECStatus ReadFromHeaderFile(const char *fileName, HeaderType type, SECItem *item, PRBool isHexData) { SECStatus rv; PRFileDesc* file; SECItem filedata; SECItem outbuf; unsigned char *non
body; unsigned char *
body; char header[40]; char trailer[40]; outbuf.type = siBuffer; file = PR_Open(fileName, PR_RDONLY, 0); if (!file) { PR_fprintf(PR_STDERR, "Failed to open %s\n", fileName); return SECFailure; } switch (type) { case SYMKEY: strcpy(header, ENCKEY_HEADER); strcpy(trailer, ENCKEY_TRAILER); break; case MACKEY: strcpy(header, MACKEY_HEADER); strcpy(trailer, MACKEY_TRAILER); break; case...
...NCKEY_HEADER); strcpy(trailer, ENCKEY_TRAILER); break; case MACKEY: strcpy(header, MACKEY_HEADER); strcpy(trailer, MACKEY_TRAILER); break; case IV: strcpy(header, IV_HEADER); strcpy(trailer, IV_TRAILER); break; case MAC: strcpy(header, MAC_HEADER); strcpy(trailer, MAC_TRAILER); break; case PAD: strcpy(header, PAD_HEADER); strcpy(trailer, PAD_TRAILER); break; } rv = FileToItem(&filedata, file); non
body = (char *)filedata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(non
body, '\r'); /* maybe this is a MAC file */ if (
body) trail...
...iledata.data; if (!non
body) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(non
body, header)) != NULL) { char *trail = NULL; non
body =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(non
body, '\r'); /* maybe this is a MAC file */ if (
body) trail = strstr(++
body, trailer); if (trail != NULL) { *trail = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); return SECFailure; } } else {
body = non
body; } cleanup: PR_Close(file); HexToBuf(
body, item, isHexData); return SECSuccess; } /* * EncryptAndMac */ SECStatus EncryptAndMac(PRFileDesc *inFile, PRFileDesc *headerFile, PRFileDesc *encFile, PK11SymKey *ek, PK1...
Utilities for nss samples
; PRFileDesc *inFile = NULL; inFile = PR_Open(inFileName, PR_RDONLY, 0); if (!inFile) { PR_fprintf(PR_STDERR, "Failed to open file \"%s\" (%ld, %ld).\n", inFileName, PR_GetError(), PR_GetOSError()); rv = SECFailure; goto cleanup; } if (ascii) { /* First convert ascii to binary */ SECItem filedata; char *asc, *
body; /* Read in ascii data */ rv = FileToItem(&filedata, inFile); asc = (char *)filedata.data; if (!asc) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(asc, "-----BEGIN")) != NULL) { ...
...ileToItem(&filedata, inFile); asc = (char *)filedata.data; if (!asc) { PR_fprintf(PR_STDERR, "unable to read data from input file\n"); rv = SECFailure; goto cleanup; } /* check for headers and trailers and remove them */ if ((
body = strstr(asc, "-----BEGIN")) != NULL) { char *trailer = NULL; asc =
body;
body = PORT_Strchr(
body, '\n'); if (!
body)
body = PORT_Strchr(asc, '\r'); /* maybe this is a MAC file */ if (
body) trailer = strstr(++
body, "-----END"); if (trailer != NULL) { *trailer = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); ...
...C file */ if (
body) trailer = strstr(++
body, "-----END"); if (trailer != NULL) { *trailer = '\0'; } else { PR_fprintf(PR_STDERR, "input has header but no trailer\n"); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } } else {
body = asc; } /* Convert to binary */ rv = ATOB_ConvertAsciiToItem(der,
body); if (rv) { PR_fprintf(PR_STDERR, "error converting ascii to binary %s\n", PORT_GetError()); PORT_Free(filedata.data); rv = SECFailure; goto cleanup; } PORT_Free(filedata.data); } else { /* Rea...
Components.utils.cloneInto
() { window.addonScriptObject.greetme(); }, false); Cloning objects that contain DOM elements By default, if the object you clone contains objects that are reflected from C++, such as DOM elements, the cloning operation will fail with an error. ...
...ct.greetme(); }, false); Cloning objects that contain DOM elements By default, if the object you clone contains objects that are reflected from C++, such as DOM elements, the cloning operation will fail with an error. ...
... var addonScriptObject = {
body: contentWindow.document.
body }; contentWindow.addonScriptObject = cloneInto(addonScriptObject, contentWindow, {wrapReflectors: true}); // page script var test = document.getElementById("test"); test.addEventListener("click", function() { console.log(window.addonScriptObject.
body.innerHTML); }, false); Access to these objects in the target scope is subject to the normal security checks. ...
nsIHTMLEditor
ue); void removeInlineProperty(in nsIAtom aProperty, in AString aAttribute); void removeInsertionListener(in nsIContentFilter inFilter); void removeList(in AString aListType); void replaceHeadContentsWithHTML(in AString aSourceToInsert); void selectElement(in nsIDOMElement aElement); void setBackgroundColor(in AString aColor); void set
BodyAttribute(in AString aAttr, in AString aValue); void setCaretAfterElement(in nsIDOMElement aElement); void setCSSInlineProperty(in nsIAtom aProperty, in AString aAttribute, in AString aValue); void setDocumentTitle(in AString aTitle); void setInlineProperty(in nsIAtom aProperty, in AString aAttribute, in AString aValue); void setParagraphFormat(in AStri...
... Return value pasteNoFormatting() Paste the text in the OS clipboard at the cursor position, replacing the selected text (if any), but strip out any HTML styles and formatting. void pasteNoFormatting( in long aSelectionType ); Parameters aSelectionType rebuildDocumentFromSource() Rebuild the entire document from source HTML Needed to be able to edit HEAD and other outside-of-
BODY content. void rebuildDocumentFromSource( in AString aSourceString ); Parameters aSourceString HTML source string of the entire new document. removeAllDefaultProperties() Unregisters all default style properties with the editor. void removeAllDefaultProperties(); Parameters None. removeAllInlineProperties() Deletes all the inline properties from all text in the current selection.
...children of <HEAD> with string of HTML source. void replaceHeadContentsWithHTML( in AString aSourceToInsert ); Parameters aSourceToInsert selectElement() Set the selection at the suppled element. void selectElement( in nsIDOMElement aElement ); Parameters aElement An element in the document. setBackgroundColor() Set the value of the "bgcolor" attribute on the document's <
body> element. void setBackgroundColor( in AString aColor ); Parameters aColor The HTML color string, such as "#ffccff" or "yellow" set
BodyAttribute() Set an attribute on the document's <
body> element such as text, link, background colors. void set
BodyAttribute( in AString aAttr, in AString aValue ); Parameters aAttr The attribute to be set. aValue The value of the attribute. ...
nsIMsgSearchTerm
true if matches */ boolean matchJunkPercent(in unsigned long aJunkPercent); matchJunkScoreOrigin /* * Test search term match for junkscoreorigin * @param aJunkScoreOrigin Who set junk score? ...
... * @param aScopeTerm scope of search * @param aOffset offset of message in message store. * @param aLength length of message. * @param aCharset folder charset. * @param aMsg db msg hdr of message to match. * @param aDB db containing msg header. */ boolean match
Body(in nsIMsgSearchScopeTerm aScopeTerm, in unsigned lon...
...ScoreOrigin(in string aJunkScoreOrigin); match
Body /** * Test if the
body of the passed in message matches "this" search term. * @param aScopeTerm scope of search * @param aOffset offset of message in message store. * @param aLength length of message. * @param aCharset folder charset. * @param aMsg db msg hdr of message to match. * @param aDB db containing msg header. ...
nsISmsService
12) Implemented by: @mozilla.org/sms/smsservice;1. ...
... timestamp A Date object...
... timestamp A Date object with the timestamp of the message. read A Boolean indicating whether a message is marked as read or unread. ...
nsITraceableChannel
m', 'setInputStream'); var BinaryOutputStream = CC('@mozilla.org/binaryoutputstream;1', 'nsIBinaryOutputStream', 'setOutputStream'); var StorageStream = CC('@mozilla.org/storagestream;1', 'nsIStorageStream', 'init'); function TracingListener() { this.receivedChunks = []; // array for incoming data. ...
...ta = iStream.readBytes(aCount); this.receivedChunks.push(data); oStream.writeBytes(data, aCount); this.originalListener.onDataAvailable(aRequest, aContext, sStream.newInputStream(0), aOffset, aCount); }, onStartRequest: function(aRequest, aContext) { this.originalListener.onStartRequest(aRequest, aContext); }, onStopRequest: function(aRequest, aContext, aStatusCode) { this.response
Body = this.receivedChunks.join(""); delete this.receivedChunks; this.responseStatus = aStatusCode; this.originalListener.onStopRequest(aRequest, aContext, aStatusCode); this.deferredDone.resolve(); }, QueryInterface: function(aIID) { if (aIID.equals(Ci.nsIStreamListener) || aIID.equals(Ci.nsISupports)) { return this; } throw Cr.NS_NOINTERFACE; } }; var httpResponseObserver = { ...
...; var httpResponseObserver = { observe: function(aSubject, aTopic, aData) { var newListener = new TracingListener(); aSubject.QueryInterface(Ci.nsITraceableChannel); newListener.originalListener = aSubject.setNewListener(newListener); /////// END - DO NOT EDIT newListener.promiseDone.then( function() { // no error happened console.log('yay response done:', newListener.response
Body); }, function(aReason) { // promise was rejected, right now i didnt set up rejection, but i should listen to on abort or bade status code then reject maybe } ).catch( function(aCatch) { console.error('something went wrong, a typo by dev probably:', aCatch); } ); } }; Services.obs.addObserver(httpResponseObserver, 'http-on-examine-response', false); // Services.obs.rem...
nsIXULTemplateBuilder
result produced by the query. A rule consists of conditions that cause a rule to be either accepted or rejected. The condition syntax allows for common conditional handling; additional filtering may be applied by adding a custom filter to a rule with the builder's addRuleFilter() method. If a result passes a rule's conditions, this is considered a match, and the content within the rule's <action>
body is inserted as a sibling of the <template>, assuming the template builder creates real DOM content. Only one rule will match a result. For a tree builder, for example, the content within the action
body is used to create the tree rows instead. A matching result must have its ruleMatched() method called. When a result no longer matches, the result's hasBeenRemoved() method must be called. Optional...
...Each of these declared bindings must be supplied to the query processor via its addBinding() method. The bindings are evaluated after a rule has matched. Templates may generate content recursively, using the previous iteration's results as reference point to invoke the same queries. ...
...hrows NS_ERROR_NULL_POINTER if either argument is null, or NS_ERROR_INVALID_ARG if the ids don't match resultBindingChanged() Informs the template builder that one or more of the optional bindings for a result has changed. In this case, the rules are not reapplied as it is expected that the same rule will still apply. The builder will resynchronize any variables that are referenced in the action
body. void resultBindingChanged( in nsIXULTemplateResult aResult ); Parameters aResult The result to change Errors Throws NS_ERROR_NULL_POINTER if aResult is null getResultForId() Returns the result for a given ID. Only one such result is returned and is always the result with that ID associated with the active match. This method will return null is there is no result for the ID. nsIXULTemplateR...
Paint Flashing Tool - Firefox Developer Tools
k the "Highlight painted area" icon in the Toolbox again. Example: CSS transitions One area where implementation choices can affect repaint efficiency is in CSS transitions. The example below shows two different ways to move an element using a CSS transition. The first way applies the transition to the element's margin-left, while the second way moves the element using the transform property. ...
... an element using a CSS transition. The first way applies the transition to the element's margin-left, while the second way moves the element using the transform property. ...
...v> <div class="moving-box" id="moving-box-transform">Transition using transform</div> </div> </
body> #container { border: 1px solid; } .moving-box { height: 20%; width:20%; margin: 2%; padding: 2%; background-color: blue; color: white; font-size: 24px; } #moving-box-left-margin { transition: margin-left 4s; } #moving-box-transform { transition: transform 4s; }
body:hover #moving-box-left-margin{ margin-left: 74%; }
body:hover #moving-box-transform { transform: translate(300%); } To see the transition, move the mouse into the space below: Now switch paint flashing on, and try it again. You should see that the margin-left version triggers a series of repaints as the element moves, while the transform version only causes repaints in the start and end ...
AbstractRange - Web APIs
is any text inside it. In order to set a range endpoint within the text of an element, be sure to find the text node inside the element: let startElem = document.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. The end point is set to be the middle of the first child of the span, and then the range is used to copy the contents of the range. Ranges and the hierarchy of the DOM In order to define a range of characters within a document in a...
...s</strong> is a paragraph.</p> Imagine using a Range to extract the word "paragraph" from this. The code to do that looks like the following: let paraNode = document.querySelector("p"); let paraTextNode = paraNode.childNodes[1]; let range = document.createRange(); range.setStart(paraTextNode, 6); range.setEnd(paraTextNode, paraTextNode.length-1); let fragment = range.cloneContents(); document.
body.appendChild(fragment); First we get references to the paragraph node itelf as well as to the second child node within the paragraph. The first child is the <strong> element. The second child is the text node " is a paragraph.". With the text node reference in hand, we create a new Range object by calling createRange() on the Document itself. We set the starting position of the range to the six...
...e text node's string, and the end position to the length of the text node's string minus one. This sets the range to encompass the word "paragraph". We then finish up by calling cloneContents() on the Range to create a new DocumentFragment object which contains the portion of the document encompassed by the range. After that, we use appendChild() to add that fragment at the end of the document's
body, as obtained from document.
body. The result looks like this: Specifications Specification Status Comment DOMThe definition of 'AbstractRange' in that specification. Living Standard ...
AnalyserNode.getFloatFrequencyData() - Web APIs
shows basic usage of an AudioContext to connect a MediaElementAudioSourceNode to an AnalyserNode. While the audio is playing, we collect the frequency data repeatedly with requestAnimationFrame() and draw a "winamp bargraph style" to a <canvas> element. For more complete applied examples/information, check out our Voice-change-O-matic-float-data demo (see the source code too). <!doctype html> <
body> <script> const audioCtx = new AudioContext(); //Create audio source //Here, we use an audio file, but this could also be e.g. microphone input const audioEle = new Audio(); audioEle.src = 'my-audio.mp3';//insert file name here audioEle.autoplay = true; audioEle.preload = 'auto'; const audioSourceNode = audioCtx.createMediaElementSource(audioEle); //Create analyser node const analyserNode = aud...
...inCount; const dataArray = new Float32Array(bufferLength); //Set up audio node network audioSourceNode.connect(analyserNode); analyserNode.connect(audioCtx.destination); //Create 2D canvas const canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = 0; canvas.style.left = 0; canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.
body.appendChild(canvas); const canvasCtx = canvas.getContext('2d'); canvasCtx.clearRect(0, 0, canvas.width, canvas.height); function draw() { //Schedule next redraw requestAnimationFrame(draw); //Get spectrum data analyserNode.getFloatFrequencyData(dataArray); //Draw black background canvasCtx.fillStyle = 'rgb(0, 0, 0)'; canvasCtx.fillRect(0, 0, canvas.width, canvas.height); //Dr...
... Working Draft ...
BroadcastChannel: message event - Web APIs
nts of a <textarea> when the user clicks a button. There are two "receiver" iframes that listen to the broadcast message and write the result into a <div> element. ...
...-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; 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; }); Receiver 2 <h1>Receiver 2</h1> <div id="received"></div> ...
... { 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; }); 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 Stat...
Manipulating video using canvas - Web APIs
element with a canvas, you can manipulate video data in real time to incorporate a variety of visual effects to the video being displayed. This tutorial demonstrates how to perform chroma-keying (also known as the "green screen effect") using JavaScript code. The document content The HTML document used to render this content is shown below. ...
...low. ...
... margin: 10px; background:#3B3B3B; } </style> </head> <
body> <div> <video id="video" src="media/video.mp4" controls="true" crossorigin="anonymous"/> </div> <div> <canvas id="c1" width="160" height="96"></canvas> <canvas id="c2" width="160" height="96"></canvas> </div> <script type="text/javascript" src="processor.js"></script> </
body> </html> The key bits to take away from this are: This document establishes two canvas elements, with the IDs c1 and c2. Canvas c1 is used to display the current frame of the original video, while c2 is used to display the video after performing the chroma-keying effect; c2 is preloaded with the still image that will be used to replace the green background in the video. The JavaScript code...
Basic animations - Web APIs
{ requestAnimationFrame(anim); c.fillStyle = "rgba(0,0,0,0.05)"; c.fillRect(0, 0, cn.width, cn.height); a.forEach(function(e, i) { e.dr(); }); } </script> <style> #cw { position: fixed; z-index: -1; }
body { margin: 0; padding: 0; background-color: rgba(0,0,0,0.05); } </style> </head> <
body> <canvas id="cw"></canvas> </
body> </html> OutPut Snake Game <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale...
... </style> </head> <
body> <canvas id="cw"></canvas> </
body> </html> OutPut Snake Game <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Nokia 1100:snake..Member berries</title> </head> <
body> <div class="keypress hide"> <div class="up" onclick="emit(38)">↑</div> <div class="right" onclick="emit(39)">→</div> <div class="left" onclick="emit(37)">←</div> <div class="down" onclick="emit(40)">↓</div> </div> <div class="banner" id="selector"> <div> Time :<span id="time">0</span> </div> <...
... <div class="down" onclick="emit(40)">↓</div> </div> <div class="banner" id="selector"> <div> Time :<span id="time">0</span> </div> <div>LousyGames (C)</div> <div> Score :<span id="score">0</span> </div> <div class="touch off" onclick="touch(this)">touch</div> </div> <canvas id="main"></canvas> </
body> <style>
body { margin: 0; overflow: hidden; background: #000 } .banner { text-align: center; color: #fff; background: #3f51b5; line-height: 29px; position: fixed; left: 0; top: 0; right: 0; font-family: monospace; height: 30px; opacity: .4; display: flex; t...
Basic usage of canvas - Web APIs
This function, or one like it, could also be called using window.setTimeout(), window.setInterval(), or any other event handler, as long as th...
...This function, or one like it, could also be called using window.setTimeout(), window.setInterval(), or any other event handler, as long as the page has been loaded first. Here is how a template would look in action. As shown her...
..."/> <script type="application/javascript"> function draw() { var canvas = document.getElementById('canvas'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgb(200, 0, 0)'; ctx.fillRect(10, 10, 50, 50); ctx.fillStyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillRect(30, 30, 50, 50); } } </script> </head> <
body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </
body> </html> This example looks like this: ScreenshotLive sample << PreviousNext >> ...
Document.forms - Web APIs
collection = document.forms; Value An HTMLCollection object listing all of the document's forms. Each item in the collection is a HTMLFormElement representing a single <form> element. If the document has no forms, the returned collection is empty, with a length of zero. ...
... <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="alert(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...
... Living Standard Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'Document.forms' in that specification. Obsolete Initial definition. ...
Document.width - Web APIs
Note: Starting in Gecko 6.0, document.width is no longer supported. Instead, use document.
body.clientWidth. See element.clientWidth. Returns the width of the <
body> element of the current document in pixels. Not supported by Internet Explorer. ...
...rting in Gecko 6.0, document.width is no longer supported. Instead, use document.
body.clientWidth. See element.clientWidth. Returns the width of the <
body> element of the current document in pixels. Not supported by Internet Explorer. ...
...nger supported. Instead, use document.
body.clientWidth. See element.clientWidth. Returns the width of the <
body> element of the current document in pixels. Not supported by Internet Explorer. ...
EventTarget.addEventListener() - Web APIs
1 = function(event) { console.log(this.name); // undefined, as |this| is the element }; this.onclick2 = function(event) { console.log(this.name); // 'Something Good', as |this| is bound to newly created object }; element.addEventListener('click', this.onclick1, false); element.addEventListener('click', this.onclick2.bind(this), false); // Trick } const s = new Something(document.
body); Another solution is using a special function called handleEvent() to catch any events: const Something = function(element) { // |this| is a newly created object this.name = 'Something Good'; this.handleEvent = function(event) { console.log(this.name); // 'Something Good', as this is bound to newly created object switch(event.type) { case 'click': // some code here...
...ere... ...
...hers) to block the browser's main thread while it is attempting to handle scrolling, resulting in possibly enormous reduction in performance during scroll handling. To prevent this problem, some browsers (specifically, Chrome and Firefox) have changed the default value of the passive option to true for the touchstart and touchmove events on the document-level nodes Window, Document, and Document.
body. This prevents the event listener from being called, so it can't block page rendering while the user is scrolling. Note: See the compatibility table below if you need to know which browsers (and/or which versions of those browsers) implement this altered behavior. You can override this behavior by explicitly setting the value of passive to false, as shown here: /* Feature detection */ let pa...
HTMLTableElement - Web APIs
first element that is neither a <caption>, a <colgroup>, nor a <thead>, or as the last child if there is no such element, and the first <tfoot> that is a child of this element is removed from the tree, if any. HTMLTableElement.rowsRead only Returns a live HTMLCollection containing all the rows of the element, that is all <tr> that are a child of the element, or a child of one of its <thead>, <t
body> and <tfoot> children. The rows members of a <thead> appear first, in tree order, and those members of a <t
body> last, also in tree order. The HTMLCollection is live and is automatically updated when the HTMLTableElement changes. HTMLTableElement.tBodiesRead only Returns a live HTMLCollection containing all the <t
body> of the element. The HTMLCollection is live and is automatically updated whe...
...new one is created and inserted in the tree as the first child of the <table> element. HTMLTableElement.deleteCaption() Removes the first <caption> that is a child of the element. HTMLTableElement.insertRow() Returns an HTMLTableRowElement representing a new row of the table. It inserts it in the rows collection immediately before the <tr> element at the given index position. If necessary a <t
body> is created. If the index is -1, the new row is appended to the collection. If the index is smaller than -1 or greater than the number of rows in the collection, a DOMException with the value IndexSizeError is raised. HTMLTableElement.deleteRow() Removes the row corresponding to the index given in parameter. If the index value is -1 the last row is removed; if it smaller than -1 or greater than...
...OMException with the value IndexSizeError is raised. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement' in that specification. Living Standard Added the sortable property and the stopSorting() method. HTML5The definition of 'HTMLTableElement' in that specification. Recommendation Added the createT
Body() method. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTMLTableElement' in that specification. Obsolete Defined when caption, tHead, tFoot, insertRow(), and deleteRow() raise exceptions. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTMLTableElement' in that specification. Obsolete Initial definition. ...
HTMLTableRowElement.rowIndex - Web APIs
The HTMLTableRowElement.rowIndex read-only property represents the position of a row in relation to the whole <table>. Even when the <thead>, <t
body>, and <tfoot> elements are out of order in the HTML, browsers render the table in the right order. Therefore the rows count from <thead> to <t
body>, from <t
body> to <tfoot>. Syntax var index = HTMLTableRowElement.rowIndex Value Returns the index of the row, or -1 if the row is not part of a table. Example This example uses JavaScript to label all the row numbers in a table. ...
... table in the right order. Therefore the rows count from <thead> to <t
body>, from <t
body> to <tfoot>. Syntax var index = HTMLTableRowElement.rowIndex Value Returns the index of the row, or -1 if the row is not part of a table. Example This example uses JavaScript to label all the row numbers in a table. ...
...x Value Returns the index of the row, or -1 if the row is not part of a table. Example This example uses JavaScript to label all the row numbers in a table. ...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
ding on the current execution context. queueMicrotask(() => { /* code to run in the microtask here */ }); The microtask function itself takes no parameters, and does not return a value. When to use microtasks In this section, we'll take a look at scenarios in which microtasks are particularly useful. Generally, it's about capturing or checking results, or performing cleanup, after the main
body of a JavaScript execution context exits, but before any event handlers, timeouts and intervals, or other callbacks are processed. When is that useful? The main reason to use microtasks is simply that: to ensure consistent ordering of tasks, even when results or data is available synchronously, but while simultaneously reducing the risk of user-discernible delays in operations. Ensuring orderin...
... to the same fetch() operation, without potentially having other tasks such as timeouts or the like delay the transmission. The server will receive the JSON string, then will presumably decode it and process the messages it finds in the resulting array. 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. HTML <pre id="log"> </pre> JavaScript The code below is used to log the output. let logElem = document.getElementById("log"); let log = s => logElem.innerHTML += s + "<br>"; In the following code, we see a call to queueMicrotask() used to schedule a microtask to run. This call is bracketed by calls to log(), a custom function that simply outputs...
...es a microtask. This is bracketed by calls to log() to output additional messages. let callback = () => log("Regular timeout callback has run"); let urgentCallback = () => log("*** Oh noes! An urgent callback has run!"); log("Main program started"); setTimeout(callback, 0); queueMicrotask(urgentCallback); log("Main program exiting"); Result Note that the output logged from the main program
body appears first, followed by the output from the microtask, followed by the timeout's callback. That's because when the task that's handling the execution of the main program exits, the microtask queue gets processed before the task queue on which the timeout callback is located. Remembering that tasks and microtasks are kept on separate queues, and that microtasks run first will help keep this str...
MouseEvent.relatedTarget - Web APIs
g device exited from The EventTarget the pointing device entered to For events with no secondary target, relatedTarget returns null. FocusEvent.relatedTarget is a similar property for focus events. Syntax var target = instanceOfMouseEvent.relatedTarget Return value An EventTarget object or null. Example Try moving your mouse cursor into and out of the red and blue boxes. ...
...exited from The EventTarget the pointing device entered to For events with no secondary target, relatedTarget returns null. FocusEvent.relatedTarget is a similar property for focus events. Syntax var target = instanceOfMouseEvent.relatedTarget Return value An EventTarget object or null. Example Try moving your mouse cursor into and out of the red and blue boxes. ...
...elatedTarget returns null. FocusEvent.relatedTarget is a similar property for focus events. Syntax var target = instanceOfMouseEvent.relatedTarget Return value An EventTarget object or null. Example Try moving your mouse cursor into and out of the red and blue boxes. ...
Online and offline events - Web APIs
y on Windows, Linux, and OS X. This property existed in older versions of Firefox and Internet Explorer (the specification based itself off of these prior implementations), so you can begin using it immediately. Network status autodetection was implemented in Firefox 2. "online" and "offline" events Firefox 3 introduces two new events: "online" and "offline". These two events are fired on the <
body> of each page when the browser switches between online and offline mode. Additionally, the events bubble up from document.
body, to document, ending at window. Both events are non-cancellable (you can't prevent the user from coming online, or going offline). Firefox 41 fires these events when the OS reports a change in network connectivity on Windows, Linux, and OS X. You can register listeners ...
...e up from document.
body, to document, ending at window. Both events are non-cancellable (you can't prevent the user from coming online, or going offline). Firefox 41 fires these events when the OS reports a change in network connectivity on Windows, Linux, and OS X. You can register listeners for these events in a few familiar ways: using addEventListener on the window, document, or document.
body by setting the .ononline or .onoffline properties on document or document.
body to a JavaScript Function object. (Note: using window.ononline or window.onoffline will not work for compatibility reasons.) by specifying ononline="..." or onoffline="..." attributes on the <
body> tag in the HTML markup. Example There's a simple test case that you can run to verify that the events are working (doe...
...cument.
body to a JavaScript Function object. (Note: using window.ononline or window.onoffline will not work for compatibility reasons.) by specifying ononline="..." or onoffline="..." attributes on the <
body> tag in the HTML markup. 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). Here's the JavaScript part: window.addEventListener('load', function() { var status = document.getElementById("status"); var log = document.getElementById("log"); function updateOnlineStatus(event) { var condition = navigator.onLine ? "online" : "offline"; status.className = condition; status.innerHTML = condition.toUpperCase(); log.insertAdjacentHTML("beforeend", "Ev...
NavigatorPlugins.plugins - Web APIs
e Flash'); if (typeof flash != 'object') { // flash is not present return undefined; } if(flash.version){ return flash.version; } else { //No version property (e.g. in Chrome) return flash.description.replace(/Shockwave Flash /,""); } } The following example displays information about the installed plugin(s). ...
...(e.g. in Chrome) return flash.description.replace(/Shockwave Flash /,""); } } The following example displays information about the installed plugin(s). ...
... Chrome) return flash.description.replace(/Shockwave Flash /,""); } } The following example displays information about the installed plugin(s). ...
Node - Web APIs
lementation implements a specific feature and this feature is supported by the specific node. Node.setUserData() Allows a user to attach, or remove, DOMUserData to the node. Examples Remove all children nested within a node function removeAllChildren(element) { while (element.firstChild) { element.removeChild(element.firstChild) } } Sample usage /* ... ...
...ture is supported by the specific node. Node.setUserData() Allows a user to attach, or remove, DOMUserData to the node. Examples Remove all children nested within a node function removeAllChildren(element) { while (element.firstChild) { element.removeChild(element.firstChild) } } Sample usage /* ... an alternative to document.
body.innerHTML = "" ... ...
... Living Standard Added the following methods: getRootNode() DOM4The definition of 'Node' in that specification. Obsolete Removed the following properties: attributes, namespaceURI, prefix, and localName. Removed the f...
Notification.Notification() - Web APIs
and rtl (although most browsers seem to ignore these settings.) lang: The notification's language, as specified using a DOMString representing a BCP 47 language tag. See the Sitepoint ISO 2 letter language codes page for a simple reference. badge: A USVString containing the URL of the image used to represent the notification when there isn't enough space to display the notification itself.
body: A DOMString representing the
body text of the notification, which is displayed below the title. tag: A DOMString representing an identifying tag for the notification. icon: A USVString containing the URL of an icon to be displayed in the notification. image: a USVString containing the URL of an image to be displayed in the notification. data: Arbitrary data that you want associated with ...
...n was selected by the user. silent: A Boolean specifying whether the notification is silent (no sounds or vibrations issued), regardless of the device settings. The default is false, which means it won't be silent. Example In our Emogotchi demo (see source code), we run a spawnNotification() function when we want to trigger a notification. ...
...e, which means it won't be silent. Example In our Emogotchi demo (see source code), we run a spawnNotification() function when we want to trigger a notification. The function is passed parameters to specify the
body, icon, and title we want, and then it creates the necessary options object and triggers the notification by using the Notification() constructor. function spawnNotification(the
Body,theIcon,theTitle) { var options = {
body: the
Body, icon: theIcon } var n = new Notification(theTitle,options); } Specifications Specification Status Comment Notifications APIThe definition of 'Notification() constructor' in that specification. Living Standard Initial definition. ...
PluginArray - Web APIs
hods PluginArray.item Returns the Plugin at the specified index into the array. PluginArray.namedItem Returns the Plugin with the specified name. PluginArray.refresh Refreshes all plugins on the current page, optionally reloading documents. Examples The following example function returns the version of the Shockwave Flash plugin. ...
... all plugins on the current page, optionally reloading documents. Examples The following example function returns the version of the Shockwave Flash plugin. ...
...gins on the current page, optionally reloading documents. Examples The following example function returns the version of the Shockwave Flash plugin. ...
Multi-touch interaction - Web APIs
// background and border remove_event(ev); update_background(ev); ev.target.style.border = "1px solid black"; } Application UI The application uses <div> elements for the touch areas and provides buttons to enable logging and to clear the log. ...
... border remove_event(ev); update_background(ev); ev.target.style.border = "1px solid black"; } Application UI The application uses <div> elements for the touch areas and provides buttons to enable logging and to clear the log. To prevent the browser's default touch behavior from overriding this application's pointer handling, the touch-action property is applied to the <
body> element. ...
... Cache management These functions manage the global event caches evCache1, evCache2 and evCache3. function get_cache(ev) { // Return the cache for this event's target element switch(ev.target.id) { case "target1": return evCache1; case "target2": return evCache2; case...
Pinch zoom gestures - Web APIs
number of pointers down is less than two then reset diff tracker if (evCache.length < 2) { prevDiff = -1; } } Application UI The application uses a <div> element for the touch area and provides buttons to enable logging and to clear the log. ...
...rs down is less than two then reset diff tracker if (evCache.length < 2) { prevDiff = -1; } } Application UI The application uses a <div> element for the touch area and provides buttons to enable logging and to clear the log. To prevent the browser's default touch behavior from overriding this application's pointer handling, the touch-action property is applied to the <
body> element. ...
... Cache management This function helps manage the global event caches evCache. function remove_event(ev) { // Remove this event from the target's cache for (var i = 0; i < evCache.length; i++) { if (evCache[i].pointerId == ev.pointerId) { evCache.splice(i, 1); break;...
ReadableStream.pipeThrough() - Web APIs
erations can then be aborted via the corresponding AbortController. Return value The readable side of the transformStream. Exceptions TypeError The writable and/or readable property of transformStream are undefined. ...
...NG 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. Next, we log the contents of the readable stream, use pipeThrough() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too. ...
...rm-stream for the source code), an image is fetched and its
body retrieved as a ReadableStream. Next, we log the contents of the readable stream, use pipeThrough() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too. // Fetch the original image fetch('png-logo.png') // Retrieve its
body as ReadableStream .then(response => response.
body) .then(rs => logReadableStream('Fetch Response Stream', rs)) // Create a gray-scaled PNG stream out of the original .then(
body =>
body.pipeThrough(new PNGTransformStream())) .then(rs => logReadableStream('PNG Chunk Stream', rs)) Specifications Specification Status Comment StreamsThe definition of 'pipeThrough()' in that specification. Living Standard Initial defini...
StyleSheet.media - Web APIs
a property of the StyleSheet interface specifies the intended destination media for style information. It is a read-only, array-like MediaList object and can be removed with deleteMedium() and added with appendMedium(). ...
... intended destination media for style information. It is a read-only, array-like MediaList object and can be removed with deleteMedium() and added with appendMedium(). ...
... Working Draft ...
Synchronous and asynchronous requests - Web APIs
validAccessError. Example: HTTP synchronous request This example demonstrates how to make a simple synchronous request. var request = new XMLHttpRequest(); request.open('GET', '/bar/foo.txt', false); // `false` makes the request synchronous request.send(null); if (request.status === 200) { console.log(request.responseText); } Line 3 sends the request. The null parameter indicates that no
body content is needed for the GET request. Line 5 checks the status code after the transaction is completed. If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console. Example: Synchronous HTTP request from a Worker One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker. example.htm...
... XMLHttpRequest within a Worker. ...
...pRequest within a Worker. ...
XSLT Basic Example - Web APIs
Figure 1 shows the source of the basic XSLT example. The XML document (example.xml) contains the information about the article. Using the ?xml-stylesheet? processing instruction, it links to the XSLT stylesheet (example.xsl) via its href attribute. ...
...icle's title and then says to process all templates (via apply-templates) that match Author nodes which are children of the Authors node. Figure 1 : Simple XSLT Example XML Document (example.xml) : <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="example.xsl"?> <Article> <Title>My Article</Title> <Authors> <Author>Mr. Foo</Author> <Author>Mr. ...
...rocess all templates (via apply-templates) that match Author nodes which are children of the Authors node. Figure 1 : Simple XSLT Example XML Document (example.xml) : <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="example.xsl"?> <Article> <Title>My Article</Title> <Authors> <Author>Mr. Foo</Author> <Author>Mr. ...
ARIA: Main role - Accessibility
r document. The <main> element has a role of main. Developers should always prefer using the correct semantic HTML element over using ARIA. Documents and applications can be nested in the DOM, which may lead to having more than one main element as DOM descendants. If this is the case, include aria-owns to identify the relationship of the main to it's document or application ancestor. 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. If a document contains two main roles, say updating page content when triggered by JavaScript, the inact...
...ip navigation Skip navigation, also known as "skipnav", is a technique that allows an assistive technology user to quickly bypass large sections of repeated content (main navigation, info banners, etc.). This allows the user to access the main content of the page faster. Adding an id attribute to the element with a declaration of role="main" allows it to be a target of a skip navigation link. ...
...on, info banners, etc.). This allows the user to access the main content of the page faster. Adding an id attribute to the element with a declaration of role="main" allows it to be a target of a skip navigation link. <
body> <a href="#main-content">Skip to main content</a> <!-- navigation and header content --> <div id="main-content" role="main"> <!-- main page content --> </div> </
body> WebAIM: "Skip Navigation" Links Added benefits Certain technologies such as browser extensions can generate lists of all landmark roles present on a page, allowing non-screen reader users to also quickly identify and navigate to large sections of the document. Landmarks browser extension Specifications Specification Status Accessible Rich Internet Applications (...
ARIA: table role - Accessibility
instead. To create an ARIA table, add role="table" to the container element. Within that container, each row has role="row" set and contains child cells. Each cell has a role of either columnheader, rowheader, or simply cell. Rows can be children of the table or within a rowgroup. The table caption can be defined via aria-labelledby or aria-label. All other semantic table elements, such as <t
body>, <thead>, <tr>, <th>, and <td> need to be added via associated roles, such as rowgroup, row, columnheader, and cell. If the table contains sortable columns or rows, the aria-sort attribute should be added on the header cell element (not the table itself). If any rows or columns are hidden, the aria-colcount or aria-rowcount should be included indicating the total number of columns or rows, resp...
...erface allows the rearranging of cell order or otherwise changing individual cell order such as through drag and drop, use grid or treegrid instead. Note: Using a native HTML table element whenever possible is strongly encouraged. Associated WAI-ARIA roles, states, and properties role="rowgroup" An optional child of the table, the row group encapsulates a group of rows, similar to thead, t
body, and tfoot. role="row" A row within the table, and optionally within a rowgroup, that is a container for one or more cells, columnheaders, or rowheaders. aria-describedby attribute Takes as its value the id of the element that serves as a description for the table. aria-label attribute The aria-label provides an accessible name for the table. aria-colcount attribute This attribute is on...
...ex="24"> <span role="cell">term</span> <span role="cell">dt</span> </div> </div> </div> The above is part of a table. While the full table has 81 entries, as indicated by the aria-rowcount property, only four are currently visible. The columns are sortable, but not currently sorted, as indicated by the aria-sort property on the column headers. Best practices Only use table, t
body, thead, tr, th, td, etc., for data table structure. You can add these ARIA roles to ensure accessibility should the native semantics of the table be removed, such as with CSS. A relevant use case for the ARIA table role is when CSS's display property overrides the native semantics of a table, such as by display: grid. In this case, you can use the ARIA table roles to re-add the semantics. Added ...
:host-context() - CSS: Cascading Style Sheets
ttributes applied to ancestor elements. One typical use of this is with a descendant selector expression -- for example h1 -- to select only instances of the custom element that are inside an <h1>. ...
...dark-theme class is applied to <
body>. Note: This has no effect when used outside a shadow DOM. ...
...e: This has no effect when used outside a shadow DOM. ...
border-collapse - CSS: Cascading Style Sheets
nt cells have distinct borders (the separated-border table rendering model). ...
... <t
body> <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> <tr><td class="ch">Chrome</td> <td class="bk">Blink</td></tr> <tr><td class="op">Opera</td> <td class="bk">Blink</td></tr> </t
body> </table> <table class="collapse"> <caption><code>border-collapse: collapse</code></caption> <t
body> <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> <tr><td class="ch">Chrome</td> <td c...
... <t
body> <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> <tr><td class="ch">Chrome</td> <td class="bk">Blink</td></tr> <tr><td class="op">Opera</td> <td class="bk">Blink</td></tr> </t
body> </table> CSS .collapse { border-collapse: collapse; } .separate { border-collapse: separate; } table { display: inline-table; margin: 1em; border: dashed 5px; } table th, table td { border: solid 3px; } .fx { border-color: orange blue; } .gk { border-color: black red; } .ed { border-color: blue gold; } .tr { border-color: aqua; } .sa { border-color: silver blue; } .wk { border-...
repeating-linear-gradient() - CSS: Cascading Style Sheets
nition of the gradient line List of color stops where <side-or-corner> = [left | right] || [top | bottom] and <color-stop-list> = [ <linear-color-stop> [, <color-hint>? ]? ]#, <linear-color-stop> and <linear-color-stop> = <color> [ <color-stop-length> ]? ...
...stops where <side-or-corner> = [left | right] || [top | bottom] and <color-stop-list> = [ <linear-color-stop> [, <color-hint>? ]? ]#, <linear-color-stop> and <linear-color-stop> = <color> [ <color-stop-length> ]? ...
...> ] Examples Zebra stripes
body { width: 100vw; height: 100vh; }
body { background-image: repeating-linear-gradient(-45deg, transparent, transparent 20px, black 20px, black 40px); /* with multiple color stop lengths */ background-image: repeating-linear-gradient(-45deg, transparent 0 20px, black 20px 40px); } Ten repeating horizontal bars
body { width: 100vw; height: 100vh; }
body { background-image: repeating-linear-gradient(to bottom, rgb(26,198,204), rgb(26,198,204) 7%, rgb(100,100,100) 10%); } Because the last color stop is 10% and the gradient is vertical, each gradient in the repeated gradient is 10% of the height, fitting 10 horizontal bars. Note: Please see Using CSS gradients for more examples. ...
Making content editable - Developer guides
oc.innerHTML = oContent.toString(); } oDoc.contentEditable = true; } oDoc.focus(); } function printDoc() { if (!validateMode()) { return; } var oPrntWin = window.open("","_blank","width=450,height=470,left=400,top=100,menubar=yes,toolbar=no,location=no,scrollbars=yes"); oPrntWin.document.open(); oPrntWin.document.write("<!doctype html><html><head><title>Print<\/title><\/head><
body onload=\"print();\">" + oDoc.innerHTML + "<\/
body><\/html>"); oPrntWin.document.close(); } </script> <style type="text/css"> .intLink { cursor: pointer; } img.intLink { border: 0; } #toolBar1 select { font-size:10px; } #textBox { width: 540px; height: 200px; border: 1px #000000 solid; padding: 12px; overflow: scroll; } #textBox #sourceText { padding: 0; margin: 0; min-width: 498...
....close(); } </script> <style type="text/css"> .intLink { cursor: pointer; } img.intLink { border: 0; } #toolBar1 select { font-size:10px; } #textBox { width: 540px; height: 200px; border: 1px #000000 solid; padding: 12px; overflow: scroll; } #textBox #sourceText { padding: 0; margin: 0; min-width: 498px; min-height: 200px; } #editMode label { cursor: pointer; } </style> </head> <
body onload="initDoc();"> <form name="compForm" method="post" action="sample.php" onsubmit="if(validateMode()){this.myDoc.value=oDoc.innerHTML;return true;}return false;"> <input type="hidden" name="myDoc"> <div id="toolBar1"> <select onchange="formatDoc('formatblock',this[this.selectedIndex].value);this.selectedIndex=0;"> <option selected>- formatting -</option> <option value="h1">Title 1 <h1><...
... ...
Using HTML sections and outlines - Developer guides
eaning. It makes sense to use the section element to provide extra context for the parent element. HTML Aside Element (<aside>) defines a section that, though related to the main element, doesn't belong to the main flow, like an explanation box or an advertisement. The aside element has its own outline, but doesn't belong to the main one. Other Semantic HTML elements used in Sectioning HTML
Body Element (<
body>) defines all the content of a document. It contains all the content and HTML tags. HTML Header Element (<header>) defines a page area that typically contains a logo, title, and navigation. The header can also be used inside other semantic elements such as <article> or <section>. A section header might contain the section's heading, author name, etc. <article>, <section>, <aside>,...
...r, which typically contains copyright or legal notices and sometimes some links. In the context of a section, a footer might contain the sectioned content's publication date, license information, etc. <article>, <section>, <aside>, and <nav> can have their own <footer>. Despite its name, the footer is not necessarily positioned at the end of a page or section. ...
... <nav> <ul> <li><a href="#">link</a></li> <li><a href="#">link</a></li> </ul> </nav> Nesting Menus You do not nest <nav> elements. The <nav> can contain both primary and secondary menus. <nav> <ul> <li><a href="#">primary link</a></li> <li> <a href="#">prim...
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
will determine the correct directionality to use based on the contents of the <bdi>. Examples No <bdi> with only LTR This example lists the winners of a competition using <span> elements only. When the names only contain LTR text the results look fine: <ul> <li><span class="name">Henrietta Boffin</span> - 1st place</li> <li><span class="name">Jerry Cruncher</span> - 2nd place</li> </ul>
body { border: 1px solid #3f87a6; max-width: calc(100% - 40px - 6px); padding: 20px; width: calc(100% - 40px - 6px); border-width: 1px 1px 1px 5px; } No <bdi> with RTL text This example lists the winners of a competition using <span> elements only, and one of the winners has a name consisting of RTL text. In this case the "- 1", which consists of characters with neutral or weak direct...
...ompetition using <span> elements only, and one of the winners has a name consisting of RTL text. In this case the "- 1", which consists of characters with neutral or weak directionality, will adopt the directionality of the RTL text, and the result will be garbled: <ul> <li><span class="name">??????</span> - 1st place</li> <li><span class="name">Jerry Cruncher</span> - 2nd place</li> </ul>
body { border: 1px solid #3f87a6; max-width: calc(100% - 40px - 6px); padding: 20px; width: calc(100% - 40px - 6px); border-width: 1px 1px 1px 5px; } Using <bdi> with LTR and RTL text This example lists the winners of a competition using <bdi> elements. These elements instruct the browser to treat the name in isolation from its embedding context, so the example output is properly ord...
... 1px 1px 1px 5px; } Using <bdi> with LTR and RTL text This example lists the winners of a competition using <bdi> elements. These elements instruct the browser to treat the name in isolation from its embedding context, so the example output is properly ordered: <ul> <li><bdi class="name">??????</bdi> - 1st place</li> <li><bdi class="name">Jerry Cruncher</bdi> - 2nd place</li> </ul>
body { border: 1px solid #3f87a6; max-width: calc(100% - 40px - 6px); padding: 20px; width: calc(100% - 40px - 6px); border-width: 1px 1px 1px 5px; } Specifications Specification Status Comment HTML Living StandardThe definition of '<bdi>' in that specification. Living Standard HTML5The definition of '<bdi>' in that specification. Recomme...
<input type="button"> - HTML: Hypertext Markup Language
the drawing pen. The button, when clicked, invokes a function that clears the canvas. ...
...e sizePicker.oninput = function() { output.textContent = sizePicker.value; } // store mouse pointer coordinates, and whether the button is pressed var curX; var curY; var pressed = false; // update mouse pointer coordinates document.onmousemove = function(e) { curX = (window.Event) ? e.pageX : e.clientX + (document.documentElement.scrollLeft ? ...
... var curX; var curY; var pressed = false; // update mouse pointer coordinates document.onmousemove = function(e) { curX = (window.Event) ? e.pageX : e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.
body.scrollLeft); curY = (window.Event) ? e.pageY : e.clientY + (document.documentElement.scrollTop ? ...
<style>: The Style Information element - HTML: Hypertext Markup Language
s parent(s) and children. This attribute may be re-introduced in the future per https://github.com/w3c/csswg-drafts/issues/3547. If you want to use the attribute now, you can use a polyfill. 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 override those in the earlier one, if they have equal specificity. <!doctype html> <html> <head> <style> p { color: white; background-color: blue; padding: 5px; border:...
...- notice how the conflicting declarations in the later <style> element override those in the earlier one, if they have equal specificity. <!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. <!doctype html> <html> <head> <style> p { color: white; background-color: blue; padding: 5px; border: 1px solid black; ...
...ute on the second <style> element so it is only applied when the viewport is less than 500px in width. <!doctype html> <html> <head> <style> p { color: white; background-color: blue; padding: 5px; border: 1px solid black; } </style> <style media="all and (max-width: 500px)"> p { color: blue; background-color: yellow; } </style> </head> <
body> <p>This is my paragraph.</p> </
body> </html> Technical summary Content categories Metadata content, and if the scoped attribute is present: flow content. Permitted content Text content matching the type attribute, that is text/css. Tag omission Neither tag is omissible. Permitted parents Any element that accepts metadata content. Imp...
HTML documentation index - HTML: Hypertext Markup Language
eference, Web The HTML <blockquote> Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation. Usually, this is rendered visually by indentation (see Notes for how to change it). A URL for the source of the quotation may be given using the cite attribute, while a text representation of the source can be given using the <cite> element. 73 <
body>: The Document
Body element Element, HTML, Reference, Sectioning Root Element, Sections, Web The HTML <
body> Element represents the content of an HTML document. There can be only one <
body> element in a document. 74 <br>: The Line Break element Element, HTML, HTML text-level semantics, Reference, Web The HTML <br> element produces a line break in text (carriage-retu...
...Element (<listing>) renders text between the start and end tags without interpreting the HTML in between and using a monospaced font. The HTML 2 standard recommended that lines shouldn't be broken when not greater than 132 characters. 151 <main> Element, HTML, HTML grouping content, HTML sections, Reference, main The HTML <main> element represents the dominant content of the <
body> of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application. 152 <map> Element, HTML, HTML embedded content, Multimedia, Reference, Web The HTML <map> element is used with <area> elements to define an image map (a clickable link area). 153 <mark...
...ent (<sup>) specifies inline text which is to be displayed as superscript for solely typographical reasons. 202 <table>: The Table element Element, HTML, HTML tabular data, Reference, Tables, Web The HTML <table> element represents tabular data -- that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data. 203 <t
body>: The Table
Body element Element, HTML, HTML tabular data, Reference, Table
Body, Table Contents, Tables, Web, t
body The HTML Table
Body element (<t
body>) encapsulates a set of table rows (<tr> elements), indicating that they comprise the
body of the table (<table>). 204 <td>: The Table Data Cell element Cells, Data Cell, Element, HTML, HTML tabular data, Reference, Table...
Compression in HTTP - HTTP
ithms usually need a dictionary that add to the initial size) can be higher than the extra gain in compression resulting in a larger file. Do not use the two following techniques for files in a compressed format. End-to-end compression For compression, end-to-end compression is where the largest performance improvements of Web sites reside. End-to-end compression refers to a compression of the
body of a message that is done by the server and will last unchanged until it reaches the client. Whatever the intermediate nodes are, they leave the
body untouched. All modern browsers and servers do support it and the only thing to negotiate is the compression algorithm to use. These algorithm are optimized for text. In the 1990s, compression technology was advancing at a rapid pace and numerous ...
...ous successive algorithms have been added to the set of possible choices. Nowadays, only two are relevant: gzip, the most common one, and br the new challenger. To select the algorithm to use, browsers and servers use proactive content negotiation. The browser sends an Accept-Encoding header with the algorithm it supports and its order of precedence, the server picks one, uses it to compress the
body of the response and uses the Content-Encoding header to tell the browser the algorithm it has chosen. As content negotiation has been used to choose a representation based on its encoding, the server must send a Vary header containing at least Accept-Encoding alongside this header in the response; that way, caches will be able to cache the different representations of the resource. As compress...
...ideos. Apache supports compression and uses mod_deflate; for nginx there is ngx_http_gzip_module; for IIS, the <httpCompression> element. Hop-by-hop compression Hop-by-hop compression, though similar to end-to-end compression, differs by one fundamental element: the compression doesn't happen on the resource in the server, creating a specific representation that is then transmitted, but on the
body of the message between any two nodes on the path between the client and the server. Connections between successive intermediate nodes may apply a different compression. To do this, HTTP uses a mechanism similar to the content negotiation for end-to-end compression: the node transmitting the request advertizes its will using the TE header and the other node chooses the adequate method, applies ...
Cache-Control - HTTP
nt will accept the stale response after the initial expiration. Revalidation and reloading must-revalidate Indicates that once a resource becomes stale, caches must not use their stale copy without successful validation on the origin server. proxy-revalidate Like must-revalidate, but only for shared caches (e.g., proxies). Ignored by private caches. immutable Indicates that the response
body will not change over time. The resource, if unexpired, is unchanged on the server and therefore the client should not send a conditional revalidation for it (e.g. If-None-Match or If-Modified-Since) to check for updates, even when the user explicitly refreshes the page. Clients that aren't aware of this extension must ignore them as per the HTTP specification. In Firefox, immutable is only honore...
...t (e.g. If-None-Match or If-Modified-Since) to check for updates, even when the user explicitly refreshes the page. Clients that aren't aware of this extension must ignore them as per the HTTP specification. In Firefox, immutable is only honored on https:// transactions. For more information, see also this blog post. Other no-transform An intermediate cache or proxy cannot edit the response
body, Content-Encoding, Content-Range, or Content-Type. It therefore forbids a proxy or browser feature, such as Google's Web Light, from converting images to minimize data for a cache store or slow connection. only-if-cached Set by the client to indicate "do not use the network" for the response. The cache should either respond using a stored response, or respond with a 504 status code. Conditional...
...ed by the application such as images, CSS files and JavaScript files, for example. In addition, see also the Expires header. Cache-Control: public, max-age=604800, immutable Requiring revalidation Specifying no-cache or max-age=0 indicates that clients can cache a resource and must revalidate each time before using it. This means HTTP request occurs each time, but it can skip downloading HTTP
body if the content is valid. Cache-Control: no-cache Cache-Control: no-cache, max-age=0 Specifications Specification Status Comment RFC 8246: HTTP Immutable Responses IETF RFC RFC 7234: Hypertext Transfer Protocol (HTTP/1.1): Caching IETF RFC RFC 5861: HTTP Cache-Control Extensions for Stale Content IETF RFC Initial definition ...
HTTP headers - HTTP
ause of the inconveniences it caused when nonstandard fields became standard in RFC 6648; others are listed in an IANA registry, whose original content was defined in RFC 4229. IANA also maintains a registry of proposed new HTTP headers. Headers can be grouped according to their contexts: General headers apply to both requests and responses, but with no relation to the data transmitted in the
body. Request headers contain more information about the resource to be fetched, or about the client requesting the resource. Response headers hold additional information about the response, like its location or about the server providing it. Entity headers contain information about the
body of the resource, like its content length or MIME type. Headers can also be grouped according to how proxie...
...oss-origin restrictions. Do Not Track DNT Expresses the user's tracking preference. Tk Indicates the tracking status of the corresponding response. Downloads Content-Disposition Indicates if the resource transmitted should be displayed inline (default behavior without the header), or if it should be handled like a download and the browser should present a "Save As" dialog. Message
body information Content-Length The size of the resource, in decimal number of bytes. Content-Type Indicates the media type of the resource. Content-Encoding Used to specify the compression algorithm. Content-Language Describes the human language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language. Content-Location Indicate...
...r supports range requests, and if so in which unit the range can be expressed. Range Indicates the part of a document that the server should return. If-Range Creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource. Used to prevent downloading two ranges from incompatible version of the resource. Content-Range Indicates where in a full
body message a partial message belongs. Security Cross-Origin-Embedder-Policy (COEP) Allows a server to declare an embedder policy for a given document. Cross-Origin-Opener-Policy (COOP) Prevents other domains from opening/controlling a window. Cross-Origin-Resource-Policy (CORP) Prevents other domains from reading the response of the resources to which this header is applied. Content...
TRACE - HTTP
The HTTP TRACE method performs a message loop-back test along the path to the target resource, providing a useful debugging mechanism. The final recipient of the request should reflect the message received, excluding some fields described below, back to the client as the message
body of a 200 (OK) response with a Content-Type of message/http. The final recipient is either the origin server or the first server to receive a Max-Forwards value of 0 in the request. ...
...urce, providing a useful debugging mechanism. The final recipient of the request should reflect the message received, excluding some fields described below, back to the client as the message
body of a 200 (OK) response with a Content-Type of message/http. The final recipient is either the origin server or the first server to receive a Max-Forwards value of 0 in the request. ...
.... The final recipient of the request should reflect the message received, excluding some fields described below, back to the client as the message
body of a 200 (OK) response with a Content-Type of message/http. The final recipient is either the origin server or the first server to receive a Max-Forwards value of 0 in the request. ...
Network Error Logging - HTTP
ent in the JSON payload. 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. ...
... "max_age": 31556952, "endpoints": [ { "url": "https://example.com/csp-reports" } ] } Error reports In these examples, the entire reporting API payload is shown. The top-level "
body" key contains the network error report. ...
.../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. ...
Redirections in HTTP - HTTP
ger be used, and replaced with the new one.Search engine robots, RSS readers, and other crawlers will update the original URL for the resource. Code Text Method handling Typical use case 301 Moved Permanently GET methods unchanged. Others may or may not be changed to GET.[1] Reorganization of a Web site. 308 Permanent Redirect Method and
body not changed. Reorganization of a Web site, with non-GET links/operations. [1] The specification did not intend to allow method changes, but there are existing user agents that do change their method. 308 was created to remove the ambiguity of the behavior when using non-GET methods. Temporary redirections Sometimes the requested resource can't be accessed from its canonical location, ...
...also used when creating, updating, or deleting resources, to show temporary progress pages. Code Text Method handling Typical use case 302 Found GET methods unchanged. Others may or may not be changed to GET.[2] The Web page is temporarily unavailable for unforeseen reasons. 303 See Other GET methods unchanged. Others changed to GET (
body lost). Used to redirect after a PUT or a POST, so that refreshing the result page doesn't re-trigger the operation. 307 Temporary Redirect Method and
body not changed The Web page is temporarily unavailable for unforeseen reasons. Better than 302 when non-GET operations are available on the site. [2] The specification did not intend to allow method changes, but there a...
... available on the site. [2] The specification did not intend to allow method changes, but there are existing user agents that do change their method. 307 was created to remove the ambiguity of the behavior when using non-GET methods. Special redirections 304 (Not Modified) redirects a page to the locally cached copy (that was stale), and 300 (Multiple Choice) is a manual redirection: the
body, presented by the browser as a Web page, lists the possible redirections and the user clicks on one to select it. Code Text Typical use case 300 Multiple Choice Not many: the choices are listed in an HTML page in the
body. Machine-readable choices are encouraged to be sent as Link headers with rel=alternate. 304 Not Modified Sent for revalidated c...
451 Unavailable For Legal Reasons - HTTP
xample This example response is taken from the IETF RFC (see below) and contains a reference to Monty Python's Life of Brian. Note: the Link header might also contain a rel="blocked-by" relation identifying the entity and implementing blockage, not any other entity mandating it. ...
...navailable belongs in the response
body, not in the rel="blocked-by" link. This includes the name of the person or organization that made a legal demand resulting in the content's removal. ...
...tml> <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 operated by the People's Front of Judea.</p> </
body> </html> Specifications Specification Title RFC 7725: 451 Unavailable For Legal Reasons An HTTP Status Code to Report Legal Obstacles ...
Functions - JavaScript
); // Returns "Chamahk scored 5" Scope and the function stack Recursion A function can refer to and call itself. There are three ways for a function to refer to itself: The function's name arguments.callee An in-scope variable that refers to the function For example, consider the following function definition: var foo = function bar() { // statements go here } Within the function
body, the following are all equivalent: bar() arguments.callee() foo() A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, the following loop... var x = 0; while (x < 10) { // "x <...
...arameters: default parameters and rest parameters. Default parameters In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is exactly what default parameters do. Without default parameters (pre-ECMAScript 2015) In the past, the general strategy for setting defaults was to test parameter values in the
body of the function and assign a value if they are undefined. In the following example, if no value is provided for b, its value would be undefined when evaluating a*b, and a call to multiply would normally have returned NaN. However, this is prevented by the second line in this example: function multiply(a, b) { b = typeof b !== 'undefined' ? b : 1; return a * b; } multiply(5); // 5 With ...
...s provided for b, its value would be undefined when evaluating a*b, and a call to multiply would normally have returned NaN. However, this is prevented by the second line in this example: function multiply(a, b) { b = typeof b !== 'undefined' ? b : 1; return a * b; } multiply(5); // 5 With default parameters (post-ECMAScript 2015) With default parameters, a manual check in the function
body is no longer necessary. You can simply put 1 as the default value for b in the function head: function multiply(a, b = 1) { return a * b; } multiply(5); // 5 For more details, see default parameters in the reference. Rest parameters The rest parameter syntax allows us to represent an indefinite number of arguments as an array. In the following example, the function multiply uses rest para...
The arguments object - JavaScript
, 2, 3); // [1, 2, 3] While the presence of rest, default, or destructured parameters does not alter the behavior of the arguments object in strict mode code, there are subtle differences for non-strict code. In strict-mode code, the arguments object behaves the same whether or not a function is passed rest, default, or destructured parameters. That is, assigning new values to variables in the
body of the function will not affect the arguments object. Nor will assigning new variables to the arguments object affect the value of variables. Note: You cannot write a "use strict"; directive in the
body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw a syntax error. Non-strict functions that are passed only simple parameters (that is, not r...
...e arguments object affect the value of variables. Note: You cannot write a "use strict"; directive in the
body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw a syntax error. ...
...Instead, the arguments object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called (this is the same behavior as exhibited by all strict-mode functions, regardless of the type of variables they are passed): function func(a = 55) { arguments[0] = 99; // updating arguments[0] does not also up...
function* - JavaScript
https://github.com/mdn/interactive-examples and send us a pull request. You can also define generator functions using the GeneratorFunction constructor, or the function expression syntax. Syntax function* name([param[, param[, ... param]]]) { statements } name The function name. param Optional The name of a formal parameter for the function. statements The statements comprising the
body of the function. Description Generators are functions that can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances. Generators in JavaScript -- especially when combined with Promises -- are a very powerful tool for asynchronous programming as they mitigate -- if not entirely eliminate -- the problems with callbacks, such as Callback Hell and Inv...
...rances. Generators in JavaScript -- especially when combined with Promises -- are a very powerful tool for asynchronous programming as they mitigate -- if not entirely eliminate -- the problems with callbacks, such as Callback Hell and Inversion of Control. However, an even simpler solution to these problems can be achieved with async functions. Calling a generator function does not execute its
body immediately; an iterator object for the function is returned instead. When the iterator's next() method is called, the generator function's
body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. The next() method returns an object with a value property containing the yielded value and ...
...return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true). If a value is returned, it will be set as the value property of the object returned by the generator. Much like a return statement, an error is thrown inside the generator will make the generator finished -- unless caught within the generator's
body. When a generator is finished, subsequent next() calls will not execute any of that generator's code, they will just return an object of this form: {value: undefined, done: true}. 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(...
<math> - MathML
favor of the display attribute. Possible values are: display (which has the same effect as display="block") and inline. overflow Specifies how an expression behaves if it is too long to fit in the allowed width. Possible values are: linebreak (default), scroll, elide, truncate, scale. ...
...E 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> </mrow> </math> </
body> </html> XHTML notation <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>MathML in XHTML</title> </head> <
body> <math xmlns="http://www.w3.org/1998/Math/MathML"> <mrow> <mrow> <msup> <mi>a</mi>...
...You can achieve that easily by adding the .xhtml extension to your local files. For Apache servers you can configure your .htaccess file to map extensions to the correct Mime type. Since you notate your MathML in an XML document, also be sure you write a well-formed XML document. ...
Media - Progressive web apps (PWAs)
: [disabled] or [readonly]. ...
...It might also have a hover effect when the pointer is over it. More details For more information about user interfaces in CSS, see User interface in the CSS Specification. ...
...ing a document Note: This snippet only works on Firefox since it erroneously increments the CSS counter for fix-position elemnts. It shouldn not work in other browsers. See issue on css3-page. Make a new HTML document, doc4.html. Copy and paste the content from here: <!DOCTYPE html> <html> <head> <title>Print sample</title> <link rel="stylesheet" href="style4.css"> </head> <
body> <h1>Section A</h1> <p>This is the first section...</p> <h1>Section B</h1> <p>This is the second section...</p> <div id="print-head"> Heading for paged media </div> <div id="print-foot"> Page: </div> </
body> </html> Make a new stylesheet, style4.css. Copy and paste the content from here: /*** Print sample ***/ /* defaults for screen */ #print-he...
Mobile first - Progressive web apps (PWAs)
To create something more suitable for desktop, I put in the following media queries: @media (min-width: 480px) { #bottom, #top { display: none; } article, nav { display: block; } nav ul { text-align: center; } ...
...av { display: block; } nav ul { text-align: center; } nav li { display: inline; } nav li a { border-right: 1px solid #AD66D5; border-bottom: none; display: inline-block; padding: 0 5px; font-size: 1.6em; } nav li:last-child a { border-right: none; } } @media (min-width: 600px) { html { background: #eee; height: 100%; }
body { width: 600px; height: inherit; margin: 0 auto; background: url(../img/firefox-os.png) bottom left no-repeat, linear-gradient(to bottom, #fff, #eee); } .main > p { background: rgba(255,255,255,0.3); } nav li a { padding: 0 10px; font-size: 2em; } } The first one cancels out the CSS display: table behaviour, hides the links to jump to and from the naviga...
...n the HTML element. For example, the Modernizr in our example app is testing for multiple background image and rgba support. When they are not supported, the <html> tag looks like this: <html class=" js no-rgba no-multiplebgs"> When these are present, we can serve alternative styling rules to provide sensible fallbacks using descendant selectors -- see the following in my code. .no-multiplebgs
body { background: white; } .no-rgba .main > p { background: white; } This is not hugely pretty, but it does make the main content area more readable on browsers that don't support either or both of these features. Modernizr also puts its feature detect results in a JavaScript Modenizr object too, so that you can run JavaScript code selectively depending on feature support. For example, you cou...
The building blocks of responsive design - Progressive web apps (PWAs)
re! } This causes nothing inside the brick.js file to be run unless the viewport width is 480px or less. Problem solved. Really wide screens One thing you might notice is that when the viewport gets very wide (such as on a cinema display), the layout stops getting wider, and just centers in the space available. This is pretty simple to achieve. ...
... viewport width is 480px or less. Problem solved. Really wide screens One thing you might notice is that when the viewport gets very wide (such as on a cinema display), the layout stops getting wider, and just centers in the space available. This is pretty simple to achieve. ...
...isplay), the layout stops getting wider, and just centers in the space available. This is pretty simple to achieve. You could use a min-width media query to fix the <
body> width at a certain point: @media all and (min-width: 1400px) {
body { width: 1400px; margin: 0 auto; } } But it's actually easier to just set the following rule instead, and get rid of the media query altogether:
body { max-width: 1400px; margin: 0 auto; } Orientation fail We also came across some problems with orientation: the mobile-app layout of our example app is designed for portrait orientation, and looks terrible when viewed on a device in landscape orientation. To fix this, we added in a media query that only applies its contents to the markup when device is viewed in landscape orientation: @med...
fill-rule - SVG: Scalable Vector Graphics
ule attribute is a presentation attribute defining the algorithm to use to determine the inside part of a shape. Note: As a presentation attribute, fill-rule can be used as a CSS property. As a presentation attribute, it can be applied to any element but it has effect only on the following eight elements: <altGlyph>, <path>, <polygon>, <polyline>, <text>, <textPath>, <tref>, and <tspan> html,
body,svg { height:100% } <svg viewBox="-10 -10 220 120" xmlns="http://www.w3.org/2000/svg"> <!-- Default value for fill-rule --> <polygon fill-rule="nonzero" stroke="red" points="50,0 21,90 98,35 2,35 79,90"/> <!-- The center of the shape has two path segments (shown by the red stroke) between it and infinity. It is therefore considered outside the shape, and not filled. --> <p...
...in any direction, and then examining the places where a segment of the shape crosses the ray. Starting with a count of zero, add one each time a path segment crosses the ray from left to right and subtract one each time a path segment crosses the ray from right to left. After counting the crossings, if the result is zero then the point is outside the path. Otherwise, it is inside. ...
...d" d="M210,0 h90 v90 h-90 z M230,20 v50 h50 v-50 z"/> </svg> evenodd The value evenodd determines the "insideness" of a point in the shape by drawing a ray from that point to infinity in any direction and counting the number of path segments from the given shape that the ray crosses. If this number is odd, the point is inside; if even, the point is outside. ...
points - SVG: Scalable Vector Graphics
The points attribute defines a list of points. Each point is defined by a pair of number representing a X and a Y coordinate in the user coordinate system. If the attribute contains an odd number of coordinates, the last one will be ignored. ...
... polyline For <polyline>, points defines a list of points, each representing a vertex of the line to be drawn. Each point is define by a X and Y coordinate in the user coordinate system. Note: A polyline is an open shape, meaning the last point is not connected to the first point. 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. Each point is define by a X and Y coordinate in the user coordinate syst...
...svg> polygon For <polygon>, points defines a list of points, each representing a vertex of the shape to be drawn. Each point is define by a X and Y coordinate in the user coordinate system. Note: A polygon is a closed shape, meaning the last point is connected to the first point. 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. Candidate Recommendatio...
x - SVG: Scalable Vector Graphics
For <altGlyph>, x defines the x-axis coordinate of the alternate glyph. ...
... multiple values, x defines the x coordinate of each individual glyph from the text. If there are less values than glyphes, the remaining glyphes are placed in the continuity of the last positioned glyph. If there are more values than glyphes, extra values are ignored. ...
...ltiple values, x defines the x coordinate of each individual glyph from the text. If there are less values than glyphes, the remaining glyphes are placed in the continuity of the last positioned glyph. If there are more values than glyphes, extra values are ignored. ...
x1 - SVG: Scalable Vector Graphics
The x1 attribute is used to specify the first x-coordinate for drawing an SVG element that requires more than one coordinate. Elements that only need one coordinate use the x attribute instead. ...
...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> line For <line>, x1 defines the x coordinate of the starting point of the line. ...
...="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 gradient stop values. ...
x2 - SVG: Scalable Vector Graphics
The x2 attribute is used to specify the second x-coordinate for drawing an SVG element that requires more than one coordinate. Elements that only need one coordinate use the x attribute instead. ...
...="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> line For <line>, x2 defines the x coordinate of the ending point of the line. ...
...="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 gradient stop values. ...
y - SVG: Scalable Vector Graphics
For <altGlyph>, y defines the y-axis coordinate of the alternate glyph. ...
... multiple values, y defines the y coordinate of each individual glyph from the text. If there are less values than glyphes, the remaining glyphes are placed in the continuity of the last positioned glyph. If there are more values than glyphes, extra values are ignored. ...
...ltiple values, y defines the y coordinate of each individual glyph from the text. If there are less values than glyphes, the remaining glyphes are placed in the continuity of the last positioned glyph. If there are more values than glyphes, extra values are ignored. ...
y1 - SVG: Scalable Vector Graphics
The y1 attribute is used to specify the first y-coordinate for drawing an SVG element that requires more than one coordinate. Elements that only need one coordinate use the y attribute instead. ...
...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> line For <line>, y1 defines the y coordinate of the starting point of the line. ...
...2="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 gradient stop values. 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. --> <linearGradient y1="0%" id="g0"> <stop offset="5%" stop-color="black" /> <stop offset="50%" stop-color="red" /> <stop offset="95%" stop-color="black" /> </linearGradient...
y2 - SVG: Scalable Vector Graphics
The y2 attribute is used to specify the second y-coordinate for drawing an SVG element that requires more than one coordinate. Elements that only need one coordinate use the y attribute instead. ...
...ttp://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> line For <line>, y2 defines the y coordinate of the ending point of the line. ...
... 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 gradient stop values. 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. --> <linearGradient y2="0%" id="g0"> <stop offset="5%" stop-color="black" /> <stop offset="50%" stop-color="red" /> <stop offset="95%" stop-color="black" /> </linearGradient>...
Cross-domain Content Scripts - Archive of obsolete content
ta; var pageWorker = require("sdk/page-worker").Page({ contentURL: data.url("page.html"), contentScriptFile: data.url("page-script.js") }); pageWorker.on("message", function(message) { console.log(message); }); The "page.html" file embeds an iframe whose content is served from "http://en.m.wikipedia.org/": <!DOCTYPE html> <!-- page.html --> <html> <head></head> <
body> <iframe id="wikipedia" src="http://en.m.wikipedia.org/"></iframe> </
body> </html> The "page-script.js" file locates "Today's Featured Article" and sends its content to "main.js": // page-script.js var iframe = window.document.getElementById("wikipedia"); var todaysFeaturedArticle = iframe.contentWindow.document.getElementById("mp-tfa"); self.postMessage(todaysFeaturedArticle...
...js") }); forecast_panel.on("show", function(){ forecast_panel.port.emit("show"); }); require("sdk/ui/button/action").ActionButton({ id: "get-forecast", label: "Get the forecast", icon: "./icon-16.png", onClick: function() { forecast_panel.show(); } }); The "panel.html" just includes a <div> block for the forecast: <!DOCTYPE html> <!-- panel.html --> <html> <head></head> <
body> <div id="forecast_summary"></div> </
body> </html> The "panel-script.js" uses XMLHttpRequest to fetch the latest forecast: // panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=YOUR-API-KEY"; self.port.on("show", function () { var request = new XMLHttpRequest(); request.open("GET", url, true); request.onload = function...
ui/frame - Archive of obsolete content
one mandatory option, which is a url pointing to an HTML document supplied under your add-ons "data" directory. ...
...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="weather" class="info-element"></span> <script type="text/javascript" src="city-info.js"></script> </
body> </html> If we save this document as "city-info.html" under the add-on's "data" directory, we can create a frame hosting it and add the frame to a toolbar like this: var { Frame } = require("sdk/ui/frame"); var { Toolbar } = require("sdk/ui/toolbar"); var frame = new Frame({ url: "./city-info.html" }); var toolbar = Toolbar({ name: "city-info", title: "City info", items: [frame] }); ...
Modifying the Page Hosted by a Tab - Archive of obsolete content
ticular tab, load one or more content scripts into it using attach() method of tab object. The job of these scripts is to interact with web 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 could download this icon: . This add-on creates a button with Mozilla favicon as an icon. It has a click handler which fetches the active tab and loads a script into the page hosted by the active tab. The script is specified using the contentScript option...
...-on script, tab.attach() returns a worker object containing the port property you use to send messages to the content script. Let's rewrite the example above to pass a message from the add-on to the content script. ...
Localization - Archive of obsolete content
lation of the hello_id identifier, it will get the correct translation for the current locale. Using localized strings in HTML This example uses the action button API, which is only available from Firefox 29 onwards. ...
...he correct translation for the current locale. Using localized strings in HTML This example uses the action button API, which is only available from Firefox 29 onwards. ...
Displaying web content in an extension without security issues - Archive of obsolete content
ol is useful. This protocol is special because it inherits the privileges from its parent document. However, if a "data:" document is the topmost content document, there is no parent document (remember, content documents have no access to the chrome documents above them) and consequently no privileges. ...
...l. This protocol is special because it inherits the privileges from its parent document. However, if a "data:" document is the topmost content document, there is no parent document (remember, content documents have no access to the chrome documents above them) and consequently no privileges. ...
Creating a Web based tone generator - Archive of obsolete content
on mozWriteAudio() is called to write those samples produced in the audio stream. In order to always have samples to play, a buffer of 500 ms is created. The function mozCurrentSampleOffset() is used to know the position of the samples being played so that we can fill a 500 ms buffer of audio samples. <!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. var audio = new Audio(); audio.mozSetup(1, sampleRate); var currentWri...
...ta.length; i<size; i++) { soundData[i] = Math.sin(k * currentSoundSample++); } } var audioDestination = new AudioDataDestination(sampleRate, requestSoundData); function start() { currentSoundSample = 0; frequency = parseFloat(document.getElementById("freq").value); } function stop() { frequency = 0; } </script> </
body> </html> ...
Monitoring WiFi access points - Archive of obsolete content
This object is described in lines 11 through 40 in the code above. The onChange() method (lines 13 through 27) begins by enabling UniversalXPConnect privile...
...This object is described in lines 11 through 40 in the code above. The onChange() method (lines 13 through 27) begins by enabling UniversalXPConnect privileges, then clearing out the div (d) that will receive the upd...
Using XML Data Islands in Mozilla - Archive of obsolete content
e = document.getElementById("purchase-order").textContent; var parser = new DOMParser(); var doc = parser.parseFromString(orderSource, "application/xml"); var lineItems = doc.getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "lineItem"); var firstPrice = lineItems[0].getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "price")[0].textContent; document.
body.textContent = "The purchase order contains " + lineItems.length + " line items. The price of the first line item is " + firstPrice + "."; } </script> </head> <
body onload="runDemo()";> Demo did not run </
body> </html> The XML source text can be parsed into a DOM tree using the DOMParser API: var parser = new DOMParser(); var doc = parser.parseFromString(orderSource, "application/xml"); The HTML5...
...entsByTagNameNS("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. The price of the first line item is " + firstPrice + "."; } </script> </head> <
body onload="runDemo()";> <object id="purchase-order" data="purchase_order.xml" type="text/xml" style="display: none;"></object> <div id="output-box">Demo did not run</div> </
body> </html> ...
Visualizing an audio spectrum - Archive of obsolete content
ores the metadata of the audio element in global variables; the function for the MozAudioAvailable event does an FFT of the samples and displays them in a canvas. NOTE: You can use the AudioNode called AnalyserNode to perform real-time FFT analysis on an audio stream, rather than the code shown below. ...
...eShiftStepReal) - (currentPhaseShiftImag * phaseShiftStepImag); currentPhaseShiftImag = (tmpReal * phaseShiftStepImag) + (currentPhaseShiftImag * phaseShiftStepReal); } halfSize = halfSize << 1; } i = bufferSize/2; while(i--) { spectrum[i] = 2 * Math.sqrt(real[i] * real[i] + imag[i] * imag[i]) / bufferSize; } }; </script> </
body> </html> ...
Dehydra Function Reference - Archive of obsolete content
d will be called by Dehydra while compiling. See the Dehydra object reference for details on the available object properties. process_type(type) Dehydra calls this for each class, struct, enum, union, and typedef declaration. process_type is called after process_function is called for all the member functions. type is a type object representing the type that was declared. ...
... process_decl(decl) process_decl is called for every global variable, function, or template declaration. ...
JavaScript crypto - Archive of obsolete content
This allows the page to automatically login and logout based on the presence of the SmartCard. Generating keys and issuing user certificates There are several crypto object methods used in generating keys for certificates...
...This allows the page to automatically login and logout based on the presence of the SmartCard. Generating keys and issuing user certificates There are several crypto object methods used in generating keys for certificates: generateCRMFRequest(), importUs...
Basics - Archive of obsolete content
he consolestring console.log("hello world!"); arn()This method does stuff. error()This method does stuff. exception()This method does stuff. logFromCaller()This method does stuff. Class Notifications The Notification Box appears at the bottom right corner of the browser and displays important information to the user. The namespace for this class is jetpack.notificaitons. ...
...oes stuff. exception()This method does stuff. logFromCaller()This method does stuff. Class Notifications The Notification Box appears at the bottom right corner of the browser and displays important information to the user. The namespace for this class is jetpack.notificaitons. Methods show(titlestring
bodystringiconstring)Draws a notification box. titleThe head of the notification message.string
bodyThe messagestringfalse iconThe URL of an .ico file.string jetpack.notifications.show("hello world");var my
Body = " My first message
body on Jetpack";var myIcon = "http://www.mozilla.com/favicon.ico";jetpack.notifications.show({title: "My first message on jetpack",
body: my
Body, icon: myIcon}); Class Tabs In this class you can find information about the tabs in your Firefox window. The namespace ...
Jetpack Snippets - Archive of obsolete content
e documents the Jetpack Prototype, which is no longer under active development. Read the experiment report for what we learned from it and the blog post announcing the first SDK release for what we're up to next! Bits of code that may come in handy. ...
.../head><
body> <p>some slidbar you want to debug</p> <a href="javascript:console.log('hello!')">test</a> <script><![CDATA[ //firebug lite bookmarklet code: var firebug=document.createElement('script'); firebug.setAttribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'); document.
body.appendChild(firebug); (function(){if(window.firebug.version){firebug.init();}else{setTimeout(arguments.callee);}})();void(firebug); ]]></script> </
body></html>, width: 800, //wide enough to use firebug onSelect: function(slide) { slide.slide(800, true); }}); Calling into a slidebar from the global jetpack scope jetpack.slideBar.append({ ...
Table Cellmap - Archive of obsolete content
>cell 1</td><td>cell 2</td></tr> <tr><td>cell 3</td><td>cell 4</td></tr> </table> This would create a cellmap with two rows and in each row 2 entries. Each entry in the cellmap wold have a direct link to the corresponding TableCellFrames. Tables with footers, headers etc. Take the same table and adder a header <table> <thead> <tr><td>head cell 1</td><td>head cell 2</td></tr> </thead> <t
body> <tr><td>cell 1</td><td>cell 2</td></tr> <tr><td>cell 3</td><td>cell 4</td></tr> </t
body> </table> Now we have two different rowgroups and and the rowspans can not cross the borders between the different rowgroups. (ref XHTML-2.0). Further the table header and footer will be repeated on every page when printed out. Due to this behind the cellmap for the table we will find a cellmap for ever...
... There is a special attribute for rowspan="0" and colspan="0", because html 4.0 did introduce a special handling of the 0 value. rowspan = number [CN] This attribute specifies the number of rows spanned by the current cell. The default value of this attribute is one ("1"). The value zero ("0") means that the cell spans all rows from the current row to the last row of the table section (THEAD, T
BODY, or TFOOT) in which the cell is defined. colspan = number [CN] This attribute specifies the number of columns spanned by the current cell. The default value of this attribute is one ("1"). The value zero ("0") means that the cell spans all columns from the current column to the last column of the column group (COLGROUP) in which the cell is defined. The handling of zero spans introduces overhe...
The life of an HTML HTTP request - Archive of obsolete content
sIHTMLContent interface as well as their respective DOM interfaces. nsIContent::AppendChild() is used to build the content tree but AppendChild takes a "aNotify" argument that marks if it should notify the document about the content model changes or not. This argument is always PR_FALSE when the content sink calls AppendChild. The content sink tells the document about content model changes (Notify
Body()) in places like nsHTMLContentSink::WillInterrupt() and nsHTMLContentSink::DidBuildModel(). WillInterrup is called by the parser between every 8kb block of data (unless the parser is temporarily blocked). (7) Since the presentation shell (nsPresShell) has registred as an DocumentObserver with the nsIDocument it also gets notified of changes in the Document/Content tree. This is used to create a...
... frames created from a content node, then the first of these are called the "primary" node, and the following frames can be found by using the GetNextInFlow() method of nsIFrame. The initial reflow is done by the nsHTMLContentSink::StartLayout(), StartLayout() calls PresShell::InitialReflow(). StartLayout is called quite early in the parsing process, for HTML it's called in nsHTMLContentSink::Open
Body() (among other places). TODO: How are nsIFrames reflowed after a change when they already exist? (8) Each nsIFrame knows how how to draw itself on the screen. When the PresShell [Note: not true, who really does the call?] has layouted (reflowed) the frames it calls nsIFrame::Paint() method of all frames. These get passed references to the presentation context and a rendering context to do the d...
Deprecated and defunct markup - Archive of obsolete content
tag?) Typo for <action> --Neil 03 March 2011 <autorepeatbutton> (action occurs repeatedly on mouse hover--used to construct other elements; used in <arrowscrollbox> and large drop-down menus) So, not deprecated? ...
... menus/toolbars) <textfield> (like <textbox>) <thumb> (<button> with deprecated <gripper>; implements sliding box in center of scrolbar) <title> (to add a caption on a <titledbox> <titledbox> (box with a frame) <titledbutton> (attempt to combine text and images before <button>) <toolbarpaletteitem> Required to embed non-buttons in customisable toolbars --Neil 03 March 2011 <tree
body> (old/experimental and unsupported XUL tags) Lives on as the internal name for the ancestor <treechildren> element --Neil 03 March 2011 <treecaption> (old/experimental and unsupported XUL tags) <treecolgroup> (former name for <treecols> <treecolpicker> (internal use only; part of XBL for <tree>) <treefoot> (old/experimental and unsupported XUL tags) <treeindentation> (old/experim...
Attribute Substitution - Archive of obsolete content
<< PreviousNext >> So far, attribute replacement in an action
body has been used to replace an entire attribute with the value of a variable. However, you may also replace only part of attribute's value, or use multiple variables in one attribute. For instance, to include a prefix before a variable value, you can use: <label value="My name is ?name"/> The effect will be that the ?name part of the attribute will be replaced by the value of the variable ?name. For instance, if the value of ?name is 'Jake', then the attribute value will be 'My name is Jake'. ...
...e"/> The effect will be that the ?name part of the attribute will be replaced by the value of the variable ?name. For instance, if the value of ?name is 'Jake', then the attribute value will be 'My name is Jake'. You can include multiple variables in one attribute if desired: <label value="My name is ?name and my age is ?age"/> This technique will work for any variable replacement in the action
body, except for the uri attribute since that wouldn't be meaningful. Note that variable names must have a space after them as this is how the end of variable is determined. That is '?name?age' is considered to be a single variable with that name, not two variables together. To use two variables, place a space between them. It is sometimes useful though, to concatenate two values together without a sp...
Bindings - Archive of obsolete content
title"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/description" object="?description"/> </query> It works similarly to the previous triple. The ?photo variable is filled in with the known value and then the arc is looked up the datasource, filling in the value for the ?description variable. The ?description variable would then be used in the action
body. Let assume though, that we are only going to add a description to one of the photos in the datasource; the other two photos will not have a description. This may mean the description is not known, or that it wasn't filled in by the user. <rdf:Description rdf:about="http://www.xulplanet.com/ndeakin/images/t/palace.jpg" dc:title="Palace from Above"/> dc:desc...
...each match, the datasource is examined for the description, and the value of the ?description variable is filled in. The effect is three matches, only one of which will display a description. The photos that don't have a description will be treated as if the description were blank. That is, the ?description variable will be replaced with an empty string when analyzing the attributes in the action
body. Here is this example. You can have more than one binding if you wish. The others will be evaluated in a similar way. For instance, the title triple could be moved to a binding such that it could be optional also. << PreviousNext >> ...
Building Menus With Templates - Archive of obsolete content
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 placed on a menu-type button. The query generates a list of the person tags within the datasource and outputs the action
body for each one. The uri attribute has not been placed on the menupopup element which is the direct child of the action element but has instead been placed on the menuitem element. This causes the menupopup to only be created once. The menuitem elements however will be repeated for each result from the query. This makes sense, as we only want one menupopup to be created but multiple menuitem element...
...ed content does not get removed again when the menu is closed again; this extra feature of menus is only intended to be a performance enhancement to speed up the time it takes to display a window by avoiding extra generation that can be put off until later. You might be wondering why we couldn't just put the datasources attribute on the menupopup instead and not have a menupopup inside the action
body. You can actually do this, however, you no longer receive the performance benefit as the entire content will be generated right away. The special feature of menus to not generate content immediately applies only to the menu itself. Generating a Recursive Menu Menus are often generated from a template recursively. When creating recursive menus, you will need to use multiple rules, since leaf items...
Building Trees - Archive of obsolete content
ou can also use the content builder for a tree. There may be situations that call for this, typically when handling smaller amounts of data. However, the content builder becomes slower as the amount of data increases. Apart from the flags attribute, the template syntax for the tree builder and the content builder are identical. However, the tree builder requires a very specific form to the action
body. Specifically, the action
body should be a single treeitem with its rows and cells. 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> ...
... predicates into values, and returns the value. In the example above, the first cell should display the title. The builder doesn't compute any labels until the view asks for them. When the view requests a label for the first cell, the builder looks up the 'http://purl.org/dc/elements/1.1/title' predicate for the row in question and returns it. The content builder generates content in the template
body and substitutes data from the datasource right away. However, it will generate the same result on screen to the user as with the tree builder. Compare the example with a tree builder and the same example using a content builder. Here is an example of a tree using an SQLite datasource: <tree datasources="profile:messages.sqlite" ref="*" querytype="storage" flags="dont-build-content"> <tree...
SQLite Templates - Archive of obsolete content
tbox containing the values in one column in a database table. <listbox datasources="profile:userdata.sqlite" ref="*" querytype="storage"> <template> <query> select name from myfriends </query> <action> <listitem uri="?" label="?name"/> </action> </template> </listbox> The query returns the list of values from the 'name' column in the table 'myfriends'. The action
body, starting at the node with uri="?" is repeated for each result returned from the query. If the query returns six results, six listitems will be generated. The labels have the special value '?name'. The syntax with the question mark is similar as with the other query types. It means, substitute the attribute value with the value of a column from the result. In this case, '?name' means replace this...
...rces="profile:userdata.sqlite" ref="*" querytype="storage"> <template> <query> select name, email from myfriends where age >= 30 </query> <action> <hbox uri="?"> <label value="?name"/> <label value="?email"/> </hbox> </action> </template> </vbox> This template displays the results of two columns. Any occurance of a question mark in the action
body is replaced with the value from the query results. Here, this is used two times, once to display the name and the second to display the email. The uri attribute on the hbox element is required on one element within the action
body. For Sqlite queries it will almost always be on the outermost node. Note also that the query statement has a where clause which restricts the rows to those with an age ...
Static Content - Archive of obsolete content
resent. That is, before the template is examined, the menulist would have one item in it, with the label 'All'. The template generates two results as before, one for each country, and appends a menuitem for each one. 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 demonstrates how the template builder generates content, and the specifics of how this is done become important when dealing with recursive content and multiple rules. What's going on here is that the XUL parser first creates the outer menulist element. The static content outside the template will also be created. The result will be a XUL display that looks just like the code above, except ...
...t looks just like the code above, except that the template and its content is hidden. At this point, the menulist will have a menupopup as a child, and the menupopup will in turn have one menuitem child. Next, the template is examined and two results are generated. Remember that only the content at the uri attribute or below inside the action are copied for each result. When processing the action
body, the builder looks at the first element inside the action, in this case, the menupopup. This element doesn't have a uri attribute, so the builder knows that this element should only be created once. You might think that the builder would then just create a menupopup, but it doesn't. Instead, it looks to see if a menupopup already exists in the location where it would be generated. In this case, t...
Using Recursive Templates - Archive of obsolete content
, a further step is done to retrieve an additional level of nodes. As each group has children itself, each result (in this case, each group) becomes the reference point for a futher iteration. The same query is executed again but using the groups generated from the previous execution of the query. This time, the query generates a result for each person in the XML source. The content of the action
body is again generated for each result, but instead of being inserted inside the outermost groupbox, this new content is inserted inside the content generated from the previous iteration. The content is always inserted directly inside the element with the uri attribute. The result is output like the following: <groupbox> ... <vbox id="row2" container="true" empty="false" class="indent"> <labe...
...The template builder has also added container and empty attributes to the groups. This is done with all nodes that have children to indicate that the node contains generated children as well as whether the node is empty. These hints are used for trees, but they can also be used in a stylesheet to provide a different appearance for containers w...
XML Assignments - Archive of obsolete content
) - 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. It allows us to declare additional variables that may be used in the action
body. The expr attribute specifies the XPath expression and the var attribute specifies the variable to assign to. Note that while the query expression uses the root node (or reference node) as the XPath context, the expressions for the assign element are evaluated using each result node as the context. For each result, the ?namelength variable will be assigned the length of the name attribute on the ...
... number of XML node siblings in the document, not the number of real siblings the people have, clearly the people in the datasource aren't actually siblings). Naturally, the number of siblings will be the same for all children, but you could imagine a more complex query expression that generated nodes where this wasn't actually the case. The two variable assignments may then be used in the action
body to replace attributes in the generated content. If a variable is used in the action that doesn't correspond to one declared in an assign element, the default behaviour is to take the corresponding attribute on the result node. Here, the two attributes 'name' and 'gender' will be taken from the XML data, as in previous examples. << PreviousNext >> ...
Styling a Tree - Archive of obsolete content
<< PreviousNext >> The following describes how to style a tree. Styling the Tree You can style the tree border and the column headers in the same way as other elements. Style added to the tree element will apply to the entire tree. Adding a style to the treecol element does not cause the style to be applied to the column but only to the header. The
body of the tree must be styled in a somewhat different way than other elements. This is because the tree
body is stored in a different way to other elements. The outer treechildren is the only real element in the tree
body. The inner elements are just placeholders. Setting Properties Instead, you must use the properties attribute on the rows or cells to set one or more named properties. This can be used with trees with static c...
...t the twisty and indentation. The following is the syntax that needs to be used: treechildren::-moz-tree-row(makeItBlue) { background-color: blue; } This style which has a complex selector is used to style the background color of rows that have the 'makeItBlue' property. This special syntax is needed because the cells themselves are not separate elements. All of the content inside the tree's
body is rendered by the treechildren element. However, CSS has a concept to access parts of elements considering them to be pseudo-elements. This selector matches some tree rows inside the treechildren element as pseudo-elements. The style sets style rules for particular parts of what it displays. This style rule means, inside a treechildren element, set the background color to blue for all tree rows ...
XML - Archive of obsolete content
thors may be people or machines, but they must use the new language if the readers are to understand what sort of data it is they are reading. It's much simpler than it seems -- much simpler, in fact, than a lot of XML primers and references would have you believe. In fact, let's create a new XML-based language right now called "MemoML". It will consist of a lexicon of four terms: memo, to, from,
body -- all of which fit together into a syntax represented in most XML circles as: <!ELEMENT memo (from, to,
body)> For developers accustomed to reading and using XML, this definition indicates that the root element "memo" is constituted by a "from" element, then a "to" element, then a "
body" element. That's it. In our new language, there are only four words, but they are adequate to describe thes...
...re are only four words, but they are adequate to describe thestructure of a real, very simple memo. Note that our language doesn't suffice to describe the content of the memo, which is written in english. But that's not what markup languages are for, in general. An actual memo using the MemoML to represent itself might look like this: <memo> <from>Ian Oeschger</from> <to>Steve Rudman</to> <
body>I think the first draft of the guide is done!</
body> </memo> Note how the memo element -- the root element in our brief definition, ordeclaration, above -- surrounds the other three elements. In the MemoML definition, the memo element is defined as containing the from, to, and
body elements in that order. So the example here is valid memo according to our DTD; it's a memo that's been writtten i...
Table Reflow Internals - Archive of obsolete content
The initial chunk of an xml doc is loaded. The initial chunk of an html doc (or a subsequent chunk of an xml doc) is loaded. The container posts a dirty reflow command with itself as the target. Content is inserted, appended, or deleted through the DOM. ...
... the next page, or start on the next page. If it can continue, it returns an incomplete status. If it can't continue it returns a complete status. A continuation may also need to be continued Continuations are linked together by prevInFlow and nextInFlow pointers Pagination Illustration nsSimplePageSequence nsPageFrame nsPageContentFrame areaFrame (html) blockFrame (
body) nsTableOuterFrame nsTableOuterFrame blockFrame (
body) areaFrame (html) nsPageContentFrame continued nsPageFrame continued Intro to paginated reflow The page sequence starts with one page and reflows it. If the page is incomplete then the page sequence creates a continuation for the page and sets it as the page's...
Using the W3C DOM - Archive of obsolete content
n IE method since IE 4 and has been standardised in HTML5. Both properties can be read or set. Reading the property returns the text of an element with all the element content removed. Setting the property replaces all the element's content with a single text node with the assigned text. The following examples show how to modify the text of a SPAN element that already exists in the HTML file. ...
...It then tests for support for textContent, then innerText and uses which ever is supported. If neither is supported, it assumes support for basic DOM 1 methods and uses those. It should be clear that translating scripts to modify document content is not a trivial undertaking. The benefit of such a conversion is that the script will w...
Using workers in extensions - Archive of obsolete content
lizing an extension Updating an extension to support multiple Mozilla applications Download the sample You may download the complete example: Download the example. How this differs from previous versions This version of the stock ticker extension moves the XMLHttpRequest call that fetches updated stock information into a worker thread, which then passes that information back to the main
body of the extension's code to update the display in the status bar. This demonstrates not only how to use workers in an extension, but also how to perform XMLHttpRequest in a worker, and how workers and main thread code can pass data back and forth. The worker The worker thread's job in this example is to issue the XMLHttpRequest calls that fetch the updated stock information. That's all it does. ...
...It starts by setting up an interval handler (in lines 26-28) that calls refreshInformation() every 10 minutes. Then it sets the worker's onmessage event handler to a function which looks at the event passed into it, and does one of two things: If there is a data field on the event, the stock symbol being tracked is set to the upper case version of th...
-ms-scrollbar-arrow-color - Archive of obsolete content
arrows, and a scroll bar with a green scroll box and arrows. ...
...r: green; } <
body> <div class="blueScrollBox"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> <div class="greenScrollBox"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> </
body> The following image shows the result: Specifications Not part of any specification. ...
-ms-scrollbar-face-color - Archive of obsolete content
arrows, and a scroll bar with a green scroll box and arrows. ...
...r: green; } <
body> <div class="blueScrollBox"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> <div class="greenScrollBox"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> </
body> This image shows the result: Specifications Not part of any specification. ...
-ms-scrollbar-shadow-color - Archive of obsolete content
...
...g example shows how to create a style rule that sets the -ms-scrollbar-shadow-color property for a <textarea> element. <!DOCTYPE html> <html> <head> <title>scrollbar-shadow-color</title> <style> .BlueShadow { scrollbar-shadow-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. ...
Displaying notifications (deprecated) - Archive of obsolete content
is closed (whether by being clicked or by some other means). Note: If the notification is dismissed by the user clicking on it, both events will get fired. ...
...t'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>"; document.
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'r...
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. ...
... ctx.fillRect(i * 4, canvas.height, 3, -magnitude); } ctx.drawImage(document.getElementById('mozlogo'),0,0, canvas.width, canvas.height); } var audio = document.getElementById('audio-element'); audio.addEventListener('MozAudioAvailable', audioAvailable, false); audio.addEventListener('loadedmetadata', loadedMetadata, false); </script> </
body> </html> ...
RDF in Fifty Words or Less - Archive of obsolete content
la.org/smart-mail/get-mail.cgi?user=waterson&folder=inbox"> <sm:message id="4025293"> <sm:recipient> Chris Waterson "waterson@netscape.com" </sm:recipient> <sm:sender> Aunt Helga "helga@netcenter.net" </sm:sender> <sm:received-by>x-wing.mcom.com</sm:received-by> <sm:subject>Great recipe for Yam Soup!</sm:subject> <sm:
body> http://www.mozilla.org/smart-mail/get-
body.cgi?id=4025293 </sm:
body> </sm:message> <sm:message id="4025294"> <sm:recipient> Chris Waterson "waterson@netscape.com" </sm:recipient> <sm:sender> Sarah Waterson "waterson.2@postbox.acs.ohio-state.edu" </sm:sender> <sm:received-by>x-wing.mcom.com</sm:received-by> ...
...3 </sm:
body> </sm:message> <sm:message id="4025294"> <sm:recipient> Chris Waterson "waterson@netscape.com" </sm:recipient> <sm:sender> Sarah Waterson "waterson.2@postbox.acs.ohio-state.edu" </sm:sender> <sm:received-by>x-wing.mcom.com</sm:received-by> <sm:subject>We won our ultimate game</sm:subject> <sm:
body> http://www.mozilla.org/smart-mail/get-
body.cgi?id=4025294 </sm:
body> </sm:message> </rdf:Description> </rdf:RDF> Upon receipt of the above monstrosity, the RDF engine folds the RDF into the graph at the appropriate place, and the tree control that actually implements the UI to the bookmarks is notified that it should begin drawing some icons for the latest message ab...
Common causes of memory leaks in extensions - Extensions
ment. If you put a reference to anything within this compartment into a long-lived window object (such as browser.xul), JavaScript module or XPCOM component, the bootstrap.js compartment will become a zombie. ...
...will leak: function leakref() {} function modifyDocument(document) { var a = document.createElement("a"); document.
body.appendChild(a); // The new DOM node holding a reference to leakref will prevent // that function object from being garbage collected and hence // will leak the whole bootstrap compartment. a.someProperty = leakref; } function modifyDocument2(document) { // The "
body" DOM node holding a reference to leakref will prevent // that function object from being garbage collected and hence // will leak the whole bootstrap compartment. document.
body.someProperty = leakref; } See also Kris Maglione's guide to cleaning up bootstrapped extensions. Failing to clean up event listeners Extensions can be disabled and removed by user actions, but it also happens whe...
Game promotion - Game development
ilder made for indie game developers and provides a great starting point to create your website. Presskit() is a press kit builder that helps you create a press page to share with the media. Social media Your social media presence is very important -- follow the right hashtags, make friends, engage in conversations, help other devs in need. Honesty is key and you should be authentic, because no
body likes boring press releases or pushy advertisements. When the time comes your community will help you spread the word about your shiny little game. You should use at least Twitter and Facebook and be active on appropriate forums -- the most popular one is HTML5GameDevs.com. Share your gamedev news and answer questions, so people will value what you're doing and will know that you're ok. Remember...
...ng -- devs are sensitive on this matter and you may end up with an angry crowd if you just try to sell them something. Fairs The other event-related option is fairs (or expos) -- at such an event you can get a booth among other devs and promote your game to all the attendees passing by. If you do so, try to be unique and original, so you easily stand from the crowd. Do it the right way and every
body will be talking about you and your game. Having a booth gives you the possibility to interact with your fans directly -- besides the promotion part you can also test new builds of your game on regular people and fix any bugs (or incorporate any feedback) they uncover. You can't imagine what people may come up with when playing your game, and what obvious issues you've missed while spending hours ...
Initialize the framework - Game development
he framework. Using your favourite text editor, create a new HTML document, save it as index.html, in a sensible location, and add the following code to it: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Gamedev Phaser Workshop - lesson 01: Initialize the framework</title> <style>* { padding: 0; margin: 0; }</style> <script src="js/phaser.min.js"></script> </head> <
body> <script> var game = new Phaser.Game(480, 320, Phaser.CANVAS, null, { preload: preload, create: create, update: update }); function preload() {} function create() {} function update() {} </script> </
body> </html> Downloading the Phaser code Next, we need to go through the process of downloading the Phaser source code and applying it to our HTML document. This tutorial...
...ave the Phaser code inside a /js directory in the same location as your index.html file. Update the src value of the first <script> element as shown above. Walking through what we have so far At this point we have a charset defined, <title> and some basic CSS in the header to reset the default margin and padding. We also have a <script> element to apply the Phaser source code to the page. The
body contains a second <script> element, where we will write the JavaScript code to render the game and control it. The <canvas> element is generated automatically by the framework. We are initializing it by creating a new Phaser.Game object and assigning it to the game variable. The parameters are: The width and height to set the <canvas> to. The rendering method. The three options are AUTO, CAN...
Player paddle and controls - Game development
te() { game.physics.arcade.collide(ball, paddle); } The first parameter is one of the objects we are interested in -- the ball -- and the second is the other one, the paddle. This works, but not quite as we expected it to -- when the ball hits the paddle, the paddle falls off the screen! All we want is the ball bouncing off the paddle and the paddle staying in the same place. We can set the
body of the paddle to be immovable, so it won't move when the ball hits it. To do this, add the below line at the bottom of the create() function: paddle.
body.immovable = true; Now it works as expected. Controlling the paddle The next problem is that we can't move the paddle. To do that we can use the system's default input (mouse or touch, depending on platform) and set the paddle position to wh...
... the ball. Find the existing ball = game.add.sprite( ... ) line, and replace it with the following two lines: ball = game.add.sprite(game.world.width*0.5, game.world.height-25, 'ball'); ball.anchor.set(0.5); The velocity stays almost the same -- we're just changing the second parameter's value from 150 to -150, so the ball will start the game by moving up instead of down. Find the existing ball.
body.velocity.set( ... ) line and update it to the following: ball.
body.velocity.set(150, -150); Now the ball will start right from the middle of the paddle. Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: Next steps We can move the paddle and bounce the ball off it, but what's the point if the ball ...
HTTP header - MDN Web Docs Glossary: Definitions of Web-related terms
An HTTP header is a field of an HTTP request or response that passes additional information, altering or precising the semantics of the message or of the
body. Headers are case-insensitive, begins at the start of a line and are immediately followed by a ':' and a value depending of the header itself. The value finish at the next CRLF or at the end of the message. Traditionally, headers are classed in categories, though this classification is no more part of any specification: General header: Headers applying to both requests and responses but with no relation to the data eventually transmitted in the
body. Request header: Headers containing more information about the resource to be fetched or about the client itself. Response header: Headers with additional information about the ...
...and responses but with no relation to the data eventually transmitted in the
body. Request header: Headers containing more information about the resource to be fetched or about the client itself. Response header: Headers with additional information about the response, like its location or about the server itself (name, version, ...). Entity header: Headers containing more information about the
body of the entity, like its content length or its MIME-type. 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...
HTML: A good basis for accessibility - Learn web development
</td> <td id="aside" colspan="2" bgcolor="#ff80ff" valign="top"> <h2>Related</h2> <!-- aside content goes here --> </td> </tr> <!-- spacer row --> <tr id="spacer" height="10"> <td> </td> </tr> <!-- footer row --> <tr id="footer" bgcolor="#ffffff"> <td colspan="6"> <p>(C)Copyright 2050 by no
body. All rights reversed.</p> </td> </tr> </table> If you try to navigate this using a screen reader, it will probably tell you that there's a table to be looked at (although some screen readers can guess the difference between table layouts and data tables). You'll then likely (depending on which screen reader you're using) have to go down into the table as an object and look at i...
...This link allows people to bypass content repeated throughout multiple pages on a website, such as a website's header and primary navigation. Skip links are especially useful for people who navigate with the aid of assistive technology such as switch control, voice command, or mouth sticks/head wands, where the act of moving throug...
HTML: A good basis for accessibility - Learn web development
</td> <td id="aside" colspan="2" bgcolor="#ff80ff" valign="top"> <h2>Related</h2> <!-- aside content goes here --> </td> </tr> <!-- spacer row --> <tr id="spacer" height="10"> <td> </td> </tr> <!-- footer row --> <tr id="footer" bgcolor="#ffffff"> <td colspan="6"> <p>(C)Copyright 2050 by no
body. All rights reversed.</p> </td> </tr> </table> If you try to navigate this using a screen reader, it will probably tell you that there's a table to be looked at (although some screen readers can guess the difference between table layouts and data tables). You'll then likely (depending on which screen reader you're using) have to go down into the table as an object and look at i...
...This link allows people to bypass content repeated throughout multiple pages on a website, such as a website's header and primary navigation. Skip links are especially useful for people who navigate with the aid of assistive technology such as switch control, voice command, or mouth sticks/head wands, where the act of moving throug...
Debugging CSS - Learn web development
ting the element with the class of box1; this is the first element on the page with a bordered box drawn around it. If you look at the Rules view to the right of your HTML, you should be able to see the CSS properties and values applied to that element. You will see the rules directly applied to class box1 and also the CSS that is being inherited by the box from its ancestors, in this case to <
body>. This is useful if you are seeing some CSS being applied that you didn't expect. Perhaps it is being inherited from a parent element and you need to add a rule to overwrite it in the context of this element. Also useful is the ability to expand out shorthand properties. In our example the margin shorthand is used. Click on the little arrow to expand the view, showing the different longhand pro...
... (the small colored circle) that shows the color applied to the border. A color picker will open up and you can try out some different colors; these will update in real time on the page. In a similar fashion, you could change the width or style of the border. Adding a new property You can add properties using the DevTools. Perhaps you have realised that you don't want your box to inherit the <
body> element's font size, and want to set its own specific size? You can try this out in DevTools before adding it to your CSS file. You can click the closing curly brace in the rule to start entering a new declaration into it, at which point you can start typing the new property and DevTools will show you an autocomplete list of matching properties. After selecting font-size, enter the value you wa...
CSS FAQ - Learn web development
... </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. #stockTicker { font-weight: bold; font: 12px Verdana; /* font-weight is now set to normal */ } Use of the * selector The * wildcard selector refers to any element, and it has to be used with particular care.
body * { font-weight: normal; } #stockTicker { font: 12px Verdana; } .corpName { font-weight: bold; } .stockUp { color: red; } <div id="section"> NYS: <span class="corpName"><span class="stockUp">GE</span></span> +1.0 ... </div> In this example the
body * selector applies the rule to all elements inside
body, at any hierarchy level, including the .stockUp class. So font-weight: bold; applied to ...
... The use of the * selector should be minimized as it is a slow selector, especially when not used as the first element of a selector. Its use should be avoided as much as possible. ...
Fundamental text and font styling - Learn web development
p { font-weight: bold; } p { font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; } Line height The line-height property sets the height of each line of text -- this can take most length and size units, but can also take a unitless value, which acts as a multiplier and is generally considered the best option -- the font-size is multiplied to get the line-height. ...
...his active learning session, we don't have any specific exercises for you to do: we'd just like you to have a good play with some font/text layout properties, and see what you can produce! You can either do this using offline HTML/CSS files, or enter your code into the live editable example below. If you make a mistake, you can always reset it using the Reset button. ...
Typesetting a community school homepage - Learn web development
the bottom of the CSS file, to make sure it is easy to mark the bits you have done. Don't worry if some of the selectors are repetitious; we'll let you off in this instance. Fonts: First of all, download a couple of free-to-use fonts. Because this is a college, the fonts should be chosen to give the page a fairly serious, formal, trustworthy feel -- a serif site-wide font for the general text
body, coupled with sans-serif or slab serif for the headings might be nice. Use a suitable service to generate bulletproof @font-face code for these two fonts. Apply your
body font to the whole page, and your heading font to your headings. General text styling: Give the page a site-wide font-size of 10px. Give your headings and other element types appropriate font-sizes defined using a suitabl...
... slab serif for the headings might be nice. Use a suitable service to generate bulletproof @font-face code for these two fonts. Apply your
body font to the whole page, and your heading font to your headings. General text styling: Give the page a site-wide font-size of 10px. Give your headings and other element types appropriate font-sizes defined using a suitable relative unit. Give your
body text a suitable line-height. Center your top level heading on the page. Give your headings a little bit of letter-spacing to make them not too too squashed, and allow the letters to breathe a bit. Give your
body text some letter-spacing and word-spacing, as appropriate. Give the first paragraph after each heading in the <section> a little bit of text-indentation, say 20px. Links: Give th...
HTML basics - Learn web development
ument That wraps up the basics of individual HTML elements, but they aren't handy on their own. Now we'll look at how individual elements are combined to form an entire HTML page. Let's revisit the code we put into our index.html example (which we first met in the Dealing with files article): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My test page</title> </head> <
body> <img src="images/firefox-icon.png" alt="My test image"> </
body> </html> Here, we have the following: <!DOCTYPE html> -- the doctype. It is required preamble. In the mists of time, when HTML was young (around 1991/92), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other use...
...rity of written languages. Essentially, it can now handle any textual content you might put on it. There is no reason not to set this and it can help avoid some problems later on. <title></title> -- the <title> element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in. It is also used to describe the page when you bookmark/favourite it. <
body></
body> -- the <
body> element. This contains all the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks or whatever else. Images Let's turn our attention to the <img> element again: <img src="images/firefox-icon.png" alt="My test image"> As we said before, it embeds an image into our page in the position it ...
JavaScript basics - Learn web development
d 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. Go to your test site and create a new folder named scripts. Within the scripts folder, create a new file called main.js, and save it. In your index.html file, enter this code on a new line, just before the closing </
body> tag: <script src="scripts/main.js"></script> This is doing the same job as the <link> element for CSS. It applies the JavaScript to the page, so it can have an effect on the HTML (along with the CSS, and anything else on the page). Add this code to the main.js file: const myHeading = document.querySelector('h1'); myHeading.textContent = 'Hello world!'; Make sure the HTML and JavaScrip...
...the identity operator (as described above) to compare the variable iceCream with the string chocolate to see if the two are equal. If this comparison returns true, the first block of code runs. If the comparison is not true, the second block of code--after the else statement--runs instead. Functions Functions are a way of packaging functionality that you wish to reuse. It's possible to define a
body of code as a function that executes when you call the function name in your code. This is a good alternative to repeatedly writing the same code. You have already seen some uses of functions previously. For example: let myVariable = document.querySelector('h1'); alert('hello!'); These functions, document.querySelector and alert, are built into the browser. If you see something wh...
What’s in the head? Metadata in HTML - Learn web development
d in Getting started with HTML. Objective: To learn about the HTML head, its purpose, the most important items it can contain, and what effect it can have on the HTML document. What is the HTML head? Let's revisit the simple HTML document we covered in the previous article: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My test page</title> </head> <
body> <p>This is my page</p> </
body> </html> The HTML head is the contents of the <head> element -- unlike the contents of the <
body> element (which are displayed on the page when loaded in a browser), the head's content is not displayed on the page. Instead, the head's job is to contain metadata about the document. In the above example, the head is quite small: <head> <meta charset="utf-8">...
...t can possibly be put in the head, but rather to teach you how to use the major elements that you'll want to include in the head, and give you some familiarity. Let's get started. Adding a title We've already seen the <title> element in action -- this can be used to add a title to the document. This however can get confused with the <h1> element, which is used to add a top level heading to your
body content -- this is also sometimes referred to as the page title. But they are different things! 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 o...
From object to iframe — other embedding technologies - Learn web development
haracter).</p> <textarea id="code" class="input" style="width: 95%;min-height: 100px;"> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click...
...serves the website pages to disallow them from being embedded inside <iframe>s (see Configure CSP directives, below.) This makes sense -- an entire MDN page doesn't really make sense to be embedded in other pages unless you want to do something like embed them on your site and claim them as your own -- or attempt to steal data via clickjacking, which are both really bad things to do. Plus if every
body started to do this, all the additional bandwidth would start to cost Mozilla a lot of money. Only embed when necessary Sometimes it makes sense to embed third-party content -- like youtube videos and maps -- but you can save yourself a lot of headaches if you only embed third-party content when completely necessary. A good rule of thumb for web security is "You can never be too cautious. If you...
Responsive images - Learn web development
ages below the header. The header image will likely span the whole of the width of the header, and the content image will fit somewhere inside the content column. 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. In viewports below that width, the
body will stay at 100% of the width of the viewport. The header image has been set so that its center always stays in the center of the header, no matter what width the heading is set at. If the site is b...
...the width of the viewport. The header image has been set so that its center always stays in the center of the header, no matter what width the heading is set at. If the site is being viewed on a narrower screen, the important detail in the center of the image (the people) can still be seen, and the excess is lost off either side. It is 200px high. The content images have been set so that if the
body element becomes smaller than the image, the images start to shrink so that they always stay inside the
body, rather than overflowing it. However, issues arise when you start to view the site on a narrow screen device. The header below looks ok, but it's starting to take up a lot of the screen height for a mobile device. And at this size, it is difficult to see the people within the first conten...
Arrays - Learn web development
In an animated scene for example, you might have an array of objects representing the background graphics currently displayed, and you might only want 50 displayed at once, for performa...
...r the next term to be entered searchInput.value = ''; searchInput.focus(); } } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; }
body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea...
Silly story generator - Learn web development
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. Basic setup: Create a new file called main.js, in the same directory as your index.html file. Apply the external JavaScript file to your HTML by inserting a <script> element into your HTML referencing main.js. Put it just before the closing </
body> tag. Initial variables and functions: In the raw text file, copy all of the code underneath the heading "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" and paste it into the top of the main.js file. This gives you three variables that store references to the "Enter custom name" text field (customName), the "Generate random story" button (randomize), and the <p> element at the bottom of the ...
.... Initial variables and functions: In the raw text file, copy all of the code underneath the heading "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" and paste it into the top of the main.js file. This gives you three variables that store references to the "Enter custom name" text field (customName), the "Generate random story" button (randomize), and the <p> element at the bottom of the HTML
body that the story will be copied into (story), respectively. In addition you've got a function called randomValueFromArray() that takes an array, and returns one of the items stored inside the array at random. Now look at the second section of the raw text file -- "2. RAW TEXT STRINGS". This contains text strings that will act as input into our program. We'd like you to contain these inside variabl...
Starting our Svelte Todo list app - Learn web development
we have a name prop being specified when we instantiate the App component inside src/main.js, which isn't used inside App. The console should currently give you a message along the lines of "<App> was created with unknown prop 'name'". To get rid of this, remove the name prop from src/main.js; it should now look like so: import App from './App.svelte' const app = new App({ target: document.
body }) export default app Now if you check your testing server URL you'll see our Todos.svelte component being rendered: Adding static markup For the moment we will start with a static markup representation of our app, so you can see what it will look like. Copy and paste the following into our Todos.svelte component file, replacing the existing content: <!-- Todos.svelte --> <div class="to...
...r: inherit; font: inherit; line-height: normal; -webkit-font-smoothing: inherit; -moz-osx-font-smoothing: inherit; -webkit-appearance: none; } button::-moz-focus-inner { border: 0; } button, input, optgroup, select, textarea { font-family: inherit; font-size: 100%; line-height: 1.15; margin: 0; } button, input { overflow: visible; } input[type="text"] { border-radius: 0; }
body { width: 100%; max-width: 68rem; margin: 0 auto; font: 1.6rem/1.25 Arial, sans-serif; background-color: #f5f5f5; color: #4d4d4d; } @media screen and (min-width: 620px) {
body { font-size: 1.9rem; line-height: 1.31579; } } /*END RESETS*/ /* GLOBAL STYLES */ .form-group > input[type="text"] { display: inline-block; margin-top: 0.4rem; } .btn { padding: 0.8rem 1rem 0.7...
Handling common HTML and CSS problems - Learn web development
me:</label> <input id="time" type="time"> </div> </form> The output of this code is as follows: Hidden example label { float: left; width: 30%; text-align: right; } input { float: right; width: 65%; } label, input { margin-bottom: 20px; } div { clear: both; margin: 10px; }
body { width: 400px; margin: 0 auto; } <form> <div> <label for="date">Enter a date:</label> <input id="date" type="date"> </div> <div> <label for="time">Enter a time:</label> <input id="time" type="time"> </div> </form> Note: You can also see this running live as forms-test.html on GitHub (see the source code also)...
...n set a browser query by pressing the Autoprefixer Settings button and entering the query in the text field in the Settings section on the page. In your code, you can select sections of CSS you want to add prefixes to, open the command pallette (Cmd/Ctrl + Shift + P), then type in Autoprefixer and select the Autoprefixer result that autocompletes. As an example, we entered the following code:
body { display: flex; } We highlighted it and ran the Autoprefixer command, and it replaced it with this:
body { display: -webkit-box; display: -ms-flexbox; display: flex; } Layout issues Another problem that might come up is differences in layouts between browsers. Historically this used to be much more of a problem, but recently, with modern browsers tending to support CSS more consisten...
Introducing a complete toolchain - Learn web development
velopment environment. Transformation: Tooling that allows us to use the latest features of a language (e.g. JavaScript) or another language entirely (e.g. JSX or TypeScript) in our development process, and then transforms our code so that the production version still runs on a wide variety of browsers, modern and older. Post development: Tooling that comes into play after you are done with the
body of development to ensure that your software makes it to the web and continues to run. In this case study we'll look at adding tests to your code, and deploying your app using Netlify so it is available for all the web to see. Let's start working on these, beginning with our development environment. Creating a development environment This part of the toolchain is sometimes seen to be delaying ...
...looks (or validates), it's very likely that it can be done with the right eslint configuration. A little later in this chapter, we'll provide the eslint config. Once a working configuration is in place, running the command can generate some useful information. Here is an example eslint output: ./my-project/src/index.js 2:8 error 'React' is defined but never used no-unused-vars 22:20 error '
body' is defined but never used no-unused-vars 96:19 error 'b' is defined but never used no-unused-vars ? 3 problems (3 errors, 0 warnings) Note: We'll install eslint in the next section; don't worry about this for now. As with other tools, code editor integration support is typically good for eslint, and potentially more useful as it can give us real-time feedback when issues crop up: ...
Package management basics - Learn web development
about how you structure your project. Other tools can be very different, but at least Parcel makes it easy for our initial experiment. So now we need to add an index.html file to our working directory. Create index.html in your test directory, and give it the following contents: <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <title>My test page</title> </head> <
body> <script src="./index.js"></script> </
body> </html> Next, we need to add an index.js file in the same directory as index.html. For now index.js can be empty; it just needs to exist. Create this now. Having fun with Parcel Now we'll run our newly installed Parcel tool. In your terminal, run the following command: parcel index.html You should see something like this printed to your term...
...some page content. Let's say we want to show human-readable relative dates, such as "2 hours ago", "4 days ago" and so on. The date-fns package's formatDistanceToNow() method is useful for this (there's other packages that do the same thing too). In the index.js file, add the following code and save it: import { formatDistanceToNow } from 'date-fns' const date = '1996-09-13 10:00:00'; document.
body.textContent = formatDistanceToNow(new Date(date)) + ' ago'; Go back to http://localhost:1234 and you'll see how long ago it is since the author turned 18. What's particularly special about the code above is that it is using the formatDistanceToNow() function from the date-fns package, which we didn't install! Parcel has spotted that you need the module, searched for it in the npmjs.com package ...
Accessibility API cross-reference
ors' names etc. contentinfo <footer> Page footers are often tagged as an Artifact (not "real" content) with the 'contentinfo' provided as document level XMP metadata instead The mouse pointer - when and how is this used? CURSOR n/a n/a n/a A definition of a term or concept. definition <dd>, <dfn> <L
Body> Iconified version of an app (n/a - use either PUSHBUTTON or LISTITEM) DESKTOP_ICON DESKTOP_ICON n/a A specific kind of a graphic - a diagram. DIAGRAM n/a n/a figure <figure> A dial or a knob. MSAA only. DIAL n/a n/a n/a A dialog or message box. DIALOG DIALOG DIALOG ...
...e of contents item). In such a case, they should be wrapped in a <Reference> Pragmatically however, user agents should expect to find <Link> tags as direct children of <TOCI> A list LIST LIST LIST list <ol>, <ul> <L> An item in a list LISTITEM n/a LIST_ITEM listitem <li> <LI> may contain <Lbl> (bullet, numeral, term etc.) and <L
Body> A type of live region where new information is added in meaningful order and old information may disappear. log The main content of a document, distinct from complementary info, headers, footers, navigation, asides etc. main <main> A type of live region where non-essential information changes frequently. ...
Gecko info for Windows accessibility vendors
it is, than variant.bstrVal contains the role string. The role string may be an HTML tag name followed by comma, space and the namespace of the current element. In most current cases the namespace can be ignored, but it may become important in the future. The following HTML tags are exposed as BSTR's: abbr, acronym, blockquote, dd, dl, dt, form, frame, h1, h2, h3, h4, h5, h6, iframe, q, t
body, tfoot, thead In addition, an HTML list uses the bullet BSTR role to expose bullets and numbers that are automatically inserted into the formatting by Gecko. In addition, ROLE_LIST with STATE_READONLY and ROLE_LISTITEM are used to expose the list structure. This makes it important to check the STATE_READONLY flag when encountering a ROLE_LIST, because the HTML list form element also uses ROL...
...t supported, STATE_HASPOPUP used with ROLE_BUTTON instead ROLE_BUTTONDROPDOWNGRID Supported for XUL <colorpicker> ROLE_PAGETABLIST XUL: <tab> DHTML: role="wairole:tabs" "abbr", "acronym", "blockquote", "dd", "dl", "dt", "form", "frame", "h1", "h2", "h3", "h4", "h5", "h6", "iframe", "q", "t
body", "tfoot", "thead" HTML tag mirrors the role string "bullet" Indirectly created for bullets when <ol> or <ul> used to create an HTML list "abbr", "acronym", "blockquote", "form", "frame", "h1", "h2", "h3", "h4", "h5", "h6", "iframe", "q", "t
body", "tfoot", "thead" Created from the identical HTML markup No name ...
MozBeforePaint
.g. 50 or 60. This is intentional, because modern operating systems and hardware won't let the browser display more frames than that anyway. Limiting the frame rate avoids wasting work, thereby saving CPU usage and power and improving overall system performance. Example This example performs a simple animation, moving a box a short distance after a short period of time. ...
...This computes the current position for the animating box and updates the box's position on screen, and, if the animation sequence is not yet complete, calls window.requestAnimationFrame() to schedule the next animation frame to be drawn. When the animation sequence completes, removes the event listen...
Examples
is locating uncaught rejections. Warning: When consuming promises, you should always handle or report errors (rejection reasons). See handling errors and common pitfalls. Rejection handlers provide information about the exact error time and location, but the handlers may sometimes be forgotten. ...
...s and common pitfalls. Rejection handlers provide information about the exact error time and location, but the handlers may sometimes be forgotten. Consider the following cases: function f() { return Promise.reject(new Error("BOOM!")); // If no
body catches the error, how will it be reported? } function g() { return Promise.resolve().then(function() { throw new Error("BOOM!"); // If no
body catches the error, how will it be reported? }); } function h() { Promise.reject(new Error("BOOM!"); // Oops, we forgot to return the promise, no
body can catch it! } We adopt the following strategy: if a promise is rejected at the time of its garbage-collection and if the promise is at the end of a promise chain (i.e. thatPromise.then has never been called), then we print a warning. Note: ...
WebRequest.jsm
String The HTTP method to be used (GET, POST, etc). responseHeaders Array of HTTP headers. The HTTP response headers that were received. This is only included if you set "responseHeaders" in the opt_extraInfoSpec argument. statusCode Number HTTP response code. onResponseStarted Triggered once the browser has started to receive the response
body. Note that you can't pass "blocking" for this event, so you can't modify or cancel the request from this event: it's informational only. opt_extraInfoSpec values Name Description "responseHeaders" Include response headers in the argument passed to the listener. Listener argument Name Type Description url String Target of the requ...
...ontent-Type" value String Header value, for example "image/png" Chrome incompatibilities Although this API is modeled on Chrome's webRequest extension API, there are some differences. We're working on addressing them, though. filtering by windowId and tabId is not supported. the onAuthRequired, onBeforeRedirect, and onErrorOccurred events are not supported. the "request
Body" instruction in opt_extraInfoSpec is not supported. redirection is not allowed in onBeforeRequest or onHeadersReceived, but is allowed in onBeforeSendHeaders. See bug 1176092. handlerBehaviorChanged() is not supported. requestId is not included in the argument passed to the listener. Examples Basic examples This example just logs the URL for every request initiated: let {WebRequest} = Cu.
Mozilla Web Developer FAQ
nces are safe, too.) document.write() is not supported. The stream that is going into the parser can't be tampered with in mid-parse. Things that look like XML comments are treated as XML comments--even inside script or style elements. Elements need to be in the XHTML namespace in order to be treated as XHTML elements. meta tags are not examined for character encoding information. t
body, head,
body, and html are not inferred if the tags are not explicitly present. CDATA sections are supported. XML empty element notation (<foo/>) is supported. White space characters in attribute values are normalized to spaces at parse time, so the original white space never makes it to the DOM. This affects data round tripping using hidden form inputs. In versions prior to Gecko 1...
...ime, so the original white space never makes it to the DOM. This affects data round tripping using hidden form inputs. In versions prior to Gecko 1.9/Firefox 3, the document is not loaded and rendered incrementally. The layout mode is the (Full) Standards Mode regardless of doctype. CSS works according to the XML+CSS rules. HTML-specific CSS exceptions do not apply. For example, the
body element gets no special treatment. CSS selectors are case-sensitive. The DOM is in the XML mode. Namespace-aware variants of methods need to be used when working with elements (eg. createElementNS() instead of createElement()). Element and attribute names are not normalized to upper case. Other namespaces are supported. MathML SVG (in SVG-enabled builds only) X...
Gecko Profiler FAQ
st Profiling non-nsThreads? The current setup requires each thread that you want to profile to notify the profiler about its existence. We have this hooked up for nsThreads, and as of very recently also for rayon threads (used in stylo). We have not attempted to register other threads with the profiler. Bug 1341811 suggests hooking platform thread spawning functions but no
body has looked at it yet. Profiling all nsThreads - how bad is the overhead? [mstange] I don't know. I think Julian Seward has done some measurements on this, I think. [ehsan] Try clicking the toolbar icon for the extension, expanding the Settings section, and enter the secret cheat code "," in the Threads field and click on "Apply (Restart Profiler)". This will ...
... markers are only exposed as a huge unsearchable list in the Markers tab. If you have a rough idea of what the user was doing, try searching for functions that you'd expect in the call tree and see where they are in the thread timeline. What is a suggested comprehensive performance analysis workflow for code changes that impact UI? [mstange] I don't know if any
body has written down such a workflow. My usual, very unscientific approach is: Use it for a while, and if you notice slowness, profile it. Pay attention to the red jank markers at the top. [ehsan] Mike Conley's Oh No Reflow! Add-on is helpful. How do we know when profiler output is statistically significant (for comparing across runs / across machines)? ...
Midas
rame. This also avoids problems with bug 198155. In addition to the built-in commands, advanced editing can be done by manipulating the Selection and range objects. It is beneficial to be familiar with these objects when working with an editable document. 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. Document.queryCommandEnabled Determines whether the given command can be executed on the document in its current state. Document.queryCommandIndeterm Determines whether the current selection is in an in...
...rue/false Selects whether pressing return inside a paragraph creates another paragraph or just inserts a <br> tag. inserthorizontalrule null/string (when string is the Line's id) This command will insert a horizontal rule (line) at the insertion point. Does it delete the selection? Yes! inserthtml A string. This command will insert the given html into the <
body> in place of the current selection or at the caret location. The given string is the HTML to insert. insertimage A URI. This command will insert an image (referenced by the given url) at the insertion point. insertorderedlist Depends on the selection. If the caret is not inside a non-LI block, that block becomes the first LI and an OL. If the caret is inside...
Hacking Tips
ck is order as defined in js/src/ion/IonFrames-x86-shared.h, it is composed of the return address, a descriptor (a small value), the JSFunction (if it is even) or a JSScript (if the it is odd, remove it to dereference the pointer) and the frame ends with the number of actual arguments (a small value too). If you want to know at which LIR the code is failing at, the js::ion::CodeGenerator::generate
Body function can be intrumented to dump the LIR id before each instruction. for (; iter != current->end(); iter++) { IonSpew(IonSpew_Codegen, "instruction %s", iter->opName()); [...] masm.store16(Imm32(iter->id()), Address(StackPointer, -8)); // added if (!iter->accept(this)) return false; [...] } This modification will add an instruction which abuse the stack pointer ...
...an call iongraph program within gdb when the execution is stopped. This instrumentation adds an iongraph command when provided with an instance of a MIRGenerator*, will call iongraph, graphviz and your prefered png viewer to display the MIR graph at the precise time of the execution. To find MIRGenetator* instances, is best is to look up into the stack for OptimizeMIR, or CodeGenerator::generate
Body. OptimizeMIR function has a mir argument, and the CodeGenerator::generate
Body function has a member this->gen. (gdb) bt #0 0x00000000007eaad4 in js::InlineList<js::jit::MBasicBlock>::begin() const (this=0x33dbbc0) at .../js/src/jit/InlineList.h:280 #1 0x00000000007cb845 in js::jit::MIRGraph::begin() (this=0x33dbbc0) at .../js/src/jit/MIRGraph.h:787 #2 0x0000000000837d25 in js::jit::BuildPhiR...
JS_EnterLocalRootScope
ot to manage global roots temporarily. JS_AddRoot roots a variable, ensuring that whatever the variable points to at any given moment is protected from GC. By contrast, local root scopes protect newly-created objects, doubles, and strings. There is no need to tell the JS engine about each variable that may point to such a value. Calling JS_EnterLocalRootScope and JS_LeaveLocalRootScope around the
body of the native hook protects each object, double, and string created using the same JSContext from GC. 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. Even if JS_G...
... JSContext from GC. 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. Even if JS_GC is // called, these new values will not be collected. ok = my_GetProperty
Body(cx, obj, id, vp); // When we leave the local root scope, this protection ends. New // items created in this local root scope become subject to GC. JS_LeaveLocalRootScope(cx); return ok; } Note: JS_LeaveLocalRootScope or JS_LeaveLocalRootScopeWithResult must be called once for every prior successful call to JS_EnterLocalRootScope. If JS_EnterLocalRootScope fails, you must not mak...
Feed content access API
: function(result) { var feed = result.doc; feed.QueryInterface(Components.interfaces.nsIFeed); // Open a new window var win = window.open("", "FeedTest_Window"); var doc = win.document.wrappedJSObject; doc.open(); // Write the HTML header and page title doc.write("<html><head><title>Feed: " + feed.title.text + "</title></head><
body>"); doc.write("<h1>" + feed.title.text + "</h1><p>"); var itemArray = feed.items; var numItems = itemArray.length; // Write the article information if (!numItems) { doc.write("<i>No news is good news!</i>"); } else { var i; var theEntry; var theUrl; var info; for (i=0; i<numItem...
...To get the title of the feed, you look at the feed.title property. The title is an nsIFeedTextConstruct that can represent the text in various formats; we get its text property to fetch the feed'...
Avoiding leaks in JavaScript XPCOM components
hese properties have to be preserved across garbage collections, even if the wrapper is not reachable from any garbage collection root, since the JavaScript programmer could access the DOM node again the same way he did the first time, and would then expect the added properties to still be there. We currently implement this by making the wrapper a root in the JavaScript garbage collector once some
body sets a JavaScript property on a DOM node. (This is roughly equivalent to making all the properties roots, but simpler.) Once this happens, it remains a root until the document stops being displayed. This means that neither the element nor any of the properties nor any of the objects reachable from those properties can be freed until the document is no longer displayed. You might think that it's ...
...e don't do anything to protect them from garbage collection. This makes program behavior depend on when garbage collection happens, which means the API is nondeterministic, which is really bad. This situation may improve at some point in the future. The situation with JavaScript properties on DOM nodes may also improve--see bug 283129--but it requires substantial changes.) Things not to do Every
body writing, reviewing, or checking in JavaScript code to Mozilla CVS should understand why these things are bad. Don't store temporary objects permanently in global variables Storing temporary objects permanently in global variables will leak memory in garbage-collected languages. That it leaks in the XPCOM+JavaScript world isn't at all special. The most common way this is done in JavaScript is o...
Starting WebLock
case of the components, which also require unique identifiers, the identifier is the CID. Subclassing nsISupports The next line in iWebLock names the interface and defines its base interface. iWeblock derives from nsISupports. XPIDL has no way to define multiple inheritance - something that all scriptable objects must deal with. interface iWebLock : nsISupports The Web Locking Interface The
body of the block (the stuff between the curly braces) defines the methods and attributes of our interface. There are basically two functional sets on this interface. The first section of the interface controls whether or not WebLock checks to see if a web page can be loaded. If locked, WebLock will prevent sites not on the white list from loading. void lock(); void unlock(); This interface doe...
...server, public iWebLock { public: WebLock(); virtual ~WebLock(); NS_DECL_ISUPPORTS NS_DECL_NSIOBSERVER NS_DECL_IWEBLOCK }; Note that we derive from the nsIObserver interface as well as the iWeblock class. We do not need to explicitly derive from nsISupports as both of these two other interfaces are already subclasses of nsISupports: Interface Hierarchy for WebLock The
body of the class declaration uses declaration macros that are generated from an XPIDL interface file. Every header generated from an XPIDL file has a similar macro that defines all the methods in that interface. This makes changes to the interface when designing a bit simpler, as you do not have to modify any class declarations. There are times, of course, when you cannot use these macros-as when tw...
mozIRegistry
. It happens that this objective requires storing information about which implementation to use in a place distinct from your source code. And it happens that we've chosen, up till now, to store that information in the "Netscape registry" file. Which explains how this information came to be associated with the notion of a "registry." Someday (I hope) this page will be properly titled so that every
body knows it is the place to come to in order to find out how they are supposed to link together the various XPCOM components that together form the Mozilla browser. The information below is intended to tell you everything you need to know about how to do that. Summary Clients will rely on nsRepository to create instances of a given class. Clients requiring dynamic "binding" of CLSIDs will be requ...
...e explaining the rationale for the design and implementation of these components in this document. Lastly, there's one component (labelled "mozRDFRegistry/nsIRDFDatabase") that potentially will emerge as an improved implementation of one of the mozIRegistry interfaces. I'll be discussing that implementation only briefly (mainly because I'm hoping I can pawn off the chore of implementing it to some
body else). There's another component that turns out to also be real important when you go to hook up your code with other Mozilla components. That's the Service Manager. I'm just starting to understand the role it plays in this and it isn't really under my jurisdiction, so there's nothing about it here right now. In the future, I'll either add the information about it or at least put in a link to i...
nsIMsgFilterCustomAction
readonly attribute boolean needs
Body; }; ...
...w); /* does this action start an async action? If so, a copy listener must * be used to continue filter processing after the action. This only * applies to after-the-fact (manual) filters. Call OnStopCopy when done * using the copyListener to continue. */ readonly attribute boolean isAsync; /// Does this action need the message
body? readonly attribute boolean needs
Body; }; ...
nsIMsgWindow
lemented by: @mozilla.org/messenger/msgwindow;1. To create an instance, use: msgWindow = Components.classes["@mozilla.org/messenger/msgwindow;1"] .createInstance(Components.interfaces.nsIMsgWindow); In Thunderbird the default message window is stored in the global variable msgWindow. Method overview void displayHTMLInMessagePane(in AString title, in AString
body, in boolean clearMsgHdr); void StopUrls(); void closeWindow(); Attributes Attribute Type Description windowCommands nsIMsgWindowCommands This allows the backend code to send commands to the UI, such as clearMsgPane. statusFeedback nsIMsgStatusFeedback This allows the backend...
... nsIDOMWindow The message window's global chrome window object. Set this to initialize the rootDocShell. Methods displayHTMLInMessagePane() Loads the specified HTML in the message pane. This is equivalent to calling LoadURI on the nsIWebNavigation object with a data: URL specifying the HTML. void displayHTMLInMessagePane(in AString title, in AString
body, in boolean clearMsgHdr); Parameters title Not used.
body The HTML to display in the message pane. Note that the HTML is wrapped in <html> and <
body> tags for you. clearMsgHdr Whether or not the existing message pane and header should be cleared before the HTML is displayed. StopUrls() This is equivalent to calling Stop(ns...
nsMsgSearchScope
Defined in comm-central/ mailnews/ base/ search/ public/ nsMsgSearchCore.idl [scriptable, uuid(6e893e59-af98-4f62-a326-0f00f32147cd)] interface nsMsgSearchScope { const nsMsgSearchScopeValue offlineMail = 0; const nsMsgSearchScopeValue offlineMailFilter = 1; const nsMsgSearchScopeValue onlineMail = 2; const nsMsgSearchScopeValue onlineMailFilter = 3; /// offline news, base table, no
body or junk const nsMsgSearchScopeValue localNews = 4; const nsMsgSearchScopeValue news = 5; const nsMsgSearchScopeValue newsEx = 6; const nsMsgSearchScopeValue LDAP = 7; const nsMsgSearchScopeValue LocalAB = 8; const nsMsgSearchScopeValue allSearchableGroups = 9; const nsMsgSearchScopeValue newsFilter = 10; const nsMsgSearchScopeValue LocalABAnd = 11; const nsMsgSearchScopeValue LD...
...ue LocalAB = 8; const nsMsgSearchScopeValue allSearchableGroups = 9; const nsMsgSearchScopeValue newsFilter = 10; const nsMsgSearchScopeValue LocalABAnd = 11; const nsMsgSearchScopeValue LDAPAnd = 12; // IMAP and NEWS, searched using local headers const nsMsgSearchScopeValue onlineManual = 13; /// local news + junk const nsMsgSearchScopeValue localNewsJunk = 14; /// local news +
body const nsMsgSearchScopeValue localNews
Body = 15; /// local news + junk +
body const nsMsgSearchScopeValue localNewsJunk
Body = 16; }; ...
Mail composition back end
broken in to a few different calls. Currently, this method does several functions depending on the arguments passed in, but this could easily lead to confusion. This is something that very well may change as time allows). NS_IMETHOD CreateAndSendMessage( nsIEditorShell *aEditor, - the editor object for the mail compose operation. If this is not null, the
body will be extracted from this object and any embedded objects or links will be sent as part of the message in MHTML nsIMsgIdentity *aUserIdentity, - the user identity for the person doing the send operation. This will be needed to determine the appropriate folder for copy operations. nsIMsgCompFields *fields, - the message ...
...eAs, nsMsgSaveAsDraft, nsMsgSaveAsTemplate. nsIMessage *msgToReplace, - if the delivery mode is set to nsMsgSaveAsDraft, this is a pointer to the the nsIMessage object for the message that needs to be replaced const char *attachment1_type, const char *attachment1_
body, PRUint32 attachment1_
body_length, - the full text of the first attachment is provided via `attachment1_type' `attachment1_
body' and `attachment1_
body_length'. These may all be 0 if all attachments are provided externally. const struct nsMsgAttachmentData *attachments, - Subsequent attachments are provided as URLs to load, describ...
The libmime module
(Foobar, FoobarClass, foobarClass, &MIME_SUPERCLASS); The definition of MIME_SUPERCLASS is just to move most of the knowlege of the exact class hierarchy up to the file's header, instead of it being scattered through the various methods; see below. Method Declarations We will be putting function pointers into the class object, so we declare them here. They can generally all be static, since no
body outside of this file needs to reference them by name; all references to these routines should be through the class object. extern int FoobarMethod(Foobar *); ...etc... Class Initialization Function The MimeDefClass macro expects us to define a function which will finish up any initialization of the class object that needs to happen before the first time it is instantiated. Its name m...
...- MimeInlineTextHTML | | | | | |--- MimeInlineTextRichtext | | | | | | | |--- MimeInlineTextEnriched | | | | | |--- MimeInlineTextVCard | | | | | |--- MimeInlineTextCalendar | | | |--- MimeInlineImage | | | |--- MimeExternalObject | |--- MimeExternal
Body ...
Plug-in Basics - Plugins
edding plug-ins in ActiveX applications. The following examples demonstrate this use of nested object elements with markup more congenial to Gecko included as children of the parent object element. ...
...This nesting is quite common in the use of object elements, and lets you avoid code forking for different browsers. Nesting...
URLs - Plugins
RL works identically with buffers and files. To post data from a memory buffer, set the flag file to false, the buffer buf to the data to post, and len to the length of the buffer. Possible URL types include http (similar to an HTML form submission), mailto (sending mail), news (posting a news article), and ftp (uploading a file). For protocols in which the headers must be distinguished from the
body, such as http, the buffer or file should contain the headers, followed by a blank line, then the
body. If no custom headers are required, simply add a blank line ('\n') to the beginning of the file or buffer. NOTE: You cannot use NPN_PostURL to specify headers (even a blank line) in a memory buffer. To do this, use NPN_PostURLNotify for this purpose. ? The NPN_PostURLNotify function has all the ...
...ta, and its length, myLength. It sends myData and myLength to the mailto URL mailto:fred@example.com. The target window for displaying the message is null in the example. Normally, using a null target window causes the response to be delivered from the server to the plug-in instance in a new stream, but no response is expected for a mailto URL. You cannot use either of these functions to set the
body or attachments of an email message. << PreviousNext >> ...
AudioContext.createMediaStreamDestination() - Web APIs
, and the event data is pushed into the chunks array. After that, the stop event fires, a new blob is made of type opus -- which contains the data in the chunks array, and a new window (tab) is then opened that points to a URL created from the blob. From here, you can play and save the opus file. ...
...ediaRecorder.ondataavailable = function(evt) { // push each chunk (blobs) in an array chunks.push(evt.data); }; mediaRecorder.onstop = function(evt) { // Make blob out of our blobs, and open it. var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); document.querySelector("audio").src = URL.createObjectURL(blob); }; </script> </
body> </html> Note: You can view this example live, or study the source code, on Github. Specifications Specification Status Comment Web Audio APIThe definition of 'createMediaStreamDestination()' in that specification. Working Draft ...
Managing screen orientation - Web APIs
ing elit. Duis lacinia nisi nec sem viverra vitae fringilla nulla ultricies. In ac est dolor, quis tincidunt leo. Cras commodo quam non tortor consectetur eget rutrum dolor ultricies. Ut interdum tristique dapibus. ...
...a vitae fringilla nulla ultricies. In ac est dolor, quis tincidunt leo. Cras commodo quam non tortor consectetur eget rutrum dolor ultricies. Ut interdum tristique dapibus. ...
DataTransfer.effectAllowed - Web APIs
e moved element to the target's DOM var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragover_handler(ev) { console.log("dragOver: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } </script> <
body> <h1>Examples <code>DataTransfer</code>.{<code>dropEffect</code>, <code>effectAllowed</code>} properties</h1> <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 ...
... Living Standard HTML 5.1The definition of 'effectAllowed' in that specification. Recommendation Initial definition ...
DataTransfer.items - Web APIs
e" if (ev.dataTransfer.items != null) { for (var i=0; i < ev.dataTransfer.items.length; i++) { console.log("... ...
... Living Standard HTML 5.1The definition of 'items' in that specification. Recommendation Initial definition ...
DataTransfer.setData() - Web APIs
ion dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); // Get the data, which is the id of the drop target var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); // Clear the drag data cache (for all formats/types) ev.dataTransfer.clearData(); } </script> <
body> <h1>Examples of <code>DataTransfer</code>: <code>setData()</code>, <code>getData()</code>, <code>clearData()</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(ev...
... Living Standard HTML 5.1The definition of 'setData()' in that specification. Recommendation Initial definition ...
DataTransfer.types - Web APIs
e" if (ev.dataTransfer.items != null) { for (var i=0; i < ev.dataTransfer.items.length; i++) { console.log("... ...
... Living Standard HTML 5.1The definition of 'types' in that specification. Recommendation Initial definition ...
Document.alinkColor - Web APIs
Gecko supports both alinkColor/:active and :focus. ...
...lor; document.alinkColor = color; color is a string containing the name of the color (e.g., blue, darkblue, etc.) or the hexadecimal value of the color (e.g., #0000FF) Notes The default value for this property in Mozilla Firefox is red (#ee0000 in hexadecimal). document.alinkColor is deprecated in DOM Level 2 HTML. One alternative is the CSS selector :active. Another alternative is document.
body.aLink, although this is deprecated in HTML 4.01 in favor of the CSS alternative. Gecko supports both alinkColor/:active and :focus. Internet Explorer 6 and 7 support alinkColor/:active only for HTML anchor (<a>) links and the behavior is the same as :focus under Gecko. There is no support for :focus in IE. ...
Document.createTreeWalker() - Web APIs
h a method acceptNode, which is called by the TreeWalker to determine whether or not to accept a node that has passed the whatToShow check. entityReferenceExpansion Optional A Boolean flag indicating if when discarding an EntityReference its whole sub-tree must be discarded at the same time. Return value A new TreeWalker object. ...
...le 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.evaluate() - Web APIs
re used. resultType is an integer that corresponds to the type of result XPathResult to return. Use named constant properties, such as XPathResult.ANY_TYPE, of the XPathResult constructor, which correspond to integers from 0 to 9. result is an existing XPathResult to use for the results. 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. * The result will likely be an unordered node iterator. */ 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...
...lly on very large documents. This is because the evaluation of the query spends does not waste time visiting unnecessary nodes. Using // is generally slow as it visits every node from the root and all subnodes looking for possible matches. Further optimization can be achieved by careful use of the context parameter. For example, if you know the content you are looking for is somewhere inside the
body tag, you can use this: document.evaluate(".//h2", document.
body, null, XPathResult.ANY_TYPE, null); Notice in the above document.
body has been used as the context instead of document so the XPath starts from the
body element. (In this example, the "." is important to indicate that the querying should start from the context node, document.
body. If the "." was left out (leaving //h2) the query w...
Document.getElementsByClassName() - Web APIs
e HTMLCollection as the method's this value. Here we'll find all div elements that have a class of 'test': var testElements = document.getElementsByClassName('test'); var testDivs = Array.prototype.filter.call(testElements, function(testElement){ return testElement.nodeName === 'DIV'; }); Get the first element whose class is 'test' This is the most commonly used method of operation. ...
...Only elements with ALL of the classNames specified are selected. HTML <span class="orange fruit">Orange Fruit</span> <span class="orange juice">Orange Juice</span> <span class="apple juice">Apple Juice</span> <span class="foo bar">Something Random</sp...
Document.getElementsByTagName() - Web APIs
var div1Paras = div1.getElementsByTagName('p'); var num = div1Paras.length; alert('There are ' + num + ' paragraph in #div1'); } function div2ParaElems() { var div2 = document.getElementById('div2'); var div2Paras = div2.getElementsByTagName('p'); var num = div2Paras.length; alert('There are ' + num + ' paragraph in #div2'); } </script> </head> <
body style="border: solid green 3px"> <p>Some outer text</p> <p>Some outer text</p> <div id="div1" style="border: solid blue 3px"> <p>Some div1 text</p> <p>Some div1 text</p> <p>Some div1 text</p> <div id="div2" style="border: solid red 3px"> <p>Some div2 text</p> <p>Some div2 text</p> </div> </div> <p>Some outer text</p> <p>Some outer text</p> <button...
...This is undesirable when trying to match camelCase SVG elements in a subtree in an HTML document. document.getElementsByTagNameNS() is useful in that case. See also bug 499656. document.getElementsByTagName() is similar to Element.getElementsByTagName(), except that its search en...
Document.getElementsByTagNameNS() - Web APIs
/xhtml", "p"); var num = div1Paras.length; alert("There are " + num + " <p> 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; alert("There are " + num + " <p> elements in div2 element"); } </script> </head> <
body style="border: solid green 3px"> <p>Some outer text</p> <p>Some outer text</p> <div id="div1" style="border: solid blue 3px"> <p>Some div1 text</p> <p>Some div1 text</p> <p>Some div1 text</p> <div id="div2" style="border: solid red 3px"> <p>Some div2 text</p> <p>Some div2 text</p> </div> </div> <p>Some outer text</p> <p>Some outer text</p> <button onclick="getA...
...(To accommodate Explorer, one could call an XPath wrapper instea...
Document.height - Web APIs
Note: Starting in Gecko 6.0, document.height is no longer supported. Instead, use document.
body.clientHeight. See element.clientHeight. Returns the height of the document object. In most cases, this is equal to the <
body> element of the current document. ...
... Note: Starting in Gecko 6.0, document.height is no longer supported. Instead, use document.
body.clientHeight. See element.clientHeight. Returns the height of the document object. In most cases, this is equal to the <
body> element of the current document. ...
Document.ononline - Web APIs
Both events are non-cancellable (you can't prevent the user from coming online, or going offline). window.navigator.onLine returns boolean true if the browser is online and false if it is definitely offline (disconnected from the network). The online and offline events are fired when the value of this attribute changes. It is important to note that this event and attribute are inherently unreliable. A computer can be connected to a network without having Internet access. ...
...connected from the network). The online and offline events are fired when the value of this attribute changes. It is important to note that this event and attribute are inherently unreliable. A computer can be connected to a network without having Internet access. You can register listeners for these events in a few familiar ways: Using addEventListener on the window, document, or document.
body By setting the .ononline or .onoffline properties on document or document.
body to a JavaScript Function object. (Note: using window.ononline or window.onoffline will not work for compatibility reasons.) By specifying ononline="..." or onoffline="..." attributes on the <
body> tag in the HTML markup. Example There's a simple test case that you can run to verify that the events are working. Re...
Element.getAttributeNS() - Web APIs
amespaced 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. ...
...HTML5 documents have to use getAttribute() instead. 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. Prior to the DOM4 spec...
Element.getBoundingClientRect() - Web APIs
scrollY) to get a bounding rectangle which is independent from the current scrolling position. Cross-browser fallback Scripts requiring high cross-browser compatibility can use window.pageXOffset and window.pageYOffset instead of window.scrollX and window.scrollY. Scripts without access to these properties can use code like this: // For scrollX (((t = document.documentElement) || (t = document.
body.parentNode)) && typeof t.scrollLeft == 'number' ? t : document.
body).scrollLeft // For scrollY (((t = document.documentElement) || (t = document.
body.parentNode)) && typeof t.scrollTop == 'number' ? 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. ...
...t its properties below it. <div></div> div { width: 400px; height: 200px; padding: 20px; margin: 50px auto; background: purple; } let elem = document.querySelector('div'); let rect = elem.getBoundingClientRect(); for (var key in rect) { if(typeof rect[key] !== 'function') { let para = document.createElement('p'); para.textContent = `${ key } : ${ rect[key] }`; document.
body.appendChild(para); } } Notice how the width/height are equal to the equal to its width/height + padding. Also note how the values of x/left, y/top, right, and bottom are equal to the absolute distance from the relevant edge of the viewport to that side of the element, in each case. Specifications Specification Status Comment CSS Object Model (CSSOM) View Module...
Element.localName - Web APIs
Qualified names are typically used in XML as part ...
...Qualified names are typically used in XML as part of the namespace(s) of the particular XML documents. ...
Element.scrollWidth - Web APIs
e width of the content of element in pixels. ...
...00px; } button { margin-bottom: 2em; } </style> </head> <
body> <div id="aDiv"> FooBar-FooBar-FooBar-FooBar </div> <button id="aButton"> Check for overflow </button> <div id="anotherDiv"> FooBar-FooBar-FooBar-FooBar </div> <button id="anotherButton"> Check for overflow </button> </
body> <script> var buttonOne = document.getElementById('aButton'), buttonTwo = document.getElementById('anotherButton'), divOne = document.getElementById('aDiv'), divTwo = document.getElementById('anotherDiv'); //check to determine if an overflow is happening function isOverflowing(element) { return (element.scrollWidth > element.offsetWidth); } function alert...
Element.setCapture() - Web APIs
Specification Based on Internet Explorer's implementation. ...
... Specification Based on Internet Explorer's implementation. ...
ElementCSSInlineStyle.style - Web APIs
m style rules elsewhere, such as style rules in the <head> section, or external style sheets. To get the values of all CSS properties for an element you should use Window.getComputedStyle() instead. ...
...heets. To get the values of all CSS properties for an element you should use Window.getComputedStyle() instead. ...
Comparison of Event Targets - Web APIs
border-collapse: collapse; height: 150px; width: 100%; } td { border: 1px solid #ccc; font-weight: bold; padding: 5px; min-height: 30px; } .standard { background-color: #99ff99; } .non-standard { background-color: #902D37; } </style> </head> <
body> <table> <thead> <tr> <td class="standard">Original target dispatching the event <small>event.target</small></td> <td class="standard">Target who's event listener is being processed <small>event.currentTarget</small></td> <td class="standard">Identify other element (if any) involved in the event <small>event.relatedTarget</small></td> ...
...For the mouseout event, it holds the node that the mouse moved to. Event type event.target event.relatedTarget mouseover the EventTarget which the pointing device entered the EventTarget which the pointing device exited ...
Event.composed - Web APIs
); }); When you click on the <open-shadow> element and then the <closed-shadow> element, you'll notice two things. The composed property returns true beause the click event is always able to propagate across shadow boundaries. You'll notice a difference in the value of composedPath for the two elements. ...
...ropagate across shadow boundaries. You'll notice a difference in the value of composedPath for the two elements. 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. Specifications Specification Status Comment DOMThe definition of 'composed' in that specification. Living Standard ...
Event.composedPath() - Web APIs
hen you click on the <open-shadow> element and then the <closed-shadow> element, you'll notice two things. First, the composed property returns true beause the click event is always able to propagate across shadow boundaries. Second, you'll notice a difference in the value of composedPath for the two elements. ...
...ate across shadow boundaries. Second, you'll notice a difference in the value of composedPath for the two elements. 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. Specifications Specification Status Comment DOMThe definition of 'composedPath()' in that specification. Living Standar...
Fetch API - Web APIs
o fetch resources in. The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to the Response to that request, whether it is successful or not. You can also optionally pass in an init options object as the second argument (see Request). Once a Response is retrieved, there are a number of methods available to define what the
body content is and how it should be handled (see
Body). You can create a request and response directly using the Request() and Response() constructors, but it's uncommon to do this directly. Instead, these are more likely to be created as results of other API actions (for example, FetchEvent.respondWith() from service workers). Differences from jQuery The fetch specification differs from jQuery.aj...
...not already completed. See the interface pages for more details. Fetch Interfaces WindowOrWorkerGlobalScope.fetch() The fetch() method used to fetch a resource. Headers Represents response/request headers, allowing you to query them and take different actions depending on the results. Request Represents a resource request. Response Represents the response to a request. Fetch mixin
Body Provides methods relating to the
body of the response/request, allowing you to declare what its content type is and how it should be handled. Specifications Specification Status Comment Fetch Living Standard Initial definition ...
FileList - Web APIs
ileinput" multiple> var fileInput = document.getElementById("myfileinput"); // files is a FileList object (similar to NodeList) var files = fileInput.files; var file; // loop through files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } Here is a complete example. ...
...r to NodeList) var files = fileInput.files; var file; // loop through files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } Here is a complete example. ...
GlobalEventHandlers.ondrag - Web APIs
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="d...
... Living Standard HTML 5.1The definition of 'ondrag' in that specification. Recommendation Initial definition ...
GlobalEventHandlers.ondragend - Web APIs
ge the source element's border back to green to signify a dragexit event ev.currentTarget.style.background = "green"; } function init() { // Set handlers for the source's enter/leave/end/exit events var el=document.getElementById("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <
body onload="init();"> <h1>Examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <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="dr...
... Living Standard HTML 5.1The definition of 'ondragend' in that specification. Recommendation Initial definition ...
GlobalEventHandlers.ondragenter - Web APIs
ge the source element's border back to green to signify a dragexit event ev.currentTarget.style.background = "green"; } function init() { // Set handlers for the source's enter/leave/end/exit events var el=document.getElementById("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <
body onload="init();"> <h1>Examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <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="dr...
... Living Standard HTML 5.1The definition of 'ondragenter' in that specification. Recommendation Initial definition ...
GlobalEventHandlers.ondragexit - Web APIs
ge the source element's border back to green to signify a dragexit event ev.currentTarget.style.background = "green"; } function init() { // Set handlers for the source's enter/leave/end/exit events var el=document.getElementById("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <
body onload="init();"> <h1>Examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <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="dr...
... Living Standard HTML 5.1The definition of 'ondragexit' in that specification. Recommendation Initial definition ...
GlobalEventHandlers.ondragleave - Web APIs
rce element's background color back to green to signify a dragexit event ev.currentTarget.style.background = "green"; } function init() { // Set handlers for the source's enter/leave/end/exit events var el=document.getElementById("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <
body onload="init();"> <h1>Examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</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="dr...
... Living Standard HTML 5.1The definition of 'ondragleave' in that specification. Recommendation Initial definition ...
GlobalEventHandlers.ondragover - Web APIs
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);" ondragove...
... Living Standard HTML 5.1The definition of 'ondragover' in that specification. Recommendation Initial definition ...
GlobalEventHandlers.ondragstart - Web APIs
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);" ondragove...
... Living Standard HTML 5.1The definition of 'ondragstart' in that specification. Recommendation Initial definition ...
GlobalEventHandlers.ondrop - Web APIs
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(eve...
... Living Standard HTML 5.1The definition of 'ondrop' in that specification. Recommendation Initial definition ...
GlobalEventHandlers.onload - Web APIs
At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading. There are also DOM Events like DOMContentLoaded and DOMFrameContentLoaded (which can be handle...
...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 event fires when the document has finished loading!</p> </
body> </html> Notes The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading. There are also DOM Events like DOMContentLoaded and DOMFrameContentLoaded (which can be handled using EventTarget.addEventListener()) which are fired after the DOM for the page...
HTMLCanvasElement.toBlob() - Web APIs
lement to the document, whose source image is the one created using the canvas. var canvas = document.getElementById('canvas'); canvas.toBlob(function(blob) { var newImg = document.createElement('img'), url = URL.createObjectURL(blob); newImg.onload = function() { // no longer need to read the blob so it's revoked URL.revokeObjectURL(url); }; newImg.src = url; document.
body.appendChild(newImg); }); Note that here we're creating a PNG image; if you add a second parameter to the toBlob() call, you can specify the image type. 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. Windows XP do...
...l use as the file name. ...
HTMLImageElement - Web APIs
n some way that prevents it from being loaded. The specified image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the <img> element's attributes. The specified image is in a format not supported by the user agent. ...
...s, and no dimensions were specified in the <img> element's attributes. The specified image is in a format not supported by the user agent. 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 Comment CSS Object Model (CSSOM) View ModuleThe definition of 'Extensions to HTMLImageElement' in that specification. Working Draft Added the x and y properties. HTML Living StandardThe definition of 'HTMLImageElement' in that specif...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
. This information is provided as a basis for why microtasks are useful and how they function; if you don't care, you can skip this and come back later if you find that you need to. When a fragment of JavaScript code runs, it runs inside an execution context. There are three types of code that create a new execution context: The global context is the execution context created to run the main
body of your code; that is, any code that exists outside of a JavaScript function. Each function is run within its own execution context. This is frequently referred to as a "local context." Using the ill-advised eval() function also creates a new execution context. Each context is, in essence, a level of scope within your code. As one of these code segments begins execution, a new context is cons...
...to handle each callback. It then runs any pending JavaScript tasks, then any pending microtasks, then performs any needed rendering and painting before looping again to check for pending tasks. Your web site or app's code runs in the same thread, sharing the same event loop, as the user interface of the web browser itself. This is the main thread, and in addition to running your site's main code
body, it handles receiving and dispatching user and other events, rendering and painting web content, and so forth. The event loop, then, drives everything that happens in the browser as it pertains to the interaction with the user, but more importantly for our purposes here, it is responsible for the scheduling and execution of every piece of code that runs within its thread. There are three types ...
The HTML DOM API - Web APIs
well as to using it to represent HTML documents specifically. Among the things added to Document by the HTML standard are: Support for accessing various information provided by the HTTP headers when loading the page, such as the location from which the document was loaded, cookies, modification date, referring site, and so forth. Access to lists of elements in the document's <head> block and
body, as well as lists of the images, links, scripts, etc. contained in the document. Support for interacting with the user by examining focus and by executing commands on editable content. Event handlers for document events defined by the HTML standard to allow access to mouse and keyboard events, drag and drop, media control, and more. Event handlers for events that can be delivered to both eleme...
... with similar functionality. In addition, the HTML DOM API includes a few interfaces and types to support the HTML element interfaces. HTML element interfaces These interfaces represent specific HTML elements (or sets of related elements which have the same properties and methods associated with them). ...
HashChangeEvent - Web APIs
The new URL to which the window is navigating. HashChangeEvent.oldURL Read only The previous URL from which the window was navigated. Methods This interface has no methods of its own, but inherits the methods of its parent, Event. 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('hashchange', locationHashChanged); Polyfill There are several fallback scripts listed on the Modernizr GitHub page. Basically, those scripts check the loc...
...ener('hashchange', locationHashChanged); Polyfill There are several fallback scripts listed on the Modernizr GitHub page. Basically, those scripts check the location.hash at a regular interval. Here is a version that allows only one handler to be bound to the onhashchange property: ;(function(window) { // Exit if the browser implements that event if ( "onhashchange" in window.document.
body ) { return; } var location = window.location, oldURL = location.href, oldHash = location.hash; // Check the location hash on a 100ms interval setInterval(function() { var newURL = location.href, newHash = location.hash; // If the hash has changed and a handler has been bound... if ( newHash != oldHash && typeof window.onhashchange === "function" ) { ...
MediaQueryList.addListener() - Web APIs
standard function, and the event object is a MediaQueryListEvent, which inherits from Event. Return value Void. ...
... Working Draft Initial definition ...
MediaQueryList.removeListener() - Web APIs
iaQueryListListener object. In the new implementation the standard event mechanism is used, and the callback is a standard function. Return value Void. ...
... Working Draft Initial definition ...
MediaQueryListEvent.matches - Web APIs
Syntax var matches = MediaQueryListEvent.matches; Value A Boolean; returns true if the document currently matches the media query list, false if not. ...
... Working Draft Initial definition ...
MediaQueryListEvent.media - Web APIs
OMString representing a serialized media query. Syntax var media = MediaQueryListEvent.media; Value A DOMString representing a serialized media query. ...
... Working Draft Initial definition ...
MediaQueryListEvent - Web APIs
y A DOMString representing a serialized media query. Methods The MediaQueryListEvent interface inherits methods from its parent interface, Event. ...
... Working Draft Initial definition ...
MediaStreamConstraints.audio - Web APIs
n this example, we provide a simple value of true for the audio property. This tells getUserMedia() that we require an audio track, but we don't care about any specifics beyond that. ...
...stream is returned. ...
MediaStreamConstraints.video - Web APIs
we provide a simple value of true for the video property. This tells getUserMedia() that we require a video track, but we don't care about any specifics beyond that. ...
...ed. ...
MouseEvent.initMouseEvent() - Web APIs
a key was depressed during the Event. Sets the value of MouseEvent.metaKey. button the event's mouse button. relatedTarget the event's related EventTarget. Only used with some event types (e.g., mouseover and mouseout). In other cases, pass null. ...
... Obsolete From Document Object Model (DOM) Level 2 Events Specification, deprecated. ...
Node.localName - Web APIs
Qualified names are typically used in XML as part ...
...Qualified names are typically used in XML as part of the namespace(s) of the particular XML documents. ...
Using the Notifications API - Web APIs
lly try to see if the .then() method is available on requestPermission(). If so, we move on and return true. If it fails, we return false in the catch() {} block. Creating a notification Creating a notification is easy; just use the Notification constructor. This constructor expects a title to display within the notification and some options to enhance the notification such as an icon or a text
body. ...
...the user already read the notification on the webpage, in the case of a messaging app, or the following song is already playing in a music app to notifies upon song changes). ...
PageTransitionEvent - Web APIs
e Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">PageTransitionEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface also inherits properties from its parent, Event. PageTransitionEvent.persisted Read only Indicates if the document is loading from a cache. ...
...onospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">PageTransitionEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface also inherits properties from its parent, Event. PageTransitionEvent.persisted Read only Indicates if the document is loading from a cache. ...
PerformanceResourceTiming - Web APIs
ResourceTiming.responseEndRead only A DOMHighResTimeStamp immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first. PerformanceResourceTiming.transferSizeRead only A number representing the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload
body. ...
...DOMHighResTimeStamp immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first. PerformanceResourceTiming.transferSizeRead only A number representing the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload
body. PerformanceResourceTiming.encoded
BodySizeRead only A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload
body, before removing any applied content-codings. PerformanceResourceTiming.decoded
BodySizeRead only A number that is the size (in octets) received from the fetch (HTTP or cache) of the message
body, after removing any applied content-codings. PerformanceResourceTiming.serverTimi...
RTCDataChannel: message event - Web APIs
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. dc.addEventListener("message", ev => { let newParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.
body.appendChild(newParagraph); }, false); Lines 2-4 create the new paragraph element and add the message data to it as a new text node. Line 6 appends the new paragraph to the end of the document's
body. You can also use an RTCDataChannel object's onmessage event handler property to set the event handler: dc.onmessage = ev => { let newParagraph = document.createElement("p"); let textNode = do...
...nd add the message data to it as a new text node. Line 6 appends the new paragraph to the end of the document's
body. You can also use an RTCDataChannel object's onmessage event handler property to set the event handler: dc.onmessage = ev => { let newParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.
body.appendChild(newParagraph); } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'the <code>message</code> event' in that specification. Candidate Recommendation ...
Range.createContextualFragment() - Web APIs
t by invoking the HTML fragment parsing algorithm or the XML fragment parsing algorithm with the start of the range (the parent of the selected node) as the context node. The HTML fragment parsing algorithm is used if the range belongs to a Document whose HTMLness bit is set. In the HTML case, if the context node would be html, for historical reasons the fragment parsing algorithm is invoked with
body as the context instead. Syntax documentFragment = range.createContextualFragment(tagString) Parameters tagString Text that contains text and tags to be converted to a document fragment. 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.getEleme...
...rs tagString Text that contains text and tags to be converted to a document fragment. Example var tagString = "<div>I am a div node</div>"; var range = document.createRange(); // Make the parent of the first div in the document becomes the context node range.selectNode(document.getElementsByTagName("div").item(0)); var documentFragment = range.createContextualFragment(tagString); document.
body.appendChild(documentFragment); Specification Specification Status Comment DOM Parsing and SerializationThe definition of 'Range.createContextualFragment()' in that specification. Working Draft Initial specification. ...
Range.extractContents() - Web APIs
cted node is extracted and appended to the document. Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid. ...
...div").item(0)); var documentFragment = range.extractContents(); document.
body.appendChild(documentFragment); Moving items between containers This example lets you move items between two containers. Select one or more item, and then click "swap" to move them to the opposite container. ...
ReadableStream - Web APIs
Constructor ReadableStream() Creates and returns a readable stream object from the given handlers. Properties ReadableStream.locked Read only The locked getter returns whether or not the readable stream is locked to a reader. Methods ReadableStream.cancel() Cancels the stream, signaling a loss of interest in the stream by a consumer. ...
...ives the same incoming data. ReadableStream[@@asyncIterator]() Alias of getIterator method. Examples In the following example, an artificial Response is created to stream HTML fragments fetched from another resource to the browser. It demonstrates the usage of a ReadableStream in combination with a Uint8Array. ...
Reporting API - Web APIs
ting a single report. Reporting API dictionaries ReportingObserverOptions Allows options to be set in the constructor when creating a reporting observer. Available report types The spec defines the following report types: Deprecation report Indicates that a WebAPI or other browser feature being used in the website is expected to stop working in a future release. ...
...dictionaries ReportingObserverOptions Allows options to be set in the constructor when creating a reporting observer. Available report types The spec defines the following report types: Deprecation report Indicates that a WebAPI or other browser feature being used in the website is expected to stop working in a future release. Indicated by a Report.
body property with a DeprecationReport
Body return value. Intervention report Indicates that a request made by the website has been denied by the browser, e.g. for security or user annoyance reasons. Indicated by a Report.
body property with a InterventionReport
Body return value. Crash report Indicates that the website stopped running due to a browser crash. Indicated by a Report.
body property with a CrashReport
Body return value. Exam...
Request() - Web APIs
avigate, the mode value is converted to same-origin. init Optional An options object containing any custom settings that you want to apply to the request. The possible options are: method: The request method, e.g., GET, POST. The default is GET. headers: Any headers you want to add to your request, contained within a Headers object or an object literal with ByteString values.
body: Any
body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object. Note that a request using the GET or HEAD method cannot have a
body. mode: The mode you want to use for the request, e.g., cors, no-cors, same-origin, or navigate. The default is cors. credentials: The request credentials you want to use for the req...
... 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. Since we are fetching an image, we run
Body.blob on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an <img> element. 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); myIma...
Request.clone() - Web APIs
Syntax var newRequest = request.clone(); Parameters None. Return value A Request object, which is an exact copy of the Request that clone() was called on. ...
... Syntax var newRequest = request.clone(); Parameters None. Return value A Request object, which is an exact copy of the Request that clone() was called on. ...
Using the Resource Timing API - Web APIs
ces can affect an application's performance so getting accurate data on resource size can be important (especially for non-hosted resources). The PerformanceResourceTiming interface has three properties that can be used to obtain size data about a resource. The transferSize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload
body. The encoded
BodySize property returns the size (in octets) received from the fetch (HTTP or cache), of the payload
body, before removing any applied content-codings. decoded
BodySize returns the size (in octets) received from the fetch (HTTP or cache) of the message
body, after removing any applied content-codings. The following example demonstrates using these three properties. function display...
... list = performance.getEntriesByType("resource"); if (list === undefined) { console.log("= Display Size Data: performance.getEntriesByType() is NOT supported"); return; } // For each "resource", display its *Size property values console.log("= Display Size Data"); for (var i=0; i < list.length; i++) { console.log("== Resource[" + i + "] - " + list[i].name); if ("decoded
BodySize" in list[i]) console.log("... decoded
BodySize[" + i + "] = " + list[i].decoded
BodySize); else console.log("... decoded
BodySize[" + i + "] = NOT supported"); if ("encoded
BodySize" in list[i]) console.log("... encoded
BodySize[" + i + "] = " + list[i].encoded
BodySize); else console.log("... encoded
BodySize[" + i + "] = NOT supported"); if ("transferSize"...
Response() - Web APIs
This can be null (which is the default value), or one of: Blob BufferSource FormData ReadableStream URLSearchParams USVString init Optional An options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). The possible options are: status: The status code for the reponse, e.g., 200. statusText: The status message associated with the status code, e.g., OK. ...
...tusText: The status message associated with the status code, e.g., OK. headers: Any headers you want to add to your response, contained within a Headers object or object literal of ByteString key/value pairs (see HTTP headers for a reference). 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 Comment FetchThe definition of 'Response()' in that specification. Living Standard Initial definition ...
Response.clone() - Web APIs
The clone() method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. clone() throws a TypeError if the response
Body has already been used. In fact, the main reason clone() exists is to allow multiple uses of
Body objects (when they are one-use only.) Syntax var response2 = response1.clone(); Parameters None. Value A Response object. 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. ...
...only.) Syntax var response2 = response1.clone(); Parameters None. Value A Response object. 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. We then fetch this request using fetch(). When the fetch resolves successfully, we clone it, extract a blob from both responses using two
Body.blob calls, create object URLs out of the blobs using URL.createObjectURL, and display them in two separate <img> elements. var image1 = document.querySelector('.img1'); var image2 = document.querySelector('.img2'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { var response2 = response.clone(); response.blob().then(function(myBlob) { var object...
Response.type - Web APIs
The type read-only property of the Response interface contains the type of the response. It can be one of the following: basic: Normal, same origin response, with all headers exposed except "Set-Cookie" and "Set-Cookie2?. cors: Response was received from a valid cross-origin request. Certain headers and the
body may be accessed. error: Network error. No useful information describing the error is available. The Response's status is 0, headers are empty and immutable. This is the type for a Response obtained from Response.error(). opaque: Response for "no-cors" request to cross-origin resource. Severely restricted. opaqueredirect: The fetch request was made with redirect: "manual". The Response's status is 0, headers are empty,
body is null and trailer is empty. Note: An "error" Respo...
...ript: such a response to a fetch() would reject the promise. Syntax var myType = response.type; Value A ResponseType string indicating the type of the response. 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. We then fetch this request using fetch(), extract a blob from the response using
Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response type to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.type); // returns basic by default response.blob().then(funct...
ServiceWorkerRegistration.showNotification() - Web APIs
lt using event.action within the notificationclick event. 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. On Android devices, the badge should accommodate devices up to 4x resolution, about 96 by 96 px, and the image will be automatically masked.
body: A string representing an extra content to display within the notification. data: Arbitrary data that you want to be associated with the notification. This can be of any data type. dir : The direction of the notification; it can be auto, ltr or rtl icon: a USVString containing the URL of an image to be used as an icon by the notification. image: a USVString containing the URL of an image...
...ms, pause 100ms, then vibrate 400ms. Return value A Promise that resolves to undefined. 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! Buzz!', icon: '../images/touch/chrome-touch-icon-192x192.png', vibrate: [200, 100, 200, 100, 200, 100, 200], tag: 'vibration-sample' }); }); } }); } To invoke the above function at an appropriate time, you could use the ServiceWorkerGlobalScope.onnotificationclick event handler. You can also retrieve details of the Notifications that hav...
Streams API concepts - Web APIs
l use depends on how the stream was created in the first place (see the ReadableStream() constructor page). Important: Byte streams are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. This may change over time. You can make use of ready-made readable streams via mechanisms like a Response.
body from a fetch request, or roll your own streams using the ReadableStream() constructor. Teeing Even though only a single reader can read a stream at once, it is possible to split a stream into two identical copies, which can then be read by two separate readers. This is called teeing. In JavaScript, this is achieved via the ReadableStream.tee() method -- it outputs an array containing two ident...
...ipt, this is achieved via the ReadableStream.tee() method -- it outputs an array containing two identical copies of the original readable stream, which can then be read independently by two separate readers. 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. Since a response
body cannot be consumed more than once, and a stream can't be read by more than one reader at once, you'd need two copies to do this. Writable streams A writable stream is a destination into which you can write data, represented in JavaScript by a WritableStream object. This serves as an abstraction over the top of an underlying sink -- a lower-level I/O sink into which raw data is written. The d...
Streams API - Web APIs
t is available on the client-side, without needing to generate a buffer, string, or blob. There are more advantages too -- you can detect when streams start or end, chain streams together, handle errors and cancel streams as required, and react to the speed of the stream is being read at. The basic usage of Streams hinges around making responses available as streams. 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. You can also write data to streams using Writabl...
... Related stream APIs and operations ByteLengthQueuingStrategy Provides a built-in byte length queuing strategy that can be used when constructing streams. CountQueuingStrategy Provides a built-in chunk counting queuing strategy that can be used when constructing streams. Extensions to other APIs Request When a new Request object is constructed, you can pass it a ReadableStream in the
body property of its RequestInit dictionary. This Request could then be passed to a WindowOrWorkerGlobalScope.fetch() to commence fetching the stream.
Body The response
Body returned by a successful fetch request is exposed by default as a ReadableStream, and can have a reader attached to it, etc. ByteStream-related interfaces Important: these are not implemented anywhere as yet, and questions ...
SubtleCrypto.digest() - Web APIs
SHA-512 This algorithm is specified in FIPS 180-4, section 6.4, and produces an output 512 bits long. Hint: If you are looking here for how to create an keyed-hash message authentication code (HMAC), you need to use the SubtleCrypto.sign() instead. 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. The inhabitants refer to it as the planet Earth.'; async function digestMessage(message) { const encoder = new TextEncoder(); const data = encoder.encode(message); const hash = await crypto.subtle.digest('SHA-256', data); return hash; } const digestBuffer = await digestMessage(text); console.log(digestBuffer.byteLength); Converting a digest to a hex st...
...ubtle.digest('SHA-256', data); return hash; } const digestBuffer = await digestMessage(text); console.log(digestBuffer.byteLength); Converting a digest to a hex string The digest is returned as an ArrayBuffer, but for comparison and display digests are often represented as hex strings. 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. The inhabitants refer to it as the planet Earth.'; async function digestMessage(message) { const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8); // hash the message const hashArray = Array.from(new Uint8Array(hashBuffer)); ...
UIEvent.layerX - Web APIs
form.layerYCoords.value = evt.layerY; } </script> <style type="text/css"> #d1 { border: solid blue 1px; padding: 20px; } #d2 { position: absolute; top: 180px; left: 80%; right:auto; width: 40%; border: solid blue 1px; padding: 20px; } #d3 { position: absolute; top: 240px; left: 20%; width: 50%; border: solid blue 1px; padding: 10px; } </style> </head> <
body onmousedown="showCoords(event)"> <p>To display the mouse coordinates please click anywhere on the page.</p> <div id="d1"> <span>This is an un-positioned div so clicking it will return layerX/layerY values almost the same as pageX/PageY values.</span> </div> <div id="d2"> <span>This is a positioned div so clicking it will return layerX/layerY values that are relative to the top-left corner of ...
... Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox...
UIEvent.layerY - Web APIs
form.layerYCoords.value = evt.layerY; } </script> <style type="text/css"> #d1 { border: solid blue 1px; padding: 20px; } #d2 { position: absolute; top: 180px; left: 80%; right:auto; width: 40%; border: solid blue 1px; padding: 20px; } #d3 { position: absolute; top: 240px; left: 20%; width: 50%; border: solid blue 1px; padding: 10px; } </style> </head> <
body onmousedown="showCoords(event)"> <p>To display the mouse coordinates please click anywhere on the page.</p> <div id="d1"> <span>This is an un-positioned div so clicking it will return layerX/layerY values almost the same as pageX/PageY values.</span> </div> <div id="d2"> <span>This is a positioned div so clicking it will return layerX/layerY values that are relative to the top-left corner of ...
... ...
UIEvent.pageY - Web APIs
form.layerYCoords.value = evt.layerY; } </script> <style type="text/css"> #d1 { border: solid blue 1px; padding: 20px; } #d2 { position: absolute; top: 180px; left: 80%; right:auto; width: 40%; border: solid blue 1px; padding: 20px; } #d3 { position: absolute; top: 240px; left: 20%; width: 50%; border: solid blue 1px; padding: 10px; } </style> </head> <
body onmousedown="showCoords(event)"> <p>To display the mouse coordinates please click anywhere on the page.</p> <div id="d1"> <span>This is an un-positioned div so clicking it will return layerX/layerY values almost the same as pageX/PageY values.</span> </div> <div id="d2"> <span>This is a positioned div so clicking it will return layerX/layerY values that are relative to the top-left corner of t...
... ...
Boilerplate 1 - Web APIs
TML, CSS, and JavaScript repeated again and again. So we are going to hide them from now on. This would allow us to focus on the interesting pieces of code that are most relevant for learning WebGL. Specifically, the HTML has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>. The CSS contains rules for
body, canvas, and button. 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. By now, you should be able to understand what the function does. Basically, it gets the WebGL rendering context from the canvas element, initializes the ...
...r message and returns null. Finally, all JavaScript code will run within an immediate function, which is a common JavaScript technique (see Function). The function declaration and invocation will also be hidden. HTML <p>[ Some descriptive text about the example. ]</p> <button>[ Optional button element. ...
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
s, software needs the ability to not only track the locations, orientation, and movements of objects in the virtual world, but the user's location, orientation, and movement as well. But WebXR goes beyond that by adding the ability to track the location, orientation, and motion of the input devices which generate data used to determine the position and movement of individual parts of the viewer's
body (with appropriate equipment). The location and movement of the user's headset represent their head's position and orientation in the virtual environment. Hand controllers represent their hands in the same manner. Other hardware elements can be used similarly to represent other parts of the
body, providing additional data to use when simulating the user's actions in their environment. In this gu...
...trollers represent their hands in the same manner. Other hardware elements can be used similarly to represent other parts of the
body, providing additional data to use when simulating the user's actions in their environment. In this guide, we'll explore how WebXR uses spaces and, more specifically, reference spaces, to track the positions, orientations, and movements of objects and of the user's
body in the virtual world. Note: This article presumes that you are familiar with the concepts introduced in Geometry and reference spaces in WebXR: that is, the basics of 3D coordinate systems, as well as WebXR spaces, reference spaces, and how reference spaces are used to create local coordinate systems for individual objects or movable components within a scene. Representing a position using a ...
window.location - Web APIs
Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna ...
...istique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. ...
Window.pageYOffset - Web APIs
er ipsum fermentum eu. Aenean mollis dignissim ultrices. Nunc gravida, sem sit amet lobortis iaculis, dolor ligula convallis nibh, id condimentum metus libero nec odio. Quisque nec ante pretium, viverra neque nec, facilisis risus. Duis condimentum sapien non felis cursus blandit. 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. Once that's done, the vertical scroll position is checked by looking at the value of pageYOffset in the frame's contentWindow. HTML The HTML is extremely simple and has just two elements: an <iframe> that contains the docume...
...the frame's scrollingElement to the offsetTop of the target element. By doing so, we set the vertical scrolling position of the frame's document so that it's the same as the top edge of the target element. This will automatically set the scrolling position to the maximum possible value if the attempted scroll would exceed the maximum. This prevents us from falling off the edge of the document. No
body wants to know what's out there. There might be dragons. CSS iframe { width: 620px; height: 450px; border: 1px solid black; } #info { margin-top: 20px; font: 16px "Open Sans", "Helvetica", "Arial"; } Result The result follows. Note that the frame's contents have been scrolled to show the section named "Overview", and that the value of the pageYOffset property is shown with the cor...
WindowOrWorkerGlobalScope.fetch() - Web APIs
possible options are: method The request method, e.g., GET, POST. Note that the Origin header is not set on Fetch requests with a method of HEAD or GET. (This behavior was corrected in Firefox 65 -- see bug 1508661). headers Any headers you want to add to your request, contained within a Headers object or an object literal with ByteString values. Note that some names are forbidden.
body Any
body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object. Note that a request using the GET or HEAD method cannot have a
body. mode The mode you want to use for the request, e.g., cors, no-cors, or same-origin. credentials The request credentials you want to use for the request: omit, same-origin, or ...
... to a call to the AbortController method abort() method. TypeError The specified URL string includes user credentials. This information should instead be provided using an Authorization header. Examples In our Fetch Request example (see Fetch Request live) we create a new Request object using the relevant constructor, then fetch it using a fetch() call. Since we are fetching an image, we run
Body.blob() on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an <img> element. const myImage = document.querySelector('img'); let myRequest = new Request('flowers.jpg'); fetch(myRequest) .then(function(response) { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response...
Sending and Receiving Binary Data - Web APIs
Receiving binary data using JavaScript typed arrays The responseType property of the XMLHttpRequest object can be set to change the expected response type from the server. Possible values are the empty string (default), "arraybuffer", "blob", "document", "json", and "text". The response property will contain the entity
body according to responseType, as an ArrayBuffer, Blob, Document, JSON, or string. This is null if the request is not complete or was not successful. This example reads an image as a binary file and creates an 8-bit unsigned integer array from the raw bytes. Note that this will not decode the image and read the pixels. You will need a png decoding library for that. var oReq = new XMLHttpRequest(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "arraybuffe...
...' support here. Submitting forms and uploading files Please, read this paragraph. Firefox-specific examples This example transmits binary content asynchronously, using the POST method, and Firefox's non-standard sendAsBinary(). var req = new XMLHttpRequest(); req.open("POST", url, true); // set headers and mime-type appropriately req.setRequestHeader("Content-Length", 741); req.sendAsBinary(a
Body); Line 4 sets the Content-Length header to 741, indicating that the data is 741 bytes long. Obviously you need to change this value based on the actual size of the data being sent. Line 5 uses the sendAsBinary() method to initiate the request. Note: This non-standard sendAsBinary method is considered deprecated as of Gecko 31 (Firefox 31 / Thunderbird 31 / SeaMonkey 2.28) and will be removed...
XMLHttpRequest.response - Web APIs
You may attempt to request the data be provided in a specific format by setting the value of responseType after calling open() to initialize the request but before calling send() to send the request to the server. ...
...You may attempt to request the data be provided in a specific format by setting the value of responseType after calling open() to initialize the request but before calling send() to send the request to the server. ...
XMLHttpRequest.send() - Web APIs
The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived. send() accepts an optional parameter which lets you specify the request's
body; this is primarily used for requests such as PUT. If the request method is GET or HEAD, the
body parameter is ignored and the request
body is set to null. If no Accept header has been set using the setRequestHeader(), an Accept header with the type "*/*" (any type) is sent. Syntax XMLHttpRequest.send(
body) Parameters
body Optional A
body of data to be sent in the XHR request. This can be: A Document, in...
..., the
body parameter is ignored and the request
body is set to null. If no Accept header has been set using the setRequestHeader(), an Accept header with the type "*/*" (any type) is sent. Syntax XMLHttpRequest.send(
body) Parameters
body Optional A
body of data to be sent in the XHR request. This can be: A Document, in which case it is serialized before being sent. An XMLHttpRequest
BodyInit, which per the Fetch spec can be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. null If no value is specified for the
body, a default value of null is used. The best way to send binary content (e.g. in file uploads) is by using an ArrayBufferView or Blob in conjunction with the send() method. Return value undefined. Exceptions Exception Descriptio...
XMLSerializer - Web APIs
s = new XMLSerializer(); var d = document; var str = s.serializeToString(d); saveXML(str); This involves creating a new XMLSerializer object, then passing the Document to be serialized into serializeToString(), which returns the XML equivalent of the document. 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. Note: In the real world, you should usually instead call importNode() method to import the new node into the DOM, then call one of the following methods to add the node to the DOM tree: The Document and Element methods append() and prepend() The Node.replaceWith() method (to replace an existing node with the new one) T...
....insertAdjacentElement() methods. Because insertAdjacentHTML() accepts a string and not a Node as its second parameter, XMLSerializer is used to first convert the node into a string. var inp = document.createElement('input'); var XMLS = new XMLSerializer(); var inp_xmls = XMLS.serializeToString(inp); // First convert DOM node into a string // Insert the newly created node into the document's
body document.
body.insertAdjacentHTML('afterbegin', inp_xmls); The code creates a new <input> element by calling Document.createElement(), then serializes it into XML using serializeToString(). Once that's done, insertAdjacentHTML() is used to insert the <input> element into the DOM. Specifications Specification Status Comment DOM Parsing and SerializationThe definition of ...
Using the alert role - Accessibility
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. ...
..."role", "alert"); let myAlertText = document.createTextNode("You must agree with our terms of service to create an account."); myAlert.appendChild(myAlertText); document.
body.appendChild(myAlert); Note: The same result can be achieved with less code when using a script library like jQuery: $("<p role='alert'>You must agree with our terms of service to create an account.</p>").appendTo(document.
body); Example 3: Adding alert role to an existing element Sometimes it's useful to add an alert role to an element that is already visible on the page rather than creating a new element. This allows the developer to reiterate information that has become more relevant or urgent to the user. For example, a form control may have instruction about the expected value. If a different value is entered, r...
Alerts - Accessibility
the error, but allows for them continue modifying the form without losing focus (caused by the "onblur" handler in JavaScript's default 'alert' function). ...
...Alert() { var oldAlert = document.getElementById("alert"); if (oldAlert){ document.
body.removeChild(oldAlert); } } function addAlert(aMsg) { removeOldAlert(); var newAlert = document.createElement("div"); newAlert.setAttribute("role", "alert"); newAlert.setAttribute("id", "alert"); var msg = document.createTextNode(aMsg); newAlert.appendChild(msg); document.
body.appendChild(newAlert); } function checkValidity(aID, aSearchTerm, aMsg) { var elem = document.getElementById(aID); var invalid = (elem.value.indexOf(aSearchTerm) < 0); if (invalid) { elem.setAttribute("aria-invalid", "true"); addAlert(aMsg); } else { elem.setAttribute("aria-invalid", "false"); removeOldAlert(); } } </script> The checkValidity function T...
:checked - CSS: Cascading Style Sheets
{ 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. ...
...more text]</td><td>[more text]</td><td>[more text]</td></tr> <tr><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></tr> <tr><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></tr> <tr class="expandable"><td>[more text]</td><td>[more text]</td><td>[more text]</td></tr> <tr class="expandable"><td>[more text]</td><td>[more text]</td><td>[more text]</td></tr> </t
body> </table> <label for="expand-toggle" id="expand-btn">Toggle hidden rows</label> CSS /* Hide the toggle checkbox */ #expand-toggle { display: none; } /* Hide expandable content by default */ .expandable { visibility: collapse; background: #ddd; } /* Style the button */ #expand-btn { display: inline-block; margin-top: 12px; padding: 5px 11px; background-color: #ff7; border: 1p...
:nth-last-child() - CSS: Cascading Style Sheets
g a group of siblings. This is the same as a simple p selector. (Since n starts at zero, while the last element begins at one, n and n+1 will both select the same elements.) p:nth-last-child(1) or p:nth-last-child(0n+1) Represents every <p> that is the first element among a group of siblings, counting from the end. This is the same as the :last-child selector. ...
... <p> that is the first element among a group of siblings, counting from the end. This is the same as the :last-child selector. ...
@document - CSS: Cascading Style Sheets
. Note: There is a -moz-prefixed version of this property -- @-moz-document. This has been limited to use only in user and UA sheets in Firefox 59 in Nightly and Beta -- an experiment designed to mitigate potential CSS injection attacks (See bug 1035091). ...
... ...
@font-face - CSS: Cascading Style Sheets
[ font-feature-settings: <font-feature-settings>; ] | [ font-variation-settings: <font-variation-settings>; ] | [ font-stretch: <font-stretch>; ] | [ font-weight: <font-weight>; ] | [ font-style: <font-style>; ] }where <family-name> = <string> | <custom-ident>+ Examples Specifying a downloadable font This example simply specifies a downloadable font to use, applying it to the entire
body of the document: View the live example <html> <head> <title>Web Font Sample</title> <style type="text/css" media="screen, print"> @font-face { font-family: "Bitstream Vera Serif Bold"; src: url("https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf"); }
body { font-family: "Bitstream Vera Serif Bold", serif } </style> </head> <
body> This is Bitstream Vera Serif B...
... document: View the live example <html> <head> <title>Web Font Sample</title> <style type="text/css" media="screen, print"> @font-face { font-family: "Bitstream Vera Serif Bold"; src: url("https://mdn.mozillademos.org/files/2468/VeraSeBd.ttf"); }
body { font-family: "Bitstream Vera Serif Bold", serif } </style> </head> <
body> This is Bitstream Vera Serif Bold. ...
@supports - CSS: Cascading Style Sheets
le: preserve-3d) or ((-moz-transform-style: preserve-3d) or ((-o-transform-style: preserve-3d) or (-webkit-transform-style: preserve-3d))) {} Note: When using both and and or operators, the parentheses must be used to define the order in which they apply. Otherwise, the condition is invalid and the whole rule is ignored. ...
... or (-o-perspective: 10px)) { ... /* CSS applied when 3D transforms, prefixed or not, are supported */ } Testing for the non-support of a specific CSS property @supports not ((text-align-last: justify) or (-moz-text-align-last: justify)) { ... /* CSS to provide fallback alternative for text-align-last: justify */ } Testing for the support of custom properties @supports (--foo: green) {
body { color: var(--varName); } } Testing for the support of a selector (eg. :is()) /* This rule won't be applied in browsers which don't support :is() */ :is(ul, ol) > li { ... /* CSS applied when the :is(...) selector is supported */ } @supports not selector(:is(a, b)) { /* Fallback for when :is() is unsupported */ ul > li, ol > li { ... /* The above expanded for browsers whi...
Border-radius generator - CSS: Cascading Style Sheets
; } .ui-checkbox .text { padding-left: 34px; background-position: center left 10px; } .ui-checkbox .left { padding-right: 34px; padding-left: 1.666em; background-position: center right 10px; } .ui-checkbox > label:hover { cursor: pointer; } .ui-checkbox > input:checked + label { background-image: url("https://mdn.mozillademos.org/files/5681/checked.png"); background-color: #379B4A; }
body { max-width: 1000px; margin: 0 auto; font-family: "Segoe UI", Arial, Helvetica, sans-serif; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; } #container { width: 100%; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-bo...
...; return input; } var SliderComponent = function SliderComponent(obj, sign) { var slider = document.createElement('div'); var startX = null; var start_value = 0; slider.addEventListener("click", function(e) { setValue(obj.topic, obj.value + obj.step * sign); }); slider.addEventListener("mousedown", function(e) { startX = e.clientX; start_value = obj.value; document.
body.style.cursor = "e-resize"; document.addEventListener("mousemove", sliderMotion); }); document.addEventListener("mouseup", function(e) { document.removeEventListener("mousemove", sliderMotion); document.
body.style.cursor = "auto"; slider.style.cursor = "pointer"; }); var sliderMotion = function sliderMotion(e) { slider.style.cursor = "e-resize"; var delta = (e.clientX -...
Variable fonts guide - CSS: Cascading Style Sheets
ific width/weight/style combination. So you would have separate files for 'Roboto Regular', 'Roboto Bold', and 'Roboto Bold Italic' -- meaning that you could end up with 20 or 30 different font files to represent a complete typeface (it could be several times that for a large typeface that has different widths as well). In such a scenario, in order to use a typeface for typical use on a site for
body copy you would need at least four files: regular, italic, bold, and bold italic. If you wanted to add more weights, like a lighter one for captions or a heavier one for extra emphasis, that would mean several more files. This results in more HTTP requests, and more data being downloaded (usually around 20k or more per file). Variable fonts With a variable font, all of those permutations can be ...
... a heavier one for extra emphasis, that would mean several more files. This results in more HTTP requests, and more data being downloaded (usually around 20k or more per file). Variable fonts With a variable font, all of those permutations can be contained in a single file. That file would be larger than a single font, but in most cases smaller or about the same size as the 4 you might load for
body copy. The advantage in choosing the variable font is that you have access to the entire range of weights, widths, and styles available, rather than being constrained to only the few that you previously would have loaded separately. This allows for common typographic techniques such as setting different size headings in different weights for better readability at each size, or using a slightly na...
Consistent list indentation - CSS: Cascading Style Sheets
ent as-is, there would be no apparent indentation and the markers would be in danger of falling off the left edge of the browser window. In order to avoid this and get some indentation, there are really only three options available to browser implementors. Give each <li> element a left margin. Give the <ul> element a left margin. Give the <ul> element some left padding. As it turns out, no
body seems to have used the first option. The second option was taken by Internet Explorer for Windows and Macintosh, and Opera. The third was adopted by Gecko, and by extension all the browsers that embed it. Let's look at the two approaches for a moment. In Internet Explorer and Opera, the lists are indented by setting a left margin of 40 pixels on the <ul> element. If we apply a background color t...
...referred values. Set both to 1.25em, if you like -- there's no reason why you have to stick with pixel-based indentation. If you want to reset lists to have no indentation, then you still have to zero out both padding and margin: ul {margin-left: 0; padding-left: 0;} Remember, though, that in so doing, you'll have the bullets hanging outside the list and its parent element. If the parent is the
body, there's a strong chance your bullets will be completely outside the browser window, and thus will not be visible. Conclusion In the end, we can see that none of the browsers mentioned in this article is right or wrong about how they lay out lists. They use different default styles, and that's where the problems creep in. By making sure you style both the left padding and left margin of lists, ...
Using CSS counters - CSS: Cascading Style Sheets
, string)' or 'counters(name, string, style)'. The generated text is the value of all counters with the given name in scope at the given pseudo-element, from outermost to innermost, separated by the specified string. The counters are rendered in the specified style (decimal by default). Basic example This example adds "Section [the value of the counter]:" to the beginning of each heading. CSS
body { counter-reset: section; /* Set a counter named 'section', and its initial value is 0. */ } h3::before { counter-increment: section; /* Increment the value of section counter by 1 */ content: "Section " counter(section) ": "; /* Display the word 'Section ', the value of section counter, and a col...
...Using the counters() function, separating text can be inserted between different levels of nested counters. Example of a nested counter CSS ol { counter-reset: section; /* Creat...
Stacking context example 2 - CSS: Cascading Style Sheets
absolute; width: 150px; height: 200px; top: 20px; left: 170px; border: 1px dashed #990000; background-color: #ffdddd; text-align: center; } #div4 { opacity: 0.8; position: absolute; width: 200px; height: 70px; top: 65px; left: 50px; border: 1px dashed #000099; background-color: #ddddff; text-align: left; padding-left: 10px; } </style></head> <
body> <br /> <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: 2; </div> </div> <br /> <div id="div3"><br /> <span class="bold">DIV #3</span><br /> position: relative;<b...
... position: absolute;<br /> z-index: 2; </div> </div> <br /> <div id="div3"><br /> <span class="bold">DIV #3</span><br /> position: relative;<br /> z-index: 1; <div id="div4"><br /> <span class="bold">DIV #4</span><br /> position: absolute;<br /> z-index: 10; </div> </div> </
body> </html> ...
Stacking context example 3 - CSS: Cascading Style Sheets
width: 200px; height: 60px; position: relative; border: 2px outset #990000; background-color: #ffdddd; padding-left: 5px; } #container2 { z-index: 1; position: absolute; top: 20px; left: 110px; } div.lev3 { z-index: 10; width: 100px; position: relative; border: 2px outset #000099; background-color: #ddddff; padding-left: 5px; } </style></head> <
body> <br /> <div class="lev1"> <span class="bold">LEVEL #1</span> <div id="container1"> <div class="lev2"> <br /><span class="bold">LEVEL #2</span> <br />z-index: 1; <div id="container2"> <div class="lev3"><span class="bold">LEVEL #3</span></div> <div class="lev3"><span class="bold">LEVEL #3</span></div> <div class="lev3"><span c...
...ass="lev3"><span class="bold">LEVEL #3</span></div> </div> </div> <div class="lev2"> <br /><span class="bold">LEVEL #2</span> <br />z-index: 1; </div> </div> </div> <div class="lev1"> <span class="bold">LEVEL #1</span> </div> <div class="lev1"> <span class="bold">LEVEL #1</span> </div> <div class="lev1"> <span class="bold">LEVEL #1</span> </div> </
body></html> ...
Using CSS transforms - CSS: Cascading Style Sheets
ther from the viewer the elements are, the smaller they are. Setting perspective This example shows a cube with the perspective set at different positions. How quick the cube shrinks is defined by the perspective property. The smaller its value is, the deeper the perspective is. HTML The HTML below creates four copies of the same box, with the perspective set at different values. ...
...It also includes classes for the container box and the cube itself, as well as each of its faces. /* Shorthand classes for different perspective values */ .pers250 { perspective: 250px; } .pers350 { perspective: 350px; } .pers500 { perspective: 500px; } .pers650 { perspective: ...
Specificity - CSS: Cascading Style Sheets
{ color: purple; } ... when used with this markup ... <p id="foo">I am a sample text.</p> ... end up looking like this: This is because it matches the same element but the ID selector has a higher specificity. Tree proximity ignorance The proximity of an element to other elements that are referenced in a given selector has no impact on specificity. The following style declaration ...
body h1 { color: green; } html h1 { color: purple; } ... with the following HTML ... <html> <
body> <h1>Here is a title!</h1> </
body> </html> ... will render as: This is because the two declarations have equal selector type counts, but the html h1 selector is declared last. Directly targeted elements vs. inherited styles Styles for a directly targeted element will always take pre...
...he two declarations have equal selector type counts, but the html h1 selector is declared last. Directly targeted elements vs. inherited styles Styles for a directly targeted element will always take precedence over inherited styles, regardless of the specificity of the inherited rule. This CSS ... #parent { color: green; } h1 { color: purple; } ... with the following HTML ... <html> <
body id="parent"> <h1>Here is a title!</h1> </
body> </html> ... will also render as: This is because the h1 selector targets the element specifically, but the green selector is only inherited from its parent. Specifications Specification Status Comment Selectors Level 4The definition of 'Calculating a selector's specificity' in that specification. Working Dr...
backdrop-filter - CSS: Cascading Style Sheets
>, <percentage>, <alpha-value>? ...
...lpha-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), linear-gradient(rgb(219, 166, 166), rgb(0, 0, 172)); background-position: center center; background-repeat: no-repeat; background-size: cover; } .container { align-items: center; display: flex; justify-content: center; height: 100%; width: 100%; } HTML <div class="container"> <div class="box"> <p>backdrop...
box-align - CSS: Cascading Style Sheets
Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check...
... Browser compatibility The compatibility table on this page is generated from structured data. ...
clamp() - CSS: Cascading Style Sheets
<calc-sum>#{3} )where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> ) Examples min, max, and clamp comparison In this example we have a simple responsive example that makes use of min(), max(), and clamp() for some of the sizes. The <
body> element's width is set as min(1000px, calc(70% + 100px)). This means that the width will be set at 1000px, unless the result of calc(70% + 100px) is less than 1000px, in which case it will be set to that value instead. min() allows you set a maximum value. The <p> element's font-size is set as max(1.2rem, 1.2vw). This means that the font-size will be set at 1.2rem, unless the computed value of ...
...quis cursus nulla scelerisque nec. Nunc eu facilisis lorem. Maecenas faucibus sapien eleifend, semper tellus at, pharetra quam. Cras feugiat vulputate tortor at rhoncus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam non felis quis sem lobortis sodales vel id libero. Phasellus sit amet placerat lorem. </p> CSS html { font-family: sans-serif; }
body { margin: 0 auto; width: min(1000px, calc(70% + 100px)); } h1 { letter-spacing: 2px; font-size: clamp(1.8rem, 2.5vw, 2.8rem); } p { line-height: 1.5; font-size: max(1.2rem, 1.2vw); } Specifications Specification Status Comment CSS Values and Units Module Level 4The definition of 'clamp()' in that specification. Editor's Draft Initial definition. ...
font-size - CSS: Cascading Style Sheets
is generally best to use values that are relative to the user's default font size. Description There are several ways to specify the font size, including with keywords or numerical values for pixels or ems. Choose the appropriate method based on the needs for the particular web page. Keywords Keywords are a good way to set the size of fonts on the web. By setting a keyword font size on the <
body> element, you can set relative font-sizing everywhere else on the page, giving you the ability to easily scale the font up or down on the entire page accordingly. Pixels Setting the font size in pixel values (px) is a good choice when you need pixel accuracy. A px value is static. This is an OS-independent and cross-browser way of literally telling the browsers to render the letters at exactly ...
...n. Ems Another way of setting the font size is with em values. The size of an em value is dynamic. When defining the font-size property, an em is equal to the font size of the element on which the em is used. If you haven't set the font size anywhere on the page, then it is the browser default, which is often 16px. So, by default 1em = 16px, and 2em = 32px. If you set a font-size of 20px on the
body element, then 1em = 20px and 2em = 40px. Note that the value 2 is essentially a multiplier of the current em size. In order to calculate the em equivalent for any pixel value required, you can use this formula: em = desired element pixel value / parent element font-size in pixels For example, suppose the font-size of the
body of the page is set to 16px. If the font-size you want is 12px, then ...
font-variant-east-asian - CSS: Cascading Style Sheets
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. ...
...n your OS, other fonts may not support OpenType features. ...
font - CSS: Cascading Style Sheets
t_line_height"> <br/> line-height <br/> optional </div> <div class="propInputCont"> <input type="text" class="curCss mandatory" id="input_font_family"> <br/> font-family <br/> mandatory </div> </div> </form> <div class="fontShortHand"> This is some sample text. ...
...o.length; i++) { if(oRadio[i].checked) { var propInput = "input_" + radio_name, curElemName = "input_" + radio_name, curElem = document.getElementById(curElemName); curElem.value = oRadio[i].value; return oRadio[i].value; } } } setCss = function () { getProperties(); injectCss(shortText); } injectCss = function(cssFragment) { old = document.
body.getElementsByTagName("style"); if (old.length > 1) { old[1].parentElement.removeChild(old[1]); } css = document.createElement("style"); css.innerHTML = ".fontShortHand{font: " + cssFragment + "}"; document.
body.appendChild(css); } setCss(); Specifications Specification Status Comment CSS Fonts Module Level 3The definition of 'font' in that specifica...
perspective - CSS: Cascading Style Sheets
tacking contextyes Formal syntax none | <length> Examples Setting perspective This example shows a cube with the perspective set at different positions. How quick the cube shrinks is defined by the perspective property. The smaller its value is, the deeper the perspective is. HTML The HTML below creates four copies of the same box, with the perspective set at different values. ...
...It also includes classes for the container box and the cube itself, as well as each of its faces. /* Shorthand classes for different perspective values */ .pers250 { perspective: 250px; } .pers350 { perspective: 350px; } .pers500 { perspective: 500px; } .pers650 { perspective: ...
Getting Started - Developer guides
page. This is repeated every 5 seconds, using a setInterval() call. The idea would be that a server-side script of some kind would continually update the text file with new timestamps, and our XHR code would be used to report the latest timestamp on the client-side. ...
... updateDisplay(text) { fullData.textContent = text; let timeArray = text.split('\n'); // included because some file systems always include a blank line at the end of text files. if(timeArray[timeArray.length-1] === '') { timeArray.pop(); } lastData.textContent = timeArray[timeArray.length-1]; } setInterval(fetchData, 5000); </script> </
body> </html> ...
DOM onevent handlers - Developer guides
to be notified of DOM events. Two common approaches are addEventListener() and the specific onevent handlers. This page focuses on how the latter work. Registering onevent handlers The onevent handlers are properties on certain DOM elements to manage how that element reacts to events. Elements can be interactive (links, buttons, images, forms, and so forth) or non-interactive (such as the base <
body> element). Events are actions like: Being clicked Detecting pressed keys Getting focus The onevent handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc. You can specify an on<...> event handler for a particular event (such as click) for a given object in different ways: Adding an HTML attribute named on<eventtype>: <button onclick="handleClick(...
...(The HTML specification names these: onblur, onerror, onfocus, onload, and onscroll.) Event handler's parameters, this binding, and the return value When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters: event -- for all event hand...
XHTML - Developer guides
erm that was historically used to describe HTML documents written to conform with XML syntax rules. The following example shows an HTML document and corresponding "XHTML" document, and the accompanying HTTP Content-Type headers they should be served with. ...
... HTML documents written to conform with XML syntax rules. The following example shows an HTML document and corresponding "XHTML" document, and the accompanying HTTP Content-Type headers they should be served with. HTML document Content-Type: text/html <!DOCTYPE html> <html lang=en> <head> <meta charset=utf-8> <title>HTML</title> </head> <
body> <p>I am a HTML document</p> </
body> </html> XHTML document Content-Type: application/xhtml+xml <?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>XHTML</title> </head> <
body> <p>I am a XHTML document</p> </
body> </html> In practice, very few "XHTML" documents are served over the web with a Content-Type: application/xhtml+xml header. Instead, even tho...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
ation: table { border: 1px solid black; font: 16px "Open Sans", Helvetica, Arial, sans-serif; border-spacing: 0; border-collapse: collapse; } th, td { border: 1px solid black; padding:4px 6px; text-align: left; } th { background-color: hsl(0, 0%, 75%); } <table> <thead> <tr> <th scope="col">Color in HSL notation</th> <th scope="col">Example</th> </tr> </thead> <t
body> <tr> <td><code>hsl(90deg, 100%, 50%)</code></td> <td style="background-color: hsl(90deg, 100%, 50%);"> </td> </tr> <tr> <td><code>hsl(90, 100%, 50%)</code></td> <td style="background-color: hsl(90, 100%, 50%);"> </td> </tr> <tr> <td><code>hsl(0.15turn, 50%, 75%)</code></td> <td style="background-color: hsl(0.15turn, 50%, 75%);"> </td> </tr> <tr> ...
... Using color Now that you know what CSS properties exist that let you apply color to elements and the formats you can use to describe colors, you can put this together to begin to make use of color. As you may have seen from the list under Things that can have color, there are plenty of things you can c...
HTML attribute reference - HTML: Hypertext Markup Language
rver accepts, typically a file type. accept-charset <form> List of supported charsets. accesskey Global attribute Keyboard shortcut to activate or add focus to the element. action <form> The URI of a program that processes the information submitted via the form. align <applet>, <caption>, <col>, <colgroup>, <hr>, <iframe>, <img>, <table>, <t
body>, <td>, <tfoot> , <th>, <thead>, <tr> Specifies the horizontal alignment of the element. allow <iframe> Specifies a feature-policy for the iframe. alt <applet>, <area>, <img>, <input> Alternative text in case an image can't be displayed. async <script> Executes the script asynchronously. autocapitalize Global attribute Sets whether in...
...t>, <select>, <textarea> Indicates whether controls in this form can by default have their values automatically completed by the browser. autofocus <button>, <input>, <keygen>, <select>, <textarea> The element should be automatically focused after the page loaded. autoplay <audio>, <video> The audio or video should play as soon as possible. background <
body>, <table>, <td>, <th> Specifies the URL of an image file. Note: Although browsers and email clients may still support this attribute, it is obsolete. Use CSS background-image instead. bgcolor <
body>, <col>, <colgroup>, <marquee>, <table>, <t
body>, <tfoot>, <td>, <th>, <tr> Background color of the element. Note: This is a legacy attribute. Please use the CS...
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
selectors. These have the same syntax as CSS selectors. They select the content to insert in place of the <content> element. Example Here is a simple example of using the <content> element. It is an HTML file with everything needed in it. Note: For this code to work, the browser you display it in must support Web Components. See Enabling Web Components in Firefox. <html> <head></head> <
body> <!-- The original content accessed by <content> --> <div> <h4>My Content Heading</h4> <p>My content text</p> </div> <script> // Get the <div> above. var myContent = document.querySelector('div'); // Create a shadow DOM on the <div> var shadowroot = myContent.createShadowRoot(); // Insert into the shadow DOM a new heading and // part of the original content: the <p> t...
...tent text</p> </div> <script> // Get the <div> above. var myContent = document.querySelector('div'); // Create a shadow DOM on the <div> var shadowroot = myContent.createShadowRoot(); // Insert into the shadow DOM a new heading and // part of the original content: the <p> tag. shadowroot.innerHTML = '<h2>Inserted Heading</h2> <content select="p"></content>'; </script> </
body> </html> If you display this in a web browser it should look like the following. Specifications This element is no longer defined by any specifications. Browser compatibility The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. DesktopMobileC...
<html>: The HTML Document / Root element - HTML: Hypertext Markup Language
Tag omission The start tag may be omitted if the first thing inside the <html> element is not a comment. ...
... the current document. This attribute is not needed, because it is redundant with the version information in the document type declaration. xmlns Specifies the XML Namespace of the document. Default value is "http://www.w3.org/1999/xhtml". This is required in documents parsed with XML parsers, and optional in text/html documents. 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. The identifying language tag should describe the language used by the majority of the content of the page. Without it, screen readers will typically default to the operating system's ...
<input type="image"> - HTML: Hypertext Markup Language
n or action attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by formenctype or the form's enctype attribute. This URL is then sent to the server using an HTTP get request. This method works well for simple forms that contain only ASCII characters and have no side effects. This is the default value. post The form's data is included in the
body of the request that is sent to the URL given by the formaction or action attribute using an HTTP post request. This method supports complex data and file attachments. dialog This method is used to indicate that the button simply closes the dialog with which the input is associated, and does not transmit the form data at all. This attribute is also available on <input type="submit"> and <butto...
...he server. Possible values are: application/x-www-form-urlencoded: The default value if the attribute is not specified. text/plain. If this attribute is specified, it overrides the enctype attribute of the element's form owner. formmethod HTML5 Specifies the HTTP method that the browser uses to submit the form. Possible values are: post: The data from the form is included in the
body of the form and is sent to the server. get: The data from the form is appended to the form attribute URI, with a '?' as a separator, and the resulting URI is sent to the server. Use this method when the form has no side-effects and contains only ASCII characters. If specified, this attribute overrides the method attribute of the element's form owner. formnovalidate HTML5 A Boolean attri...
<shadow>: The obsolete Shadow Root element - HTML: Hypertext Markup Language
rface HTMLShadowElement Attributes This element includes the global attributes. Example Here is a simple example of using the <shadow> element. It is an HTML file with everything needed in it. Note: This is an experimental technology. For this code to work, the browser you display it in must support Web Components. See Enabling Web Components in Firefox. <html> <head></head> <
body> <!-- This <div> will hold the shadow roots. --> <div> <!-- This heading will not be displayed --> <h4>My Original Heading</h4> </div> <script> // Get the <div> above with its content var origContent = document.querySelector('div'); // Create the first shadow root var shadowroot1 = origContent.createShadowRoot(); // Create the second shadow root var shado...
... Specifications This element is no longer defined by any specifications. ...
contextmenu - HTML: Hypertext Markup Language
The contextmenu attribute is obsolete and will be removed from all browsers The contextmenu global attribute is the id of a <menu> to use as the contextual menu for this element. A context menu is a menu that appears upon user interaction, such as a right-click. HTML5 now allows us to customize this menu. 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. </li> ...
...I am learning ContextMenu from MDN via Mozilla"); } function shareViaFacebook() { window.open("https://facebook.com/sharer/sharer.php?u=" + "https://developer.mozilla.org/en/HTML/Element/Using_HTML_context_menus"); } function incFont() { document.getElementById("fontSizi...
Inline elements - HTML: Hypertext Markup Language
lay both the beginning and end of the inline element's influence.</div> In this example, the <div> block-level element contains some text. Within that text is a <span> element, which is an inline element. ...
... Changing element levels You can change the visual...
HTTP caching - HTTP
fresh; after the expiration time, the resource is stale. Eviction algorithms often privilege fresh resources over stale resources. Note that a stale resource is not evicted or ignored; when the cache receives a request for a stale resource, it forwards this request with a If-None-Match to check if it is in fact still fresh. If so, the server returns a 304 (Not Modified) header without sending the
body of the requested resource, saving some bandwidth. Here is an example of this process with a shared cache proxy: The freshness lifetime is calculated based on several headers. If a "Cache-Control: max-age=N" header is specified, then the freshness lifetime is equal to N. If this header is not present, which is very often the case, it is checked if an Expires header is present. If an Expires he...
...weak validator. It is considered weak because it only has 1-second resolution. If the Last-Modified header is present in a response, then the client can issue an If-Modified-Since request header to validate the cached document. When a validation request is made, the server can either ignore the validation request and response with a normal 200 OK, or it can return 304 Not Modified (with an empty
body) to instruct the browser to use its cached copy. The latter response can also include headers that update the expiration time of the cached document. Varying responses The Vary HTTP response header determines how to match future request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server. When a cache receives a request that can be ...
Expect - HTTP
large. No common browsers send the Expect header, but some other clients such as cURL do so by default. Header type Request header Forbidden header name yes Syntax No other expectations except "100-continue" are specified currently. Expect: 100-continue Directives 100-continue Informs recipients that the client is about to send a (presumably large) message
body in this request and wishes to receive a 100 (Continue) interim response. 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 m...
...e
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. Specifications Specification Title RFC 7231, section 5.1.1: Expect Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
GET - HTTP
The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data. ...
... The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data. ...
OPTIONS - HTTP
The HTTP OPTIONS method requests permitted communication options for a given URL or server. A client can specify a URL with this method, or an asterisk (*) to refer to the entire server. ...
... The HTTP OPTIONS method requests permitted communication options for a given URL or server. A client can specify a URL with this method, or an asterisk (*) to refer to the entire server. ...
PUT - HTTP
t method creates a new resource or replaces a representation of the target resource with the request payload. The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect (that is no side effect), whereas successive identical POST requests may have additional effects, akin to placing an order several times. ...
... representation of the target resource with the request payload. The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect (that is no side effect), whereas successive identical POST requests may have additional effects, akin to placing an order several times. ...
An overview of HTTP - HTTP
T), though more operations may be needed in other cases. The path of the resource to fetch; the URL of the resource stripped from elements that are obvious from the context, for example without the protocol (http://), the domain (here, developer.mozilla.org), or the TCP port (here, 80). The version of the HTTP protocol. Optional headers that convey additional information for the servers. Or a
body, for some methods like POST, similar to those in responses, which contain the resource sent. Responses An example response: Responses consist of the following elements: The version of the HTTP protocol they follow. A status code, indicating if the request was successful, or not, and why. A status message, a non-authoritative short description of the status code. HTTP headers, like tho...
...milar to those in responses, which contain the resource sent. Responses An example response: Responses consist of the following elements: The version of the HTTP protocol they follow. A status code, indicating if the request was successful, or not, and why. A status message, a non-authoritative short description of the status code. HTTP headers, like those for requests. Optionally, a
body containing the fetched resource. APIs based on HTTP The most commonly used API based on HTTP is the XMLHttpRequest API, which can be used to exchange data between a user agent and a server. The modern Fetch API provides the same features with a more powerful and flexible feature set. Another API, server-sent events, is a one-way service that allows a server to send events to the client, using...
HTTP range requests - HTTP
mma. 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. Each part contains its own Content-Type and Content-Range fields and the required boundary parameter specifies the boundary string used to separate each
body-part. 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 r...
...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. The If-Range HTTP request header makes a range request conditional: if the condition is fulfilled, the range request will be issued and the server sends back a 206 Partial Content answer with the appropriate
body. If the condition is not fulfilled, the full resource is sent back, with a 200 OK status. This header can be used either with a Last-Modified validator, or with an ETag, but not with both. If-Range: Wed, 21 Oct 2015 07:28:00 GMT Partial request responses There are three relevant statuses, when working with range requests: In case of a successful range request, the 206 Partial Content statu...
Indexed collections - JavaScript
= ["Fire", "Rain", "Wind"] sort() can also take a callback function to determine how array elements are compared. The sort method (and others below) that take a callback are known as iterative methods, because they iterate over the entire array in some fashion. Each one takes an optional second argument called thisObject. If provided, thisObject becomes the value of the this keyword inside the
body of the callback function. If not provided, as with other cases where a function is invoked outside of an explicit object context, this will refer to the global object (window) when using arrow function as callback, or undefined when using normal function as callback. The callback function is called with two arguments, that are array's elements. The function below compares two values and returns...
...ties and elements that provide information about the match. An array is the return value of RegExp.exec(), String.match(), and String.split(). For information on using arrays with regular expressions, see Regular Expressions. Working with array-like objects Some JavaScript objects, such as the NodeList returned by document.getElementsByTagName() or the arguments object made available within the
body of a function, look and behave like arrays on the surface but do not share all of their methods. The arguments object provides a length attribute but does not implement the forEach() method, for example. Array methods cannot be called directly on array-like objects. function printArguments() { arguments.forEach(function(item) { // TypeError: arguments.forEach is not a function console.lo...
JavaScript modules - JavaScript
nes in action in main.js. Note: In some module systems, you can omit the file extension and the dot (e.g. '/modules/square'). This doesn't work in native JavaScript modules. Once you've imported the features into your script, you can use them just like they were defined inside the same file. The following is found in main.js, below the import lines: let myCanvas = create('myCanvas', document.
body, 480, 320); let reportList = createReportList(myCanvas.id); let square1 = draw(myCanvas.ctx, 50, 50, 100, 'blue'); reportArea(square1.length, reportList); reportPerimeter(square1.length, reportList); Note: Although imported features are available in the file, they are read only views of the feature that was exported. You cannot change the variable that was imported, but you can still modify p...
... very similar to how we apply a regular script to a page, with a few notable differences. First of all, you need to include type="module" in the <script> element, to declare this script as a module. To import the main.js script, we use this: <script type="module" src="main.js"></script> You can also embed the module's script directly into the HTML file by placing the JavaScript code within the
body of the <script> element: <script type="module"> /* JavaScript module code here */ </script> The script into which you import the module features basically acts as the top-level module. If you omit it, Firefox for example gives you an error of "SyntaxError: import declarations may only appear at top level of a module". You can only use import and export statements inside modules, not regular ...
SyntaxError: redeclaration of formal parameter "x" - JavaScript
The JavaScript exception "redeclaration of formal parameter" occurs when the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function
body again. Message SyntaxError: Let/Const redeclaration (Edge) SyntaxError: redeclaration of formal parameter "x" (Firefox) SyntaxError: Identifier "x" has already been declared (Chrome) Error type SyntaxError What went wrong? The same variable name occurs as a function parameter and is then redeclared using a let assignment in a function
body again. Redeclaring the same variable within the same function or block scope using let is not allowed in JavaScript. Examples Redeclared argument In this case, the variable "arg" redeclares the argument. function f(arg) { let arg = 'foo'; } // SyntaxError...
...In other words: you can omit the let keyword. If you want to create a new variable, you need to rename it as conflicts with the function parameter already. ...
TypeError: variable "x" redeclares argument - JavaScript
This might be a naming conflict and thus JavaScript warns about it. This error occurs as a warning in strict mode code only. ...
...This might be a naming conflict and thus JavaScript warns about it. This error occurs as a warning in strict mode code only. In non-strict code, the redeclaration is silently ignored. ...
Function() constructor - JavaScript
o eval. However, unlike eval, the Function constructor creates functions which execute in the global scope only. The source for this interactive example is stored in a GitHub repository. If 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 new Function([arg1 [, arg2 [, ...argN]] ,] function
Body) Parameters arg1, arg2, ... argN Names to be used by the function as formal argument names. 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 "x,theValue". function
Body A string containing the JavaScript statements comprising the function definition. Description Function objects cre...
...tor The following code creates a Function object that takes two arguments. // Example can be run directly in your JavaScript console // Create a function that takes two arguments, and returns the sum of those arguments const adder = new Function('a', 'b', 'return a + b'); // Call the function adder(2, 6); // 8 The arguments "a" and "b" are formal argument names that are used in the function
body, "return a + b". Specifications Specification ECMAScript (ECMA-262)The definition of 'Function constructor' in that specification. ...
class expression - JavaScript
The class expression is one way to define a class in ECMAScript 2015. Similar to function expressions, class expressions can be named or unnamed. If named, the name of the class is local to the class
body only. JavaScript classes use prototype-based inheritance. The source for this interactive example is stored in a GitHub repository. If 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 const MyClass = class [className] [extends otherClassName] { // class
body }; Description A class expression has a similar syntax to a class declaration (statement). As with class statements, the
body of a class expression is executed in strict mode. There are several differences between class ...
...ion) Examples A simple class expression This is just a simple anonymous class expression which you can refer to using the variable Foo. const Foo = class { constructor() {} bar() { return 'Hello World!'; } }; const instance = new Foo(); instance.bar(); // "Hello World!" Foo.name; // "Foo" Named class expressions If you want to refer to the current class inside the class
body, you can create a named class expression. The name is only visible within the scope of the class expression itself. const Foo = class NamedFoo { constructor() {} whoIsThere() { return NamedFoo.name; } } const bar = new Foo(); bar.whoIsThere(); // "NamedFoo" NamedFoo.name; // ReferenceError: NamedFoo is not defined Foo.name; // "NamedFoo" Specifications Specifi...
Function expression - JavaScript
s://github.com/mdn/interactive-examples and send us a pull request. Syntax The expression is not allowed at the start of a statement. function [name]([param1[, param2[, ..., paramN]]]) { statements } As of ES2015, you can also use arrow functions. Parameters name Optional The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function
body. paramN Optional The name of an argument to be passed to the function. statements Optional The statements which comprise the
body of the function. Description A function expression is very similar to and has almost the same syntax as a function declaration (see function statement for details). The main difference between a function expression and a function declaration is the function name...
...ations. You can't use function expressions before you create them: console.log(notHoisted) // undefined // even though the variable name is hoisted, the definition isn't. so it's undefined. notHoisted(); // TypeError: notHoisted is not a function var notHoisted = function() { console.log('bar'); }; Named function expression If you want to refer to the current function inside the function
body, you need to create a named function expression. This name is then local only to the function
body (scope). This also avoids using the non-standard arguments.callee property. let math = { 'factit': function factorial(n) { console.log(n) if (n <= 1) { return 1; } return n * factorial(n - 1); } }; math.factit(3) //3;2;1; The variable the function expression is assigned...
this - JavaScript
ew Number(7) and the string 'foo' to an object as if by new String('foo'), e.g. function bar() { console.log(Object.prototype.toString.call(this)); } bar.call(7); // [object Number] bar.call('foo'); // [object String] bar.call(undefined); // [object global] The bind method ECMAScript 5 introduced Function.prototype.bind(). Calling f.bind(someObject) creates a new function with the same
body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used. function f() { return this.a; } var g = f.bind({a: 'azerty'}); console.log(g()); // azerty var h = g.bind({a: 'yoo'}); // bind only works once! console.log(h()); // azerty var o = {a: 37, f: f, g: g, h: h}; c...
...unction is used as a constructor (with the new keyword), its this is bound to the new object being constructed. While the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned). /* * Constructors work like this: * * function MyConstructor(){ * // Actual function
body code goes here. * // Create properties on |this| as * // desired by assigning to them. E.g., * this.fum = "nom"; * // et cetera... * * // If the function has a return statement that * // returns an object, that object will be the * // result of the |new| expression. Otherwise, * // the result of the expression is the object * // currently bound to |this| * // (i.e...
empty - JavaScript
amples and send us a pull request. Syntax ; Description The empty statement is a semicolon (;) indicating that no statement will be executed, even if JavaScript syntax requires one. The opposite behavior, where you want multiple statements, but JavaScript only allows a single one, is possible using a block statement, which combines several statements into a single one. ...
...that no statement will be executed, even if JavaScript syntax requires one. The opposite behavior, where you want multiple statements, but JavaScript only allows a single one, is possible using a block statement, which combines several statements into a single one. Examples Empty loop
body The empty statement is sometimes used with loop statements. See the following example with an empty loop
body: let arr = [1, 2, 3]; // Assign all array values to 0 for (let i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ; console.log(arr); // [0, 0, 0] Unintentional usage It is a good idea to comment intentional use of the empty statement, as it is not really obvious to distinguish from a normal semicolon. In the following example, the usage is probably not intentional: if (condition)...
Populating the page: how browsers work - Web Performance
r sends an initial HTTP GET request on behalf of the user, which for websites is most often an HTML file. Once the server receives the request, it will reply with relevant response headers and the contents of the HTML. <!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. Time to First Byte (TTFB) is the time between when the user made the request--s...
...verses it. On the web page, most everything is a box. Different devices and different desktop preferences mean an unlimited number of differing viewport sizes. In this phase, taking the viewport size into consideration, the browser determines what the dimensions of all the different boxes are going to be on the screen. Taking the size of the viewport as its base, layout generally starts with the
body, laying out the dimensions of all the
body's descendants, with each element's box model properties, providing placeholder space for replaced elements it doesn't know the dimensions of, such as our image. The first time the size and position of nodes are determined is called layout. Subsequent recalculations of node size and locations are called reflows. In our example, suppose the initial layou...
Navigation and resource timings - Web Performance
rest of this explanation, we use the following variable: let timing = performance.getEntriesByType('navigation')[0]; Protocol We can check the protocol used by querying: let protocol = timing.nextHopProtocol It returns the network protocol used to fetch the resource: in this case h2 for http/2. Compression To get the compression savings percentage, we divide the transferSize by the decoded
BodySize, and subtract that from 100%. We see a savings of over 74%. let compressionSavings = 1 - (timing.transferSize / timing.decoded
BodySize) We could have used let compressionSavings = 1 - (timing.encoded
BodySize / timing.decoded
BodySize) but using transfersize includes the overhead bytes. For comparison, we can look at the network tab and see that we transferred 22.04KB for an uncompressed f...
...matically check transfer sizing and bandwidth savings. Note that this is the size for this single document alone: for this resource alone, not for all the resources combined. However, the duration, load events and DOM related timings have to do with the entire navigation, not this single asset. Client-side web applications may seem faster than this one with transfer sizes under 10000 and decoded
body sizes under 30000, but that doesn't mean JavaScript, CSS, or media assets aren't adding bloat. Checking compression ratios is important but ensure to also check duration and the time between when the DOMContentLoaded event ended and when the DOM is complete, as running JavaScript on the main thread for long periods of time can lead to a non-responsive user interface. Request time The API doesn'...
class - SVG: Scalable Vector Graphics
The following is a template for an EBNF grammar describing the <list-of-Ts> syntax: list-of-Ts ::= T | T, list-of-Ts Within the SVG DOM, values of a <list-of-Ts> type are represented by an interface specific for the particular type T. For example, a <list-of-lengths> is represented in the SVG DOM using an SVGLengthList or SVGAnimatedLengthList object. ...
... 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: <a> <altGlyph> <circle> <clipPath> <defs> <desc> <ellipse> <feBlend> <feColorMatrix> <feComponentTransfer> <feComposite> <feConvolveMatrix> <feDiffuseLighting> <feDisplacementMap> <feFlood> <feGaussianBlur> <feImage> <feMerge> <feMorphology> <feOffset> <feSpecularLighting> <feTile> <feTurbulence> <f...
cx - SVG: Scalable Vector Graphics
The cx attribute define the x-axis coordinate of a center point. Three elements are using this attribute: <circle>, <ellipse>, and <radialGradient> html,
body,svg { height:100% } <svg viewBox="0 0 300 100" xmlns="http://www.w3.org/2000/svg"> <radialGradient cx="25%" id="myGradient"> <stop offset="0" stop-color="white" /> <stop offset="100%" stop-color="black" /> </radialGradient> <circle cx="50" cy="50" r="45"/> <ellipse cx="150" cy="50" rx="45" ry="25" /> <rect x="205" y="5" width="90" height="90" fill="url(#myGradient)" /> </svg> circle For <circle>, cx defines the x-axis coordinate of the center of the shape. Value <length-percentage> Default value 0 Animatable Yes Note: Starting with SVG2 cx, is a Geometry Propert...
... Default value 0 Animatable Yes Note: Starting with SVG2 cx, is a Geometry Property, meaning this attribute can also be used as CSS property for ellipses. radialGradient For <radialGradient>, cx defines the x-axis coordinate of the end circle for the radial gradient. ...
cy - SVG: Scalable Vector Graphics
The cy attribute define the y-axis coordinate of a center point. Three elements are using this attribute: <circle>, <ellipse>, and <radialGradient> html,
body,svg { height:100% } <svg viewBox="0 0 100 300" xmlns="http://www.w3.org/2000/svg"> <radialGradient cy="25%" id="myGradient"> <stop offset="0" stop-color="white" /> <stop offset="100%" stop-color="black" /> </radialGradient> <circle cy="50" cx="50" r="45"/> <ellipse cy="150" cx="50" rx="45" ry="25" /> <rect x="5" y="205" width="90" height="90" fill="url(#myGradient)" /> </svg> circle For <circle>, cy defines the y-axis coordinate of the center of the shape. Value <length> | <percentage> Default value 0 Animatable Yes Note: Starting with SVG2, cy is a Geometry P...
... Default value 0 Animatable Yes Note: Starting with SVG2, cy is a Geometry Property meaning this attribute can also be used as a CSS property for ellipses. radialGradient For <radialGradient>, cy defines the y-axis coordinate of the end circle for the radial gradient. ...
dx - SVG: Scalable Vector Graphics
The dx attribute indicates a shift along the x-axis on the position of an element or its content. ...
... for all glyphs. If there are multiple values, dx defines a shift along the x-axis for each individual glyph relative to the preceding glyph. If there are less values than glyphs, the remaining glyphs use a value of 0. If there are more values than glyphs, extra values are ignored. ...
dy - SVG: Scalable Vector Graphics
The dy attribute indicates a shift along the y-axis on the position of an element or its content. ...
...r all glyphs. If there are multiple values, dy defines a shift along the y-axis for each individual glyph relative to the preceding glyph. If there are less values than glyphes, the remaining glyphes use a value of 0. If there are more values than glyphes, extra values are ignored. ...
href - SVG: Scalable Vector Graphics
ds on the context of each element using it. Note: Specifications before SVG 2 defined an xlink:href attribute, which is now rendered obsolete by the href attribute. Fifteen elements are using this attribute: <a>, <animate>, <animateMotion>, <animateTransform>, <discard>, <feImage>, <image>, <linearGradient>, <mpath>, <pattern>, <radialGradient>, <script>, <set>, <textPath>, and <use> html,
body, svg { height: 100%; } <svg viewBox="0 0 160 40" xmlns="http://www.w3.org/2000/svg"> <a href="https://developer.mozilla.org/"><text x="10" y="25">MDN Web Docs</text></a> </svg> In SVG a For <a>, href defines the location of the referenced object, expressed as a URL reference. Value <url> Default value None Animatable Yes animate, animateMoti...
...n image resource or to an element. If both, the xlink:href and the href attribute are specified, the latter overrides the former. Value <url> Default value None Animatable Yes image For <image>, href defines a URL referring to the image to render. 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. Value <url> ...
<a> - SVG: Scalable Vector Graphics
The <a> SVG element creates a hyperlink to other web pages, files, locations in the same page, email addresses, or any other URL. It is very similar to HTML's <a> element. SVG's <a> element is a container, which means you can create a link around text (like in HTML) but also around any shape. ...
...ault value: none; Animatable: no href The URL or URL fragment the hyperlink points to. Value type: <URL> ; Default value: none; Animatable: yes hreflang The human language of the URL or URL fragment that the hyperlink points to. Value type: <string> ; Default value: none; Animatable: yes ping A space-separated list of URLs to which, when the hyperlink is followed, POST requests with the
body PING will be sent by the browser (in the background). Typically used for tracking. For a more widely-supported feature addressing the same use cases, see Navigator.sendBeacon(). Value type: <list-of-URLs> ; Default value: none; Animatable: no referrerpolicy Which referrer to send when fetching the URL. Value type: no-referrer|no-referrer-when-downgrade|same-origin|origin|strict-origin|origi...
Example - SVG: Scalable Vector Graphics
First, each mote tries to move towards the cursor, and second each mote tries to move away from the average mote position. Combined, we get this very natural looki...
...ctly that many... ...
Namespaces crash course - SVG: Scalable Vector Graphics
are used so frequently that the term "namespace URI" is commonly used instead of "namespace name".) Redeclaring the default namespace So if all the descendants of the root element are also defined to be in the default namespace, how do you mix in content from another namespace? Easy. You just redefine the default namespace. Here's a short example. <html xmlns="http://www.w3.org/1999/xhtml"> <
body> <!-- some XHTML tags here --> <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px"> <!-- some SVG tags here --> </svg> <!-- some XHTML tags here --> </
body> </html> In this example the xmlns parameter on the root <html> element declares the default namespace to be XHTML. As a result, it and all its child elements are interpreted by the user agent as belo...
...l to know that namespace prefixes can also be used for element names. This tells the user agent that that particular element (but not its children this time!) belongs to the namespace assigned to the prefix. Knowing this will save you some confusion if you come across markup like in the following example: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <
body> <h1>SVG embedded inline in XHTML</h1> <svg:svg width="300px" height="200px"> <svg:circle cx="150" cy="100" r="50" fill="#ff0000"/> </svg:svg> </
body> </html> Note that because a namespace prefix is used for the <svg:svg> element and its child <svg:circle>, it wasn't necessary to redeclare the default namespace. In general though it is better to redeclare the default namespa...
Using shadow DOM - Web Components
e concept of the DOM (Document Object Model) -- a tree-like structure of connected nodes that represents the different elements and strings of text appearing in a markup document (usually an HTML document in the case of web documents). ...
... <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="https://www.mozilla.org/">Mozilla homepage</a></p> </section> </
body> </html> This fragment produces the following DOM structure: Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree -- this shadow DOM tree starts with a shadow root, underneath which can be attached to any elements you want, in the same way as the normal DOM. There are some bits of shadow DOM terminology to be aware of: Shadow host: The regular DOM node t...
Compiling from Rust to WebAssembly - WebAssembly
This imports the new module from the node_modules folder. This isn't considered a best p...
... This imports the new module from the node_modules folder. This isn't considered a best practice, but this is a demo, so it's OK for now. ...
Classes and Inheritance - Archive of obsolete content
can write: let Shape = Class({ initialize: function (x, y) { this.x = x; this.y = y; }, draw: function () { throw new Error("not yet implemented"); } }); The property initialize is special. When it is present, the call to the constructor is forwarded to it, as are any arguments passed to it (including the this object). In effect, initialize specifies the
body of the constructor. Note that the constructors created with Class automatically check whether they are called as constructors, so an explicit check is no longer necessary. Another special property is extends. It specifies the base class from which this class inherits, if any. Class uses this information to automatically set up the prototype chain of the constructor. If the extends property is om...
Porting the Library Detector - Archive of obsolete content
aryInfo(element) { self.port.emit('setLibraryInfo', element.target.title); } var elements = document.getElementsByTagName('img'); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('mouseover', setLibraryInfo, false); } one in the panel, which updates the panel's content with the library information: self.on("message", function(libraryInfo) { window.document.
body.innerHTML = libraryInfo; }); Finally main.js relays the library information from the widget to the panel: widget.port.on('setLibraryInfo', function(libraryInfo) { widget.panel.postMessage(libraryInfo); }); ...
notifications - Archive of obsolete content
f the user launched Firefox from the command line, notifications are logged to the terminal. Globals Functions notify(options) Displays a transient notification to the user. Parameters options : object Optional options: Name Type title string A string to display as the message's title. text string A string to display as the
body of the message. iconURL string The URL of an icon to display inside the message. It may be a remote URL, a data URI, or a URL returned by the self module. onClick function A function to be called when the user clicks the message. It will be passed the value of data. data string A string that will be passed to onClick. ...
request - Archive of obsolete content
content string,object The content to send to the server. If content is a string, it should be URL-encoded (use encodeURIComponent). If content is an object, it should be a collection of name/value pairs. Nested objects & arrays should encode safely. For GET and HEAD requests, the query string (content) will be appended to the URL. For POST and PUT requests, it will be sent as the
body of the request. contentType string The type of content to send to the server. This explicitly sets the Content-Type header. The default value is application/x-www-form-urlencoded. overrideMimeType string Use this string to override the MIME type returned by the server in the response's Content-Type header. You can use this to treat the content as a ...
Creating annotations - Archive of obsolete content
rectory under data called editor. This will contain two files: the HTML content, and the content script. Annotation editor HTML The HTML is very simple: <!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" xml:lang="en"> <head> <title>Annotation</title> <style type="text/css" media="all">
body { font: 100% arial, helvetica, sans-serif; background-color: #F5F5F5; } textarea { width: 180px; height: 180px; margin: 10px; padding: 0px; } </style> </head> <
body> <textarea rows='10' cols='20' id='annotation-box'> </textarea> </
body> </html> Save this inside data/editor as annotation-editor.html. Annotation editor content script In the corresponding cont...
Displaying annotations - Archive of obsolete content
ntent script to build the panel's content These files will live in a new subdirectory of data which we'll call annotation. Annotation panel HTML <!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" xml:lang="en"> <head> <title>Annotation</title> <style media="all" type="text/css">
body { font: 100% arial, helvetica, sans-serif; background-color: #F5F5F5; } div { text-align:left; } </style> </head> <
body> <div id="annotation"> </div> </
body> </html> Save this in data/annotation as annotation.html. Annotation panel Content Script The annotation panel has a minimal content script that sets the text: self.on('message', function(message) { ...
List Open Tabs - Archive of obsolete content
ttaches a script to all open tabs. The script adds a red border to the tab's document: require("sdk/ui/button/action").ActionButton({ id: "list-tabs", label: "List Tabs", icon: "./icon-16.png", onClick: listTabs }); function listTabs() { var tabs = require("sdk/tabs"); for (let tab of tabs) runScript(tab); } 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. To learn more about running scripts in tabs, see the tutorial on using tab.attach(). ...
Listen for Page Load - Archive of obsolete content
ser Console, not the Web Console. You don't get direct access to any content hosted in the tab. To access tab content you need to attach a script to the tab using tab.attach(). This add-on attaches a script to all open tabs. 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. You can listen for a number of other tab events, including open, close, and activate. To learn more ...
Logging - Archive of obsolete content
ommand window you used to execute jpm run: info: Hello World! console in Content Scripts You can use the console in content scripts as well as in your main add-on code. 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. If you've installed the add-on in Firefox then the messages appear in Firefox's Browser Console. But note that by default, calls to console.log() will not result in any output in the Error Con...
Open a Web Page - Archive of obsolete content
get direct access to any content hosted in the tab. To access tab content you need to attach a script to the tab using tab.attach(). 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. To learn more about running scripts in tabs, see the tutorial on using tab.attach(). ...
Canvas code snippets - Archive of obsolete content
teElement('iframe'); iframe.id = 'test-iframe'; iframe.height = '10px'; iframe.width = windowWidth + 'px'; iframe.style.visibility = 'hidden'; iframe.src = this.url; // Here is where the magic happens... ...
Rosetta - Archive of obsolete content
a 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> <script type="text/x-c" src="example.c"></script> </head> <
body> <p>Lorem ipsum</p> <script type="text/javascript"> rosetta.translateAll(); </script> </
body> </html> example.c: C Example #include <stdio.h> int main () { printf("Hello world number 2!\n"); return 0; } If creating a compiler for the C programming language, as in the example above, can really look a huge task, there are many dialects of ECMAScript which could be easily translated to s...
StringView - Archive of obsolete content
ction. Examples function myCallback (charCode, characterOffset, rawOffset /*, rawDataArray */) { this.appendChild(document.createTextNode("char #" + characterOffset + ", raw index: " + rawOffset + ", character: " + String.fromCharCode(charCode))); this.appendChild(document.createElement("br")); } (new StringView("\u4367\uD889\uDE54\u4343\u5431")).forEachChar(myCallback, document.
body); Note: stringView.forEachChar() executes a complete cycle through all characters in the stringView between characterOffset and characterOffset + charactersLength. If you want to build a custom cycle through a variable-length-encoded stringView (UTF-8, UTF-16), you can use a code like the following, which does not make use of stringView.forEachChar(). If the encoding is a fixed-length on...
Communication between HTML and your extension - Archive of obsolete content
icated for what I wanted to achieve. Eventually I put the creation of the custom event into the stateChanged function that was handling the receipt of the AJAX request. After the HTML component was update with the result of the AJAX request, I created and dispatched the event like this: var event = document.createEvent("Events"); event.initEvent("my-custom-event", true, true); document.
body.dispatchEvent(event); In the code of the extension that catches the loading of a new page I added this code: var doc = aEvent.originalTarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a Location object (see below for a link). // You can use it to make your code executed on certain pages only. if (doc && doc.addEventLi...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
the data, expressed through HTML or XML, and the display style, indicated by CSS, data can be reused better than it is when structural and stylistic markup are both embedded in HTML. There are three CSS specifications (Level 1 through Level 3), with progressively powerful features. The Gecko rendering engine handles nearly all of CSS Level 2 and some of CSS Level 3. Listing 2: CSS code sample
body { color: black; background-color: white; } p { margin-bottom: 1em; text-indent: 1em; } JavaScript: The world's most misunderstood language JavaScript is a scripting language first developed in the 1990s, at which time it was created as a way to add dynamic features to web pages. Because it was often used at first to display pop-up windows, marching text in status bars, or in other ways...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
will not work. Also, calling .bind() in a tight (inner) loop should be avoided for performance reasons, as calling .bind() does require some work and memory. Overriding/Extending/Amending existing functions A common thing add-ons do during their initialization is overriding/extending existing browser functions by using Function.toString/Function.toSource and eval to "string-patch" the function
body. // DO NOT USE! var function
Body = gBrowser.addTab.toSource(); var afterBracket = function
Body.indexOf("{") + 1; function
Body = function
Body.substring(0, afterBracket) + "myAddon.onAddTab(aURI);" + function
Body.substring(afterBracket); eval("gBrowser.addTab = " + function
Body); Of course, this not only looks messy, but can be quite error prone. Other extensions might do something similar, t...
Custom XUL Elements with XBL - Archive of obsolete content
cloning your node: all internal state in the node will be lost. This means that all your properties and fields will be reset. If you want some value to be preserved after such DOM operations, you must set it as an attribute and not an internal value. Methods Our "Person" binding has a single method that removes the item from the list: <method name="remove"> <parameter name="aEvent" /> <
body><![CDATA[ this.parentNode.removeChild(this); ]]></
body> </method> As you can see, it's very easy to define a method and the parameters it takes. You can also have a return value using the return keyword, just like on regular JS code. The method uses the parent node to remove the Person node. Simple enough. You can do almost anything from XBL code, including using XPCOM components, JS Co...
The Essentials of an Extension - Archive of obsolete content
tools can generate documentation automatically from Javadoc. sayHello : function(aEvent) { let stringBundle = document.getElementById("xulschoolhello-string-bundle"); let message = stringBundle.getString("xulschoolhello.greeting.label"); window.alert(message); } And, finally, this is our function declaration. Three lines of code are all we need for it to work. The first line in the
body of the function declares a variable that will hold the stringbundle element defined in the overlay. The variable is declared using let, which is similar to var but with more restricted scope. Here you can read more about let declarations. Just like in regular JS, we can use the DOM (Document Object Model) in order to manipulate the XUL document. First we get a reference of the stringbundle eleme...
Tabbed browser - Archive of obsolete content
rowser.selectedTab = gBrowser.addTab("http://www.google.com/"); Manipulating content of a new tab If you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading. // WRONG WAY (the page hasn't finished loading yet) var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); alert(newTabBrowser.contentDocument.
body.innerHTML); // BETTER WAY var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); newTabBrowser.addEventListener("load", function () { newTabBrowser.contentDocument.
body.innerHTML = "<div>hello world</div>"; }, true); (The event target in the onLoad handler will be a 'tab' XUL element). See tabbrowser for getBrowserForTab(). Note that the code above does not...
Firefox addons developer guide - Archive of obsolete content
d dealing with, but those are already known. These should use the Previous, Next, and PrevNext templates to add quick routes to get from chapter to chapter. See the XUL Reference, for example. Each chapter should be tagged appropriately, based on content, and every chapter should include the tag "Firefox addons developer guide". Instead of using footnotes, we should inline these notes into the
body of the article. Apostrophes are being done using curly apostrophes instead of straight ones as is done everywhere else in MDC. The stuff about installing the DOM inspector (https://developer.mozilla.org/En/Firefox_addons_developer_guide/Let%27s_build_a_Firefox_extension#Install_the_DOM_Inspector) is not accurate for Firefox 3 or later, since it's no longer included in the Firefox installer and ...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
the baseline is referred to as "descender space" since that's where the descenders in lowercase letters like "j", "y", and "q" are drawn. Figure 4 shows what happens when we add an image to the mix. Note where the image sits by default: its bottom edge is aligned with the baseline of the line box. This placement can be changed with vertical-align-- we'll talk about that in a bit-- but almost no
body ever changes the value from its default. Let's take away the text, and leave only the image, as was done in Figure 5. So we have an image sitting on the baseline of a line box that contains only the image. Now consider what happens when we put that line in a table cell (Figure 6). And there you have it-- spaces opening up where none have ever been seen before. It gets even worse with small ...
Drag and Drop Example - Archive of obsolete content
tAttribute("left", "" + event.pageX); elem.setAttribute("top", "" + event.pageY); elem.setAttribute("label", dropdata.data); } } } The getSupportedFlavours function needs only to return a list of flavours that the stack can accept to be dropped on it. In this case, it only accepts text. We don't need to do anything special for the onDragOver function, so no code is added in its
body. The onDrop handler first uses the createElement function to create a new element of the type stored in the drag session. Next, appendChild is called to add the new element to the stack, which is the target of the event. Finally, we set some attributes on the new element. The position of elements in a stack is determined by the left and top attributes. The values of the pageX and pageY properties...
Layout FAQ - Archive of obsolete content
s, but if none are pending, show the view immediately? What is the best way to determine whether there are any pending changes? On the reflow branch you could check the DIRTY and DIRTY_CHILDREN framestate flags. That won't help with pending style changes, but it'll work to detect cases when the popup or something in it needs to be reflown. ...
Style System Overview - Archive of obsolete content
red kilobytes for all our chrome), and require large numbers of allocations to construct. Detail: !important declarations cause an extra rule object CSSImportantRule to be created since they are in a separate part of the cascade Other nsIStyleRule implementations nsHTMLMappedAttributes represents stylistic HTML attributes turned into a style rule (one instance per unique set of attributes)
BodyRule handles marginwidth/marginheight mixes on
BODY and on FRAME. Various rules in nsHTMLStyleSheet.cpp do other things with presentational color-related attributes and with tables. Content nodes (instead of stylesheets) also hold onto CSSStyleRuleImpl objects that represent their style attributes. The cascade StyleSetImpl manages the different origins of rules in the cascade (UA, user, aut...
First run - Archive of obsolete content
able named manifest. You may define this variable anywhere in the global namespace of your jetpack. It's the same manifest you use when defining settings for your jetpack. The value of firstRunPage must be either a string or E4X XML. If the value is a both a string and a valid URL, the page at that URL becomes your first-run page. Otherwise, the value is assumed to be HTML, and it becomes the
body of your first-run page. 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! Visit my <a href="http://example.com/myJetpack">homepage</a>. </p> </> }; ...
First Run - Archive of obsolete content
variable named manifest. You may define this variable anywhere in the global namespace of your jetpack. It's the same manifest you use when defining settings for your jetpack. The value of firstRunPage must be either a string or E4X XML. If the value is a both a string and a valid URL, the page at that URL becomes your first-run page. Otherwise, the value is assumed to be HTML, and it becomes the
body of your first-run page. 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! Visit my <a href=//example.com/myJetpack">homepage</a>. </p> </> }; In...
Metro browser chrome tests - Archive of obsolete content
g about:blank", setUp: function () { }, tearDown: function () { }, run: function () { yield addTab("about:blank"); is(tab.browser.currentURI.spec, "about:blank", "about:blank is loaded"); } }); function test() { runTests(); } gTests contains individual tests that make up the library of tests your test file will contain. Each test can have start up and tear down logic, plus the
body of the test contained in run(). The test file can contain other functions which will be ignored unless invoked by test(). gTests make use of Promises and Tasks for managing execution. Test comparison functions used in metro browser chrome tests are identical to those supported by Mochitests, see how the comparison functions work in the Mochitest documentation for more details. Helper functions Th...
RDF Datasource How-To - Archive of obsolete content
isplaying RDF as content Now that you've gone through all this pain to expose your information as a datasource, you probably want to see it. Using XUL, you can display the contents of your datasource in a tree control, a menu, or a toolbar. In fact, you can convert RDF to an arbitrary content model using XUL Templates. ...
Merging TraceMonkey Repo - Archive of obsolete content
in hg resolve -l will have Rs next to them. Perform a build. If the tree does not build successfully you've likely merged something incorrectly. Historically, auto-merge doesn't mess up much. Land. If the sheriff gives you permission to land, hg push -r default ssh://hg.mozilla.org/tracemonkey and hg push ssh://hg.mozilla.org/mozilla-central If you can't push to mozilla-central because some
body ignored the "ask the sheriff" rule and pushed there anyway, that's typical, and it just means you have to repeat the above process. Mark Bugzilla bugs as fixed. Once you've pushed to mozilla-central, do a Bugzilla search for bugs that are not marked as RESOLVED but have fixed-in-tracemonkey in the whiteboard. For each bug in the results, find the corresponding changesets that we just merged (i...
Table Layout Regression Tests - Archive of obsolete content
l the regression tests indicate that your patch does not fork the block and table layout Submit your patch and lists the remaining differences in the bug Be prepared to cycle. How the layout regression tests work First the URL's to test are red from rtest.lst files in various directories. layout/html/tests/block/rtest.lst points to them. Snippet from rtest.lst in the table/marvin directory:
body_col.html
body_t
body.html
body_tfoot.html
body_thead.html col_span.html The regression tests compare the frame tree dumps recorded at two different times. The URL's to test are red from rtest.lstFor every file in rtest.lst Mozilla takes the root frame and dumps the whole tree via nsFrame::DumpRegression. The frame tree dumps are invoked by the nsILayoutDebugger. The frame trees are dumped to sepa...
Treehydra Manual - Archive of obsolete content
ne" + (isGCC42 ? "" : "_ipa")}); include('gcc_util.js'); // for function_decl_cfg function process_cgraph(cgraph) { // cgraph is a GCC structure representing a group of functions // within the call graph. Iterate over the functions like this. for (let node = cgraph; node; node = node.next) { let fn = node.decl; if (DECL_STRUCT_FUNCTION(fn)) { // fn has a
body print(fn); let cfg = function_decl_cfg(fn); } } GIMPLE Reference For a detailed description of GIMPLE see gcc/tree.def and gcc/cp/operators.def See also treehydra.js, gcc_compat.js, gcc_util.js, and gcc_print.js in the Treehydra libs directory, which have many ports of GCC macros and other functions for conveniently accessing GIMPLE data in JavaScript. ESP Abstract Interpreta...
Binding Implementations - Archive of obsolete content
he implementation element are ignored. Methods Methods are defined using the method element. The name given on the tag using the name attribute is the name that can be used to invoke the method on the element. A method with parameters specifies those parameters and their names with parameter elements declared underneath the method element. The implementation of the method is contained inside a
body element. The parameters specified are bound to their names in the method
body. <method name="scrollToIndex"> <parameter name="index"/> <
body> <![CDATA[ if (index < 0) return; ... ]]> </
body> </method> Properties Properties can also be defined on the bound element using property tags. There are two basic types of properties. The first type of property is a raw...
Event Handlers - Archive of obsolete content
the handler is attached to and if that event matches all of the criteria specified by the handler. The most basic handler specifies the event to listen for and an action to take when the handler fires. This action can be specified either using an action attribute or by specifying the script as a child of the handler element. If both are specified, the attribute wins. In both cases the JavaScript
body is compiled just before execution; code that does not depend on the context of the event should be factored into normal Javascript file. (Note that there is a possibility that this may change in the future.) Handlers are attached to the bound element, and they are registered by default for bubbling events. This means that <handler event="click" action="foo()"/> is analogous to onclick="foo()"...
XBL 1.0 Reference - Archive of obsolete content
BL proposals, and not all of them are reflected yet in this document. The documentation process is still in progress: please keep it in your mind while using the provided information. XBL Elements XBL 1.0 elements are in the http://www.mozilla.org/xbl namespace. ...
A XUL Bestiary - Archive of obsolete content
is based for the most part on XML. Collectively, these widgets are also known as the XPToolkit. Object Models: DOM and AOM The Document Object Model is the representation of a document as a series of scriptable objects. When a scripting language like JavaScript accesses various parts of an HTML document, it does so by means of the DOM. The parts of the document, such as the head, the links, the
body, any tags, are available as nodes whose attributes can be got and set. There are, unfortunately, different document object models corresponding to different types of documents and also to different proprietary notions about what in a document should be exposed programmatically. The W3C has standardized on a particular DOM and already has a candidate recommendation for an updated version. This is ...
Tooltips - Archive of obsolete content
. In this example, this property is examined to retrieve the label of the element that the mouse is over. This label is then set as the value of the last child of the tooltip. In the earlier example, the last child of the tooltip is a label. The effect is that the value of the label within the tooltip will change based on the element that the mouse is moved over. Tooltips in Trees As the entire
body of the tree is displayed using a single element, the tooltip and tooltiptext attributes do not apply to individual rows or cells of a tree. However, the tree will automatically display tooltips for a cell when the value is cropped. For instance, if a cell has a long label and the column is shorter than the label's length, a tooltip will appear when the mouse is moved over the cell so that the use...
Additional Navigation - Archive of obsolete content
o = http://www.xulplanet.com/ndeakin/images/t/palace.jpg) (?start = http://www.daml.org/2001/09/countries/iso#IT, ?countrytitle = Italy, ?photo = http://www.xulplanet.com/ndeakin/images/t/obselisk.jpg) The third triple just grabs the title from the photo as previous examples did, adding a value for the ?title variable for each photo. We can then display these results using the following action
body. <vbox uri="?photo" class="box-padded"> <image src="?photo"/> <label value="?title"/> <label value="Country: ?countrytitle"/> </vbox> A label for the country will be displayed as well. Naturally, it will have the same value for every photo. Some padding has been added around each photo using the 'box-padded' class. Here is the example. By carefully defining the RDF graph and using the ...
Filtering - Archive of obsolete content
to find the individual countries. A second triple is used to get the title for the country. <query> <content uri="?start"/> <triple subject="?country" predicate="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" object="?start"/> <triple subject="?country" predicate="http://purl.org/dc/elements/1.1/title" object="?countrytitle"/> </query> The action
body will need to generate a <menuitem> for each result. It will also need to include a <menupopup> around all of the items. Since we only want to generate a single menupopup, it should go outside of the element with the uri attribute. Only the contents at the element with the uri attribute and below are copied for each result. The elements above are not. <action> <menupopup> <menuitem uri="?co...
Multiple Rules - Archive of obsolete content
mpare. In this case, '?title' is used to compare the title. The rel specifies a relation operator to compare with. Here 'equals' is the operator used so an exact match is needed. The value attribute is the value to compare to, which here is 'Canal'. As the datasource has three photos, one of which has a title of 'Canal', this photo will match the first rule and the content's of that rule's action
body will be generated. The remaining two photos do not match the first rule, however they do match the second rule, as the second rule has no where clauses. For these two photos, the action
body of the second rule will apply. When used together in this example, the results are combined and only three results are shown. However, you will probably notice that the one photo that matches the first rule h...
RDF Modifications - Archive of obsolete content
as something different, naturally we don't need to change the template output, as that resource isn't being used in a template. Finally, the builder processes any statements below the one we started at, in order to fill in any remaining variables. In this case, there are no other statements, so the builder accepts this result as a new match. Since all the variables have been filled in, the action
body can be processed and a new block of content generated and inserted into the output. We'll find out how the builder determines where to insert the new content is an upcoming section. However, this does show that the template builder can update the output upon changes without rebuilding the entire template. When an unassertion occurs, or data is removed from the datasource, a different process is u...
Recursive Generation - Archive of obsolete content
it, so the result is rejected. Since there are no potential results, the builder doesn't generate anything. A similar situation will occur for item D. However, for item C, the triple does match an item, so the data will be added to the potential result: (?start = http://www.xulplanet.com/rdf/C, ?relateditem = http://www.xulplanet.com/rdf/D) A match has occured, so the content within the action
body will be created and added inside item C. Since the ?start variable points to item C and the ?relateditem variable points to D, the buttons will be created with these labels. If you look at the image of the example again, you will see that the buttons do have these labels. The resulting content for row C will look like this: <hbox id="http://www.xulplanet.com/rdf/C"> <button label="http://www.xu...
Simple Example - Archive of obsolete content
t/palace.jpg, ?title = 'Palace from Above') (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/canal.jpg, ?title = 'Canal') (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg, ?title = 'Obelisk') Since the triple is the last statement, three matches total have been found. The action
body might look like the following, which displays the image using its url and title in a label. You might note that the image's src attribute uses the member variable ?photo <action> <vbox uri="?photo" align="start"> <image src="?photo"/> <label value="?title"/> </vbox> </action> It shouldn't be too difficult to tell what would appear in the window in this example. You can see if you gu...
Template Logging - Archive of obsolete content
e. Only the 'rdf', 'xml' and 'storage' values are provided by default. If you are using a custom query processor, it may indicate that it is not installed or set up properly. unexpected <queryset> element A <queryset> element was placed in an invalid location; they should be placed directly inside the <template> element with no other kinds of elements as siblings. no member variable found. Action
body should have an element with uri attribute The member variable could not be determined. You should specify an element inside the first <action>
body with a uri attribute. You can also specify the member attribute on the template. Either way, the member variable isn't known so it isn't clear what value to use for each generated result id. <where> element is missing a subject attribute Every <where>...
XML Templates - Archive of obsolete content
expression used in the query, the attribute on the generated XML node is taken and substituted for the question mark and following string. In the above example, the use of the ?name value, causes the name attribute on each result node to be used as the value of the label. You can see the name attributes in the original XML data above. This substitution occurs for any attribute within the action
body, so you can also set other attributes with this technique. In this example, an hbox element containing a button and a label is generated for each result. <vbox datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"/> <action> <hbox uri="?" align="center"> <button label="?name"/> <label value="?gender"/> </hbox> </action> </t...
Things I've tried to do with XUL - Archive of obsolete content
has a bigger size than the window). You have no way of finding out what the clipped size is, so you can never shrink the content. An ugly workaround for this problem might include nesting an invisible HTML-Element in order to access its "clientWidth" method: <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> ... <html:
body id="invisible_element" flex="1" > <svg xmlns="http://www.w3.org/2000/svg" version="1.1"><!-- ...or _visible_ XUL content or whatever... --></svg> </html:
body> ... var available_width = document.getElementById("invisible_element").clientWidth; ... XBL in listboxes Using XBL bindings in listboxes is not easy because there is a big bug there: if you create from JS an element you want to bind, an...
Adding HTML Elements - Archive of obsolete content
You must add a html: prefix to the beginning of each tag, assuming you declared the HTML namespace as above. The tags must be entered in lowercase. "Quotes" must be placed around all attribute values. XML requires a trailing slash at the end of tags that have no content. This may be clearer from the examples below. Using HTML elements You can use any HTML tag although some such as head and
body are not really useful. Some examples of using HTML elements are shown below. <html:img src="banner.jpg"/> <html:input type="checkbox" value="true"/> <html:table> <html:tr> <html:td> A simple table </html:td> </html:tr> </html:table> These examples will create an image from the file banner.jpg, a checkbox and a single-cell table. You should always use XUL features if they are ...
Content Panels - Archive of obsolete content
he area where the web page is displayed is created by using an iframe. When the user enters a URL or clicks on a link in a document, the source of the frame is changed. 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. A box has been created containing two elements: a toolbox and an iframe. A Back button, a Forward button and a field for typing is URLs has been added to the only toolbar (We'll learn about toolbar in a later section). The web pages would appear inside the iframe. In this ...
Document Object Model - Archive of obsolete content
However, for various reasons, including better performance, you should always put scripts in separate files, except for short fragments which can be put directly in the event handler. function doFind(){ var meter = document.getElementById('progmeter'); meter.hidden = false; } This function first gets a reference to the progress meter using its id, progmeter. The second line of the function
body changes the hidden state so that the element is visible again. Finally, let's have an alert box pop up that displays what will be searched for. Of course, we wouldn't want this in the final version but we'll add it to reassure us that something would happen. function doFind(){ var meter=document.getElementById('progmeter'); meter.hidden = false; var searchtext=document.getElementById('fin...
Skinning XUL Files by Hand - Archive of obsolete content
slow. But the advantages of using XUL so far outweigh those of using the standard C++ toolkits that XUL authoring should rightfully be considered in a separate category of development. XUL represents, as one evangelist put it, the "democratization" of interface design and ofapplications development, about which we will have more to say in a later article. In short, XUL provides the tools for any
body to create interfaces as complex and as attractive as any C++/MFC/Visual IDE/Templates toolkit user's, and it does so in a way that makes these interfaces available on any platform. You don't have to know the vagueries of a "4GL" programming language or acquaint yourself with the innards of a particular platform and its native widgetry at the expense of others. XUL's technologies are interoperabl...
Tabboxes - Archive of obsolete content
five new elements, which are described briefly here and in more detail below. tabbox The outer box that contains the tabs along the top and the tab pages themselves. tabs The inner box that contains the individual tabs. In other words, this is the row of tabs. tab A specific tab. Clicking on the tab brings the tab page to the front. tabpanels The container for the pages. tabpanel The
body of a single page. You would place the content for a page within this element. The first tabpanel corresponds to the first tab, the second tabpanel corresponds to the second tab and so on. The tabbox is the outer element. It consists of two children, a tabs element which contains the row of tabs and a tabpanels elements which contains the tabbed pages. Shown below is the general syntax of a tab...
Using the Editor from XUL - Archive of obsolete content
document we opened. The editor is now set up, and ready to go. One thing to note about editor initialization is that we pass into the editor's Init() method an nsIContent* that corresponds to the root of the content tree that the editor is allowed to work with. When initializing the editor from the nsEditorShell, we pass NULL here (which tells the editor that it can edit everything under the <
body> of the document). This parameter is more important when the editor is in a text widget, where it points to the the subtree of the parent document that corresponds to widget content. Editor teardown Window destruction, and hence editor teardown is initiated in two ways, listed below. In both cases, the EditorCanClose() method is the JavaScript is called, which causes the nsEditorShell to dis...
The Implementation of the Application Object Model - Archive of obsolete content
e (thus allowing local changes to a local file to be reflected right in the XUL). Referencing local data: The LOCALDATA attribute A tag that references local RDF data does so by using the localData attribute, which gives the URI of the local data that should be merged in with the XUL content tree. Examples of tags that can reference local data are menu, menuitem, menubar, toolbox, toolbar, tree
body, and treeitem. TODO: Outline the naming scheme for local data. Give an example once I actually know what the naming scheme will be. Talk to John McMullen about 5.0 preferences and figure out where LOCALDATA will need to be used (likely on every form element control) Talk to Steve Elmer. It's likely that this might be the desirable solution for buttons that observe preferences (like the HOME b...
rule - Archive of obsolete content
amples | Attributes | Properties | Methods | Related ] A rule is used in a template. The children of the rule are used to declare the conditions in which the rule matches and the content that is generated. A rule may contain where, binding and/or action elements. A condition is defined used a where element. For each result that matches all of the conditions, content within the rule's action
body is generated. The bindings element is optional and may specify additional variable bindings to be used. When no query element is used in a template, a default query is used and the simple query syntax may be used for RDF datasources. For more information about this, see the Simple Query Syntax. Attributes iscontainer, isempty, parent, parsetype Examples (example needed) Attributes ...
template - Archive of obsolete content
tainer Type: string May optionally be set to the variable to use as the container or reference variable. If not specified, the variable specified in the uri attribute of the content tag in the template's first rule is used. member Type: string May optionally be set to the variable to use as the member variable. If not specified, the variable specified in the uri attribute in the action
body of the template's first rule is used. 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,...
treechildren - Archive of obsolete content
For content trees, the content will be placed inside this element. This element is also used to define container rows in the tree. More information is available in the XUL tutorial. Attributes alternatingbackground Attributes alternatingbackground Obsolete since Gecko 2.0 Type: boolean If true, the background of the tree's rows will alternate between two colors. You can use the :-moz-tree-row CSS style to do this instead. ...
where - Archive of obsolete content
For more information, see Where Elements. 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. ...
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
p/myapplication.xpi The application will be installed to /usr/lib/vendor/applicationname Known Issues Firewall software may identify all XUL applications as the same application. On Microsoft Windows XP, all XUL applications may wind up being grouped together in the taskbar. Frequently Asked Questions Why is installing XULRunner so painful? Why isn't there a nice installer? Because no
body has written that code yet! This is a developer preview release: additional features for installing and deploying XULRunner and applications based on XULRunner will be available in future releases. I'm writing a XUL application, how can I deploy that application to my users? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner ...
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
myapplication.xpi The application will be installed to /usr/lib/vendor/applicationname Known Issues Firewall software may identify all XUL applications as the same application. On Microsoft Windows XP, all XUL applications may wind up being grouped together in the taskbar. Frequently Asked Questions Why is installing XULRunner so painful? Why isn't there a nice installer? Because no
body has written that code yet! This is a developer preview release: additional features for installing and deploying XULRunner and applications based on XULRunner will be available in future releases. I'm writing a XUL application, how can I deploy that application to my users? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner...
XULRunner 1.9.1 Release Notes - Archive of obsolete content
cation.xpi The application will be installed to /usr/lib/vendor/applicationname Known Issues Firewall software may identify all XUL applications as the same application. On Microsoft Windows XP, all XUL applications may wind up being grouped together in the taskbar. Frequently Asked Questions Why is installing XULRunner so painful? Why isn't there a nice installer? Because no
body has written that code yet! Additional features for installing and deploying XULRunner and applications based on XULRunner will be available in future releases. I'm writing a XUL application, how can I deploy that application to my users? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner for more information. ...
XULRunner 1.9.2 Release Notes - Archive of obsolete content
~/Desktop/myapplication.xpi The application will be installed to /usr/lib/vendor/applicationname Known Issues Firewall software may identify all XUL applications as the same application. On Microsoft Windows XP, all XUL applications may wind up being grouped together in the taskbar. Frequently Asked Questions Why is installing XULRunner so painful? Why isn't there a nice installer? Because no
body has written that code yet! Additional features for installing and deploying XULRunner and applications based on XULRunner will be available in future releases. I'm writing a XUL application, how can I deploy that application to my users? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner for more information. Where is the source...
XULRunner 1.9 Release Notes - Archive of obsolete content
p/myapplication.xpi The application will be installed to /usr/lib/vendor/applicationname Known Issues Firewall software may identify all XUL applications as the same application. On Microsoft Windows XP, all XUL applications may wind up being grouped together in the taskbar. Frequently Asked Questions Why is installing XULRunner so painful? Why isn't there a nice installer? Because no
body has written that code yet! Additional features for installing and deploying XULRunner and applications based on XULRunner will be available in future releases. I'm writing a XUL application, how can I deploy that application to my users? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner for more information. Where is the sou...
XULRunner 2.0 Release Notes - Archive of obsolete content
~/Desktop/myapplication.xpi The application will be installed to /usr/lib/vendor/applicationname Known Issues Firewall software may identify all XUL applications as the same application. On Microsoft Windows XP, all XUL applications may wind up being grouped together in the taskbar. Frequently Asked Questions Why is installing XULRunner so painful? Why isn't there a nice installer? Because no
body has written that code yet! Additional features for installing and deploying XULRunner and applications based on XULRunner will be available in future releases. I'm writing a XUL application, how can I deploy that application to my users? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner for more information. Where is the source...
XULRunner FAQ - Archive of obsolete content
lled libXUL, mostly the name is a hangover from that that has now stuck. When will Firefox be based on XULRunner? There is no intention to do this for official release versions of Firefox. It is already possible to run Firefox on XULRunner now though and certain Linux distributions already do this. Why is installing XULRunner so painful? Why isn't there a nice installer? Because no
body has written that code yet! This is a developer preview release: additional features for installing and deploying XULRunner and applications based on XULRunner will be available in future releases. I'm writing a XUL application, how can I deploy that application to my users? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRun...
reftest opportunities files - Archive of obsolete content
er/htmlparser/tests/html/utf8001.html parser/htmlparser/tests/html/usascii.html parser/htmlparser/tests/html/title01.html parser/htmlparser/tests/html/title.html parser/htmlparser/tests/html/tiny.html parser/htmlparser/tests/html/thead001.html parser/htmlparser/tests/html/text003.html parser/htmlparser/tests/html/text002.html parser/htmlparser/tests/html/text001.html parser/htmlparser/tests/html/t
body001.html parser/htmlparser/tests/html/target01.html parser/htmlparser/tests/html/tag008.html parser/htmlparser/tests/html/tag007.html parser/htmlparser/tests/html/tag006.html parser/htmlparser/tests/html/tag005.html parser/htmlparser/tests/html/tag004.html parser/htmlparser/tests/html/tag003.html parser/htmlparser/tests/html/tag002.html parser/htmlparser/tests/html/tag001.html parser/htmlparser/te...
Extentsions FAQ - Archive of obsolete content
s for the feed to appear as a livemark are seemingly present and properly formatted in the feeds source? Asking for help in knowing the data that is typed into text boxes. Asking about the feasibility of making an extension that has the same functionality as "trace route". Friday, September 29 - October 6, 2006 (? top) How can we programmatically extract the subject, sender, date and the
body of an e- mail when you are reading one (in Thunderbird presumably)? Could someone make an addressbook enhancer extension that has the ability to put pictures on a contact and other features the Thunderbird address book lacks. Is there a way to save a whole news thread in Thunderbird? Is there some workaround for the timing issue with Windows and Linux? Friday, October 6 - 13, 2006 (? t...
NPN_PostURL - Archive of obsolete content
m submission), mail (sending mail), news (posting a news article), and FTP (upload a file). Plug-ins can use this function to post form data to CGI scripts using HTTP or upload files to a remote server using FTP. You cannot use NPN_PostURL to specify headers (even a blank line) in a memory buffer. To do this, use NPN_PostURLNotify. For protocols in which the headers must be distinguished from the
body, such as HTTP, the buffer or file should contain the headers, followed by a blank line, then the
body. If no custom headers are required, simply add a blank line ('\n') to the beginning of the file or buffer. NPN_PostURL is typically asynchronous: it returns immediately and only later handles the request. For this reason, you may find it useful to call NPN_PostURLNotify instead; this function not...
Introduction to Public-Key Cryptography - Archive of obsolete content
can authenticate. An administrator can implement some aspects of corporate security policies by controlling the CA certificates stored in each user's copy of Firefox. Contents of a Certificate The contents of certificates are organized according to the X.509 v3 certificate specification, which has been recommended by the International Telecommunications Union (ITU), an international standards
body, since 1988. Users don't usually need to be concerned about the exact contents of a certificate. However, system administrators working with certificates may need some familiarity with the information provided here. Certificate Data Formats Certificate requests and certificates can be created, stored, and installed in multiple formats: binary and text. All of these formats conform to X.509 sta...
Using Firebug and jQuery (Screencast) - Archive of obsolete content
ry affords you, using the results to build a Greasemonkey script, instead of a simple bookmarklet. I only really intended this to be a quick introduction to the subject, so please feel free to explore it more! More Tips: Here are some more jQuery selectors that you can use on a Digg Post: $("li.c-bury > div").remove(); - Remove all buried comments, but none of the direct replies. $("div.c-
body").show(); - Show all comments, even ones that've been buried. ...
-ms-accelerator - Archive of obsolete content
keyboard shortcut. When the option to "Hide keyboard navigation indicators until I use the Alt key" is enabled in the user's Display Properties, the "N" is not underlined until the user presses the Alt key. When Alt + N is pressed, the <input> element that defines an accesskey attribute value of "N" receives the focus. <!DOCTYPE html> <html> <head> <title>Accelerator</title> </head> <
body> <label for="oName"><u style="-ms-accelerator: true; accelerator: true">N</u>ame: </label> <input type="text" id="oName" size="25" accesskey="N" value="Your name here" /> </
body> </html> Specifications Not part of any specification. Remarks This property is supported by Windows 2000 and later. It enables users to hide navigation indicators for menu items and...
-ms-scrollbar-3dlight-color - Archive of obsolete content
-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. */ } </style> </head> <
body> <textarea class="Blue3dLight">The top and left edges of the thumb and button-face elements in the scroll bar for this element will be blue.</textarea> </
body> </html> Specifications Not part of any specification. ...
-ms-scrollbar-darkshadow-color - Archive of obsolete content
ing 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-scrollbar-highlight-color - Archive of obsolete content
rder-width: thin; overflow-y: scroll; font-family: sans-serif; float: left; margin-right: 10px; } .blueScroll { -ms-scrollbar-highlight-color: aqua; -ms-scrollbar-face-color: blue; -ms-scrollbar-arrow-color: blue; border-color: blue; } .redScroll { -ms-scrollbar-highlight-color: bisque; -ms-scrollbar-face-color: red; -ms-scrollbar-arrow-color: red; border-color: red; } <
body> <div class="blueScroll"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> <div class="redScroll"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> </
body> This image shows t...
-ms-scrollbar-track-color - Archive of obsolete content
der-width: thin; overflow-y: scroll; font-family: sans-serif; float: left; margin-right: 10px; } .blueScroll { -ms-scrollbar-highlight-color: aqua; -ms-scrollbar-face-color: blue; -ms-scrollbar-arrow-color: blue; border-color: blue; } .redScroll { -ms-scrollbar-highlight-color: bisque; -ms-scrollbar-face-color: red; -ms-scrollbar-arrow-color: red; border-color: red; } <
body> <div class="blueScroll"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> <div class="redScroll"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </div> </
body> The following ima...
-moz-windows-accent-color-in-titlebar - Archive of obsolete content
sed to apply styles based on whether accent colors are enabled in Microsoft Windows titlebars. Syntax <integer> In recent Windows versions (e.g., 10), if accent colors are enabled in window titlebars, this is 1. Otherwise it's 0. 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; } } ...
Expression closures - Archive of obsolete content
and has been removed starting with Firefox 60. For future-facing usages, consider using arrow functions. Expression closures are a shorthand function syntax for writing simple functions. Syntax function [name]([param1[, param2[, ..., paramN]]]) expression Parameters name The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function
body. paramN The name of an argument to be passed to the function. A function can have up to 255 arguments. expression The expression which comprise the
body of the function. Description This addition is nothing more than a shorthand for writing simple functions, giving the language something similar to a typical Lambda notation. JavaScript 1.7 and older: function(x) { return x * x; } JavaSc...
Legacy generator function expression - Archive of obsolete content
The legacy generator function expression was a SpiderMonkey-specific feature, which is removed in Firefox 58+. For future-facing usages, consider using the function* expression. The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function
body should contain at least one yield expression. Syntax function [name]([param1[, param2[, ..., paramN]]]) { statements } Parameters name The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function
body. paramN The name of an argument to be passed to the function. A function can have up to 255 arguments. statements The statements which comprise the
body of the function. This should contain at ...
Legacy generator function - Archive of obsolete content
The legacy generator function was a SpiderMonkey-specific feature, which is removed in Firefox 58+. For future-facing usages, consider using function*. The legacy generator function statement declares legacy generator functions with the specified parameters. You can also define functions using the Function constructor with function
Body and at least one yield expression, and a legacy generator function expression. Syntax function name([param,[, param,[..., param]]]) { [statements] } name The function name. param The name of an argument to be passed to the function. A function can have up to 255 arguments. statements The statements which comprise the
body of the function. This should contain at least one yield expression. Description An overview of the usag...
Archived JavaScript Reference - Archive of obsolete content
has been removed from the ECMAScript standard in ES2016 and is deprecated in browsers.Legacy generator functionThe legacy generator function statement declares legacy generator functions with the specified parameters.Legacy generator function expressionThe function keyword can be used to define a legacy generator function inside an expression. ...
Properly Using CSS and JavaScript in XHTML Documents - Archive of obsolete content
ote 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. Use of Comments Inside Inline style and script Authors who are familiar with HTML commonly enclose the contents of inline style and script tags in comments in order to hide the contents of the tags from browsers which do not understand them. <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 conte...
Reference - Archive of obsolete content
ects of the class Date, and thus is an instance of both Object and Function, whereas Math is merely an instanceof Object. --Sevenspade 14:23, 17 January 2007 (PST) New JavaScript features, such as "for each...in" This page doesn't mention Core_JavaScript_1.5_Reference:Statements:for_each...in. The for each...in loop should either be listed on this page or moved to a different category. And some
body should see if there are other features in the same situation. HeroreV 00:49, 27 October 2006 (PDT) Since the for each...in loop is a 1.6 feature (not a 1.5 feature), maybe someone should rename this page/category to be either a general JavaScript Reference or update it to be the 1.6 Reference. Having 1.6 features defined in the 1.5 reference might be confusing. cstevens 10:23, 20 December 2006 (...
Writing JavaScript for XHTML - Archive of obsolete content
, as long as you keep the namespace problem in focus (e.g., there is a document.createElementNS method). Of course, you can still use strings like in document.write(), but it takes a little more effort. 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 you with a parser error. Problem: I want to remain forward compatible! Given the direction away from formatting attributes and the possibility of XHTML becoming eventually more prominent...
XForms Repeat Element - Archive of obsolete content
-moz-binding: url('#grid'); } </style> <xf:model> <xf:instance> <data xmlns=""> <repeat> <item> <input>Input1</input> </item> <item> <input>Input2</input> </item> <item> <input>Input3</input> </item> </repeat> </data> </xf:instance> </xf:model> </head> <
body> <xf:repeat nodeset="/data/repeat/item" id="gridRepeat"> <xf:input ref="input"/> </xf:repeat> <br/> <div class="grid" nodeset="/data/repeat/item"/> </
body> ...
Popup Window Controls - Archive of obsolete content
setTimeout() or setInterval() will return null rather than a reference to the opened window. <html> <head> <title>Detecting Popup Controls</title> <script type="text/javascript"> <!-- // attempt to open an unsolicited window var popup = window.open('about:blank', 'popup'); if (!popup) { // the user has suppressed the popup } // --> </script> </head> <
body> <!-- your page here --> </
body> </html> If your popup window is crucial to the operation of your web site you can notify the user and ask them to add your site to the list of sites which are allowed to use unsolicited popup windows. You can also provide a hyperlink which can be used to open a popup window even in the event that the user has suppressed unsolicited popups on your site. Repl...
The Business Benefits of Web Standards - Archive of obsolete content
ng the production process, time, budgets, and resources for both the initial development and the ongoing publishing of emerging content can be measured and controlled. This is a very powerful management tool. This is the power of Web Standards. It supplies a far better development framework, for content providers, for web developers, and for CSS stylists alike. It is simply not possible for every
body not to gain and share in the huge benefits of Standards. Customers, developers, digital media creators, can be freed from the tyranny of graphics led development, code generators, and incomprehensible markup. But the real value is at the bottom line. The message to accountants, executives and shareholders alike should be irresistible. Benefits of CSS over JavaScript Specifically, graphics and...
3D collision detection - Game development
nce = Math.sqrt((x - sphere.x) * (x - sphere.x) + (y - sphere.y) * (y - sphere.y) + (z - sphere.z) * (z - sphere.z)); return distance < sphere.radius; } Using a physics engine 3D physics engines provide collision detection algorithms, most of them based on bounding volumes as well. The way a physics engine works is by creating a physical
body, usually attached to a visual representation of it. This
body has properties such as velocity, position, rotation, torque, etc., and also a physical shape. This shape is the one that is considered in the collision detection calculations. We have prepared a live collision detection demo (with source code) that you can take a look at to see such techniques in action -- this uses the open-source 3D...
Unconventional controls - Game development
an look at. To get the Leap Motion working on your computer you have to first install it by following the steps at leapmotion.com/setup. When everything is installed and the controller is connected to your computer we can proceed with implementing support in our little demo. First, we add a <script> tag with the url pointing at this file, and add <div id="output"></div> just before the closing </
body> tag for outputting diagnostic information. We will need a few helper variables for our code to work -- one for the purpose of calculating the degrees from radians, two for holding the horizontal and vertical amount of degrees our hand is leaning above the controller, one for the threshold of that lean, and one for the state of our hand's grab status. We next add these lines after all the event ...
Create the Canvas and draw on it - Game development
e <canvas> element. Using your favourite text editor, create a new HTML document, save it as index.html, in a sensible location, and add the following code to it: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Gamedev Canvas Workshop</title> <style> * { padding: 0; margin: 0; } canvas { background: #eee; display: block; margin: 0 auto; } </style> </head> <
body> <canvas id="myCanvas" width="480" height="320"></canvas> <script> // JavaScript code goes here </script> </
body> </html> We have a charset defined, <title> and some basic CSS in the header. The
body contains <canvas> and <script> elements -- we will render the game inside the first one and write the JavaScript code that controls it in the second one. The <canvas> element has an id of myCan...
Bounce off the walls - Game development
k at the walls. Bouncing off the world boundaries The easiest way to get our ball bouncing off the walls is to tell the framework that we want to treat the boundaries of the <canvas> element as walls and not let the ball move past them. In Phaser this can be easily accomplished using the collideWorldsBound property. Add this line right after the existing game.physics.enable() method call: ball.
body.collideWorldBounds = true; Now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. To make this occur we have to set its bounciness. Add the following line below the previous one: ball.
body.bounce.set(1); Try reloading index.html again -- now you should see the ball bouncing off all the walls and moving inside the canvas area. Compare your code You ...
Buttons - Game development
pressed A reference to this to specify the execution context The frames that will be used for the over, out and down events. Note: The over event is the same as hover, out is when the pointer moves out of the button and down is when the button is pressed. Now we need to define the startGame() function referenced in the code above: function startGame() { startButton.destroy(); ball.
body.velocity.set(150, -150); playing = true; } When the button is pressed, we remove the button, sets the ball's initial velocity and set the playing variable to true. Finally for this section, go back into your create() function, find the ball.
body.velocity.set(150, -150); line, and remove it. You only want the ball to move when the button is pressed, not before! Keeping the paddle still bef...
Randomizing gameplay - Game development
n this article we'll look at how. Making rebounds more random We can change the ball's velocity depending on the exact spot it hits the paddle, by modifying the x velocity each time the ballHitPaddle() function is run using a line along the lines of the below. Add this new line to your code now, and try it out. function ballHitPaddle(ball, paddle) { ball.animations.play('wobble'); ball.
body.velocity.x = -1*5*(paddle.x-ball.x); } It's a little bit of magic -- the new velocity is higher, the larger the distance between the center of the paddle and the place where the ball hits it. Also, the direction (left or right) is determined by that value -- if the ball hits the left side of the paddle it will bounce left, whereas hitting the right side will bounce it to the right. It ended up t...
Request header - MDN Web Docs Glossary: Definitions of Web-related terms
the content of the message. Request headers, like Accept, Accept-*, or If-* allow to perform conditional requests; others like Cookie, User-Agent, or Referer precise the context so that the server can tailor the answer. Not all headers appearing in a request are request headers. 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. However, these entity headers are often called request headers in such a context. In addition, CORS defines a subset of request headers as simple headers, request headers that are always considered authorized and are not explicitly listed in responses to preflight requests. A few request headers after a GET request: GET /home.html HTTP/1.1 Host: developer.mozilla.org Us...
Response header - MDN Web Docs Glossary: Definitions of Web-related terms
A response header is an HTTP header that can be used in an HTTP response and that doesn't relate to the content of the message. Response headers, like Age, Location or Server are used to give a more detailed context of the response. Not all headers appearing in a response are response headers. For example, the Content-Length header is an entity header referring to the size of the
body of the response message. However, these entity requests are usually called responses headers in such a context. The following shows a few response headers after a GET request. Note that strictly speaking, the Content-Encoding and Content-Type headers are entity header: 200 OK Access-Control-Allow-Origin: * Connection: Keep-Alive Content-Encoding: gzip Content-Type: text/html; charset=utf-8 Date: Mon, 1...
W3C - MDN Web Docs Glossary: Definitions of Web-related terms
It consists of over 350 member-organizations that jointly develop Web standards, run outreach programs, and maintain an open forum for talking about the Web. The W3C coordinates companies in the industry to make sure they implement the same W3C standards. Each standard passes through four stages of maturity: Working Draft (WD), Candidate Recommendation (CR), Proposed Recommendation (PR), and W3C Recommendation (REC). ...
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
sh your writing with a carriage return. <script>document.write("Hello World!\r");</script> is bad. <script>document.write("Hello World!\n");</script> is OK. Note that writing balanced tags may cause other tags to be inferred in a way that makes the write unbalanced. E.g. <script>document.write("<div></div>");</script> inside the head element will be interpreted as <script>document.write("</head><
body><div></div>");</script> which is unbalanced. Don't format part of a table. <table><script>document.write("<tr><td>Hello World!</td></tr>");</script></table> is bad. ...
CSS and JavaScript accessibility best practices - Learn web development
e: <h1>Heading</h1> <p>Paragraph</p> <ul> <li>My list</li> <li>has two items.</li> </ul> Some typical CSS might look like this: h1 { font-size: 5rem; } p, li { line-height: 1.5; font-size: 1.6rem; } You should: Select sensible font sizes, line heights, letter spacing, etc. to make your text logical, legible, and comfortable to read. Make sure your headings stand out from your
body text, typically big and bold like the default styling. Your lists should look like lists. Your text color should contrast well with your background color. See HTML text fundamentals and Styling text for more information. Emphasised text Inline markup that confers specific emphasis to the text that it wraps: <p>The water is <em>very hot</em>.</p> <p>Water droplets collecting on surfaces is ...
Cascade and inheritance - Learn web development
rst has styling applied to the blockquote element itself, the second has a class applied to the blockquote which sets the value of all to unset. Try setting the value of all to some of the other available values and observe what the difference is. Understanding the cascade We now understand why a paragraph nested deep in the structure of your HTML is the same color as the CSS applied to the
body, and from the introductory lessons we have an understanding of how to change the CSS applied to something at any point in the document -- whether by assigning CSS to an element or creating a class. We will now take a proper look at how the cascade defines which CSS rules apply when more than one thing could style an element. There are three factors to consider, listed here in increasing order of...
Images, media, and form elements - Learn web development
ered by the operating system and are inaccessible to styling. You should therefore always assume that forms are going to look quite different for different visitors and test complex forms in a number of browsers. Inheritance and form elements In some browsers, form elements do not inherit font styling by default. Therefore if you want to be sure that your form fields use the font defined on the
body, or on a parent element, you should add this rule to your CSS. button, input, select, textarea { font-family : inherit; font-size : 100%; } Form elements and box-sizing Across browsers form elements use different box sizing rules for different widgets. You learned about the box-sizing property in our box model lesson and you can use this knowledge when styling forms to ensure a consistent...
Organizing your CSS - Learn web development
back to this project in a year or so, and can vaguely remember there was a great tutorial about that thing, but where is it? Create logical sections in your stylesheet It is a good idea to have all of the common styling first in the stylesheet. This means all of the styles which will generally apply unless you do something special with that element. You will typically have rules set up for:
body p h1, h2, h3, h4, h5 ul and ol The table properties Links In this section of the stylesheet we are providing default styling for the type on the site, setting up a default style for data tables and lists and so on. /* || GENERAL STYLES */
body { ... } h1, h2, h3, h4 { ... } ul { ... } blockquote { ... } After this section we could define a few utility classes, for example a class th...
Combinators - Learn web development
Descendant combinator The descendant combinator -- typically represented by a single space ( ) character -- combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc) element matching the first selector. Selectors that utilize a descendant combinator are called descendant selectors.
body article p In the example below, we are matching only the <p> element which is inside an element with a class of .box. Child combinator The child combinator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Descendent elements further down the hierarchy don't match. For example...
Normal Flow - Learn web development
pan>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. ...
Styling lists - Learn web development
t of 1.5 of their font-size. Give the ordered list lower alphabetical bullets. Feel free to play with the list example as much as you like, experimenting with bullet types, spacing, or whatever else you can find. If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see a potential answer. ...
Web fonts - Learn web development
eb-font-start.html and web-font-start.css files as a starting point to add your code to (see the live example). Make a copy of these files in a new directory on your computer now. In the web-font-start.css file, you'll find some minimal CSS to deal with the basic layout and typesetting of the example. Finding fonts For this example, we'll use two web fonts, one for the headings, and one for the
body text. To start with, we need to find the font files that contain the fonts. Fonts are created by font foundries and are stored in different file formats. There are generally three types of sites where you can obtain fonts: A free font distributor: This is a site that makes free fonts available for download (there may still be some license conditions, such as crediting the font creator). Exampl...
Advanced form styling - Learn web development
le. If you are prepared to live with some differences in look and feel, you can get away with some simple styling to make sizing consistent, uniform styling of things like background-colors, and usage of appearence to get rid of some system-level styling. ...
UI pseudo-classes - Learn web development
Then we give the generated content the content "required", which is what we wanted our label to say, and style and position it as we want. The result is seen below. Styling controls based on whether their data is valid The other really important, fundamental concept ...
Your first form - Learn web development
east the action and method attributes: The action attribute defines the location (URL) where the form's collected data should be sent when it is submitted. The method attribute defines which HTTP method to send the data with (usually get or post). Note: We'll look at how those attributes work in our Sending form data article later on. For now, add the above <form> element into your HTML <
body>. The <label>, <input>, and <textarea> elements Our contact form is not complex: the data entry portion contains three text fields, each with a corresponding <label>: The input field for the name is a single-line text field. The input field for the e-mail is an input of type email: a single-line text field that accepts only e-mail addresses. The input field for the message is a <textarea>;...
Dealing with files - Learn web development
ll your website look like?" Copy the image you chose earlier into your images folder. Open up your index.html file, and insert the following code into the file exactly as shown. Don't worry about what it all means for now -- we'll look at the structures in more detail later in the series. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My test page</title> </head> <
body> <img src="" alt="My test image"> </
body> </html> The line <img src="" alt="My test image"> is the HTML code that inserts an image into the page. We need to tell the HTML where the image is. The image is inside the images directory, which is in the same directory as index.html. To walk down the file structure from index.html to our image, the file path we'd need is images/your-image-fil...
The web and web standards - Learn web development
ow HTML (all the HTML elements, and their associated APIs, and other surrounding technologies) should be implemented. Web standards are created by standards bodies -- institutions that invite groups of people from different technology companies to come together and agree on how the technologies should work in the best way to fulfill all of their use cases. The W3C is the best known web standards
body, but there are others such as the WHATWG (who were responsible for the modernization of the HTML language), ECMA (who publish the standard for ECMAScript, which JavaScript is based on), Khronos (who publish technologies for 3D graphics, such as WebGL), and others. "Open" standards One of the key aspects of web standards, which TimBL and the W3C agreed on from the start, is that the web (and web...
HTML Cheatsheet - Learn web development
Some elements are large and hold smaller elements like containers. Some elements are small and are "nested" inside larger ones. By default, "inline elements" appear next to one another in a webpage. They take up only as much width as they need in a page and fit together horizontally like words in a sentence or books shelved side-by-side in a row.All inline elements can be implemented within the <
body></
body> tags. Usage Code snippet Result A simple link <a href="https://realityripple.com/">A link to RealityRipple</a> A link to RealityRipple A simple image <img src="https://udn.realityripple.com/samples/6e/d6ed76c6c7.png" width="25" /> A generic inline container <p>p its used to <span style="color:blue">style and group</span> parti...
Add a hitmap on top of an image - Learn web development
or writing accessible link text. You may write alt="" if the href attribute is blank and the entire image already has an alt attribute. <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 every
body You aren't done until you test image maps rigorously on many browsers and devices. Try following links with your keyboard alone. Try turning images off. If your image map is wider than about 240px, you'll need to make further adjustments to make your website responsive. It's not enough to resize the image for small screens, because the coordinates stay the same and no longer match the image. I...
Tips for authoring fast-loading HTML pages - Learn web development
er of files for performance while keeping unrelated CSS in separate files for maintenance. . <script> ... JavaScript files for functions required during the loading of the page, but not any interaction related JavaScript that can only run after page loads. Minimize the number of files for performance while keeping unrelated JavaScript in separate files for maintenance. . <
body> . User visible page content in small chunks ( <header>/ <main>/ <table>) that can be displayed without waiting for the full page to download. . <script> ... Any scripts which will be used to perform interactivity. Interaction scripts typically can only run after the page has completely loaded and all necessary objects have been initialized. There is no need to load these scripts befo...
Use JavaScript within a webpage - Learn web development
ons) might break your scripts. At a minimum, leave a short message with <noscript> like this: <noscript>To use this site, please enable JavaScript.</noscript> Ideally, replicate the JavaScript functionality with HTML and server-side scripting when possible. If you're only looking for simple visual effects, CSS can often get the job done even more intuitively. Since almost every
body does have JavaScript enabled, <noscript> is no excuse for writing inaccessible scripts. Learn more <script> <noscript> James Edwards' introduction to using JavaScript accessibly Accessibility guidelines from W3C ...
Marking up a letter - Learn web development
urther help section at the bottom of this page. Project brief For this project, your task is to mark up a letter that needs to be hosted on a university intranet. The letter is a response from a research fellow to a prospective PhD student concerning their application to the university. Block/structural semantics Use appropriate document structure including doctype, and <html>, <head> and <
body> elements. In general, the letter should be marked up as an organization of headings and paragraphs, with the following exception. There is one top level heading (the "Re:" line) and three second level headings. Use an appropriate list type to mark up the semester start dates, study subjects, and exotic dances. Put the two addresses inside <address> elements. Each line of the address should s...
Mozilla splash page - Learn web development
fore they're ready to be used. Alternatively, you could use an online tool such as Glitch to create your example. This would also be useful if you want to get it assessed, or ask for help -- see the Assessment or further help section at the bottom of this page. Note: The example HTML file contains quite a lot of CSS, to style the page. You don't need to touch the CSS, just the HTML inside the <
body> element -- as long as you insert the correct markup, the styling will make it look correct. Project brief In this assessment we are presenting you with a mostly-finished Mozilla splash page, which aims to say something nice and interesting about what Mozilla stands for, and provide some links to further resources. Unfortunately, no images or video have been added yet -- this is your job! You ...
HTML table basics - Learn web development
k across a variety of devices. Active learning: Creating your first table We've talked table theory enough, so, let's dive into a practical example and build up a simple table. First of all, make a local copy of blank-template.html and minimal-table.css in a new directory on your local machine. The content of every table is enclosed by these two tags : <table></table>. Add these inside the
body of your HTML. The smallest container inside a table is a table cell, which is created by a <td> element ('td' stands for 'table data'). Add the following inside your table tags: <td>Hi, I'm your first cell.</td> If we want a row of four cells, we need to copy these tags three times. Update the contents of your table to look like so: <td>Hi, I'm your first cell.</td> <td>I'm your second ce...
Assessment: Structuring planet data - Learn web development
) Steps to complete The following steps describe what you need to do to complete the table example. All the data you'll need is contained in the planets-data.txt file. If you have trouble visualising the data, look at the live example above, or try drawing a diagram. Open your copy of blank-template.html, and start the table off by giving it an outer container, a table header, and a table
body. You don't need a table footer for this example. Add the provided caption to your table. Add a row to the table header containing all the column headers. Create all the content rows inside the table
body, remembering to make all the row headings into headings semantically. Ensure all the content is placed into the right cells -- in the raw data, each row of planet data is shown next to its as...
HTML Tables - Learn web development
cle gets you started with HTML tables, covering the very basics such as rows and cells, headings, making cells span multiple columns and rows, and how to group together all the cells in a column for styling purposes. HTML table advanced features and accessibility This module looks at some more advanced features of HTML tables -- such as captions/summaries and grouping your rows into table head,
body and footer sections -- as well as looking at the accessibility of tables for visually impaired users. Assessments Structuring planet data In our table assessment, we provide you with some data on the planets in our solar system, and get you to structure it into an HTML table. ...
Index - Learn web development
a Assessment, Beginner, CodingScripting, HTML, Learn, Tables In our table assessment, we provide you with some data on the planets in our solar system, and get you to structure it into an HTML table. 228 HTML table advanced features and accessibility Accessibility, Advanced, Article, Beginner, CodingScripting, HTML, Headers, Learn, caption, nesting, scope, sumary, table, t
body, tfoot, thead There are a few other things you could learn about table HTML, but we have really given all you need to know at this moment in time. At this point, you might want to go and learn about styling HTML tables -- see Styling Tables. 229 HTML table basics Article, Beginner, CodingScripting, HTML, Learn, Tables, basics, cell, col, colgroup, colspan, header, row, rowspa...
Build your own function - Learn web development
ction To begin with, let's put together a basic function. Note: For function naming conventions, you should follow the same rules as variable naming conventions. This is fine, as you can tell them apart -- function names appear with parentheses after them, and variables don't. Start by accessing the function-start.html file and making a local copy. You'll see that the HTML is simple -- the
body contains just a single button. We've also provided some basic CSS to style the custom message box, and an empty <script> element to put our JavaScript in. Next, add the following inside the <script> element: function displayMessage() { } We start off with the keyword function, which means we are defining a function. This is followed by the name we want to give to our function, a set of pare...
Image gallery - Learn web development
feel free to put them inline <script>/<style> elements inside the HTML page. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief You have been provided with some HTML, CSS and image assets and a few lines of JavaScript code; you need to write the necessary JavaScript to turn this into a working program. ...
Fetching data from the server - Learn web development
ts.text().then(function(text) { poemDisplay.textContent = text; }); }); But it makes more sense to call the parameter something that describes its contents. Now let's focus just on the function: function(response) { response.text().then(function(text) { poemDisplay.textContent = text; }); } The response object has a method text() that takes the raw data contained in the response
body and turns it into plain text -- the format we want it in. It also returns a promise (which resolves to the resulting text string), so here we use another .then(), inside of which we define another function that dictates what we want to do with that text string. We are just setting the textContent property of our poem's <pre> element to equal the text string, so this works out pretty simple. It i...
Third-party APIs - Learn web development
a request to it. We'll do this using the Fetch API. Add the following code block inside the fetchResults() function, just above the closing curly brace: // Use fetch() to make the request to the API fetch(url).then(function(result) { return result.json(); }).then(function(json) { displayResults(json); }); Here we run the request by passing our url variable to fetch(), convert the response
body to JSON using the json() function, then pass the resulting JSON to the displayResults() function so the data can be displayed in our UI. Displaying the data OK, let's look at how we'll display the data. Add the following function below your fetchResults() function. function displayResults(json) { while (section.firstChild) { section.removeChild(section.firstChild); } const article...
Video and Audio APIs - Learn web development
,255,0.2); left: 0; top: 0; width: 0; height: 38px; z-index: 2; } .timer span { position: absolute; z-index: 3; left: 19px; } We set the outer .timer <div> to have flex: 5, so it takes up most of the width of the controls bar. We also give it position: relative, so that we can position elements inside it conveniently according to it's boundaries, and not the boundaries of the <
body> element. The inner <div> is absolutely positioned to sit directly on top of the outer <div>. It is also given an initial width of 0, so you can't see it at all. As the video plays, the width will be increased via JavaScript as the video elapses. The <span> is also absolutely positioned to sit near the left hand side of the timer bar. We also give our inner <div> and <span> the right amount of...
Basic math in JavaScript — numbers and operators - Learn web development
steps Next At this point in the course we discuss math in JavaScript -- how we can use operators and other features to successfully manipulate numbers to do our bidding. Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is. Objective: To gain familiarity with the basics of math in JavaScript. Every
body loves math Okay, maybe not. Some of us like math, some of us have hated math ever since we had to learn multiplication tables and long division in school, and some of us sit somewhere in between the two. But none of us can deny that math is a fundamental part of life that we can't get very far without. This is especially true when we are learning to program JavaScript (or any other language for ...
What went wrong? Troubleshooting JavaScript - Learn web development
ng : after property id This error usually relates to an incorrectly formed JavaScript object, but in this case we managed to get it by changing function checkGuess() { to function checkGuess( { This has caused the browser to think that we are trying to pass the contents of the function into the function as an argument. Be careful with those parentheses! SyntaxError: missing } after function
body This is easy -- it generally means that you've missed one of your curly braces from a function or conditional structure. We got this error by deleting one of the closing curly braces near the bottom of the checkGuess() function. SyntaxError: expected expression, got 'string' or SyntaxError: unterminated string literal These errors generally mean that you've left off a string value's opening or...
JavaScript object basics - Learn web development
last'] = 'Cratchit'; Try entering the above lines, and then getting the members again to see how they've changed, like so: person.age person['name']['last'] Setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members. Try these in the JS console: person['eyes'] = 'hazel'; person.farewell = function() { alert("Bye every
body!"); } You can now test out your new members: person['eyes'] person.farewell() One useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too. Let's say we wanted users to be able to store custom value types in their people data, by typing the member name and value into two text inputs. We could get those values like this: let myDat...
Working with JSON - Learn web development
nquoted, in JSON only quoted strings may be used as properties. Active learning: Working through a JSON example So, let's work through an example to show how we could make use of some JSON data on a website. Getting started To begin with, make local copies of our heroes.html and style.css files. The latter contains some simple CSS to style our page, while the former contains some very simple
body HTML: <header> </header> <section> </section> Plus a <script> element to contain the JavaScript code we will be writing in this exercise. At the moment it only contains two lines, which grab references to the <header> and <section> elements and store them in variables: const header = document.querySelector('header'); const section = document.querySelector('section'); We have made our JSON da...
Introduction to the server side - Learn web development
rameters (the field-value pairs sent via a query string), as POST data (data sent by the HTTP POST method), or in associated cookies. Web servers wait for client request messages, process them when they arrive, and reply to the web browser with an HTTP response message. The response contains a status line indicating whether or not the request succeeded (e.g. "HTTP/1.1 200 OK" for success). The
body of a successful response to a request would contain the requested resource (e.g. a new HTML page, or an image, etc...), which could then be displayed by the web browser. Static sites The diagram below shows a basic web server architecture for a static site (a static site is one that returns the same hard-coded content from the server whenever a particular resource is requested). When a user wan...
Ember interactivity: Events, classes and state - Learn web development
tial text value equal to the text given to it when created (see below), and an isCompleted value of false. The only Ember-specific part of this class is the @tracked decorator -- this hooks in to the reactivity system and allows Ember to update what you're seeing in your app automatically if the tracked properties change. More information on tracked can be found here. Now it's time to add to the
body of the service. First add another import statement below the previous one, to make actions available inside the service: import { action } from '@ember/object'; Update the existing export default class TodoDataService extends Service { ... } block as follows: export default class TodoDataService extends Service { @tracked todos = []; @action add(text) { let newTodo = new Todo(text)...
Getting started with React - Learn web development
r import thanks to the export statement at the bottom of App.js. Line 7 calls React's ReactDOM.render() function with two arguments: The component we want to render, <App /> in this case. The DOM element inside which we want the component to be rendered, in this case the element with an ID of root. If you look inside public/index.html, you'll see that this is a <div> element just inside the <
body>. All of this tells React that we want to render our React application with the App component as the root, or first component. Note: In JSX, React components and HTML elements must have closing slashes. Writing just <App> or just <img> will cause an error. Service workers are interesting pieces of code that help application performance and allow features of your web applications to work off...
Beginning our React todo list - Learn web development
r: inherit; font: inherit; line-height: normal; -webkit-font-smoothing: inherit; -moz-osx-font-smoothing: inherit; -webkit-appearance: none; } button::-moz-focus-inner { border: 0; } button, input, optgroup, select, textarea { font-family: inherit; font-size: 100%; line-height: 1.15; margin: 0; } button, input { overflow: visible; } input[type="text"] { border-radius: 0; }
body { width: 100%; max-width: 68rem; margin: 0 auto; font: 1.6rem/1.25 Arial, sans-serif; background-color: #f5f5f5; color: #4d4d4d; } @media screen and (min-width: 620px) {
body { font-size: 1.9rem; line-height: 1.31579; } } /*END RESETS*/ /* GLOBAL STYLES */ .form-group > input[type="text"] { display: inline-block; margin-top: 0.4rem; } .btn { padding: 0.8rem 1rem 0.7r...
Focus management with Vue refs - Learn web development
(), the "Edit" Button has not been rendered yet. Instead, we need to wait until after Vue undergoes the next DOM update cycle. To do that, Vue components have a special method called $nextTick(). This method accepts a callback function, which then executes after the DOM updates. Since the focusOnEditButton() method needs to be invoked after the DOM has updated, we can wrap the existing function
body inside a $nextTick() call. focusOnEditButton() { this.$nextTick(() => { const editButtonRef = this.$refs.editButton; editButtonRef.focus(); }); } Now when you activate the "Edit" Button and then cancel or save your changes via the keyboard, focus should be returned to the "Edit" Button. Success! Vue lifecycle methods Next, we need to move focus to the edit form's <input> element w...
Styling Vue components with CSS - Learn web development
; font: inherit; line-height: normal; -webkit-font-smoothing: inherit; -moz-osx-font-smoothing: inherit; -webkit-appearance: none; } button::-moz-focus-inner { border: 0; } button, input, optgroup, select, textarea { font-family: inherit; font-size: 100%; line-height: 1.15; margin: 0; } button, input { /* 1 */ overflow: visible; } input[type="text"] { border-radius: 0; }
body { width: 100%; max-width: 68rem; margin: 0 auto; font: 1.6rem/1.25 "Helvetica Neue", Helvetica, Arial, sans-serif; background-color: #f5f5f5; color: #4d4d4d; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; } @media screen and (min-width: 620px) {
body { font-size: 1.9rem; line-height: 1.31579; } } /*END RESETS*/ Next, in your src/main.js file,...
Strategies for carrying out testing - Learn web development
in everything, press the Get Tracking ID button, then accept the terms of service that appear. The next page provides you with some code snippets and other instructions. For a basic website, what you need to do is copy the Website tracking code block and paste it into all the different pages you want to track using Google Analytics on your site. You could place the snippets below your closing </
body> tag, or somewhere else appropriate that keeps it from getting muddled up with your application code. Upload the changes to the development server, or wherever else you need your code. That's it! Your site should now be ready to start reporting analytics data. Studying analytics data Now you should be able to go back to the Analytics Web homepage, and start looking at the data you've collect...
Mozilla’s UAAG evaluation report
show in button tooltips Guideline 8. Implement specifications that benefit accessibility. Checkpoint Title Status Notes/plans 8.1 Implement accessibility features. ...
Command line options
aining spaces must be enclosed in quotes, such as "Joel User". Command actions are case insensitive. Command parameters, except profile names, are case insensitive. Blank spaces ( ) separate commands and parameters. 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" . Comma separators must not follow or precede spaces ( ). 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" . Using co...
How Mozilla's build system works
is variables in make. Variables are defined by the syntax VARIABLE = VALUE, and the value of a variable is referenced by writing $(VARIABLE). All variables are strings. All Makefile.in files in Mozilla have the same basic format: DEPTH = ../../../.. topsrcdir = @top_srcdir@ srcdir = @srcdir@ VPATH = @srcdir@ include $(DEPTH)/config/autoconf.mk # ... Main
body of makefile goes here ... include $(topsrcdir)/config/rules.mk # ... Additional rules go here ... The DEPTH variable should be set to the relative path from your Makefile.in to the top-level Mozilla directory. topsrcdir is substituted in by configure and points to the top-level Mozilla directory. srcdir is also substituted in by configure and points to the source directory for the current...
Displaying Places information using views
some of these properties in conjunction with the place attribute and property. Property Type Description flatList boolean If true the view does not recurse into containers. The action to take when a container is toggled can be set via the onOpenFlatContainer property. At least one of flatList and showRoot must be false. onOpenFlatContainer string The
body of function that will be called when a container is toggled. Only applies if property flatList is true. The function will be passed one nsINavHistoryResultNode argument named aContainer. You can QueryInterface aContainer to an nsINavHistoryContainerResultNode. showRoot boolean If true the root nsINavHistoryContainerResultNode is shown as the first row in the tree. At least one of s...
Cross Process Object Wrappers
set up with a number of compatibility shims. 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. Bidirectional CPOWs A common pattern is for chrome code to access content objects and add event listeners to them. To deal with this, CPOWs are bidirectional. This means that if content passes a CPOW to the chrome process, the chrome process ...
HTMLIFrameElement.getContentDimensions()
Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.getContentDimensions(); Returns A DOMRequest for handling the dimensions request. Its request.onsuccess handler handles the success case, and its request.onerror handler handles the failure case. ...
Embedding the editor
IEditorShell will probably move into this interface. (This would be analogous to the nsIWebNavigation interface used for a browser.) When we have one editor per docShell, loading a frameset document, or a page with an <iframe> in composer, will instantiate more than one low-level editor. We need a concept of an "editing session" - a single top-level document which is editable, and which may em
body more than one editor. This interface will be called nsI????. High-level UI and emebedding code should deal with this editing session interface, without knowledge of the underlying editors. The editing session will forward commands to the individual editors depending on focus, and mediate undo/redo between them. Alternative solution: Rather than having multiple editors in this scenario, we could...
PBackground
ead. bypass both main threads if used from a non-main thread in a content process write process-agnostic code because it can be used even from another thread in the parent process The parent side of a PBackground actor pair is always on the designated background thread, while the child side is on the thread that chooses to use PBackground. The background thread is designed to be responsive (no
body is allowed to do long running computation or file I/O on it) to guarantee better latency than going through the main threads (which can run arbitrary JS, GC, etc.) can provide. Examples IndexedDB was rebuilt on top of PBackground last year. This allows the DOM code to generally not worry about what thread (main vs. worker) or process (single vs. multiple) it is running in. Instead, it simply tu...
Internationalized Domain Names (IDN) Support in Mozilla Browsers
ICANN = Internet Corporation for Assigned Names and Numbers.) The guideline allows domain name registrars in each country to limit the use of characters for domain names. Since the Unicode repertoire contains characters no longer used in any living languages and there are also living characters in most languages that are not suitable for URI/URL creation, the ICANN guideline allows the governing
body of each country's domain registrars to set appropriate limitations on the use of characters. With this last piece of obstacle for standardization out of the way, domain name registrars are expected to move forward on implementing the new RFC's for existing and future IDN registrations quickly. JPRS (Japan Registry Service) decided to move to the new RFC implementation on July 10, 2003, only a f...
Sqlite.jsm
ecute a database transaction. A transaction is a series of related statements treated as one functional unit. If the transaction succeeds, all the statements contained within it are committed as one unit. If the transaction fails, the database is rolled back to its state before the transaction started. This function receives the following arguments: func The function defining the transaction
body. type The type of transaction to perform. This must be one of the TRANSACTION_* constants on the opened connection instance. Valid values are TRANSACTION_DEFERRED, TRANSACTION_IMMEDIATE, TRANSACTION_EXCLUSIVE. See the SQLite documentation for their meaning. The default is TRANSACTION_DEFERRED. The passed function is a Task.jsm compatible generator function. When called, the function receives ...
Index
on its own. For more detailed documentation about localization in general, see our Localization page. 20 Localizing XLIFF files for iOS OASIS, Translate, XLIFF, XML, iOS Firefox for iOS uses the XLIFF XML-based file format to hold and transfer localization data. XLIFF (eXtensible Localisation Interchange File Format) is a localization standard governed by the OASIS standards
body. The goal of the standard is to have an XML-based format to use when exchanging localization data between tools without the potential of data loss or corruption. Most translation tools support the XLIFF standard, making localizing the XLIFF files for Firefox for iOS easy to do using translation tools. Editing the raw XLIFF file is also rather easy, especially if you're already familiar with XML. ...
Localization content best practices
pt the {{privacy}}. privacy-link = Privacy Terms File-wide comments should use the same format, they should be at the top of the file (after the license header) and just drop the (entity name/key) reference. Land good quality strings Don't land temporary strings. If you already know that your strings are temporary, they shouldn't be exposed to the localization process. This would waste every
body's time and create unnecessary frustration: localizers have to translate strings that are destined to change, developers will need to use new IDs later to update them. If you're reviewing a patch, check also strings for grammar errors, capitalization or inconsistencies. For example, use the single Unicode ..., and not three dots. If you have any doubts about the quality of strings, ask a copywrit...
Localizing XLIFF files for iOS
The goal of the standard is to have an XML-based format to use when exchanging localization data between tools without the potential of data loss or corruption. Most translation tools support the XLIFF standard, making localizing the XLIFF files for Firefox for iOS easy to do using translation tools. ...
Writing localizable code
eases the localization process without the source code and is especcially recommended to extension authors. JAR Manifests can make this easy. l10n impact On frozen trees, there is the rule to not check in l10n-impact changes. So what does that mean? l10n-impact is any change to mozilla/@mod@/locales; Localizers find out if they have to catch up on changes by doing bonsai queries, just as every
body else does. No change means that this query result is empty. any changed or new use of existing localized strings; Anything that triggers a QA cycle on our 40+ localizations is l10n-impact. ...
Mozilla DOM Hacking Guide
it is called for the first time however, mCachedClassInfo is still a null pointer, and the function will create a new instance of the relevant helper class, and cache it in the mCachedClassInfo pointer, then return it. And for those interested, here the longer explanation. The first time GetClassInfoInstance() is called, passing in an aID, mCachedClassInfo for that class will still be null. The
body of the "if" clause is thus executed. We initialize "data" to be a reference to the nsDOMClassInfoData object that corresponds to the DOM class we want to "help". On the next line, there is a call to data.mConstructorFptr(aID), which, if you remember the introduction to Class Info, maps to the doCreate static member function of the relevant helper class. doCreate creates a new instance of the help...
Mozilla Web Services Security Model
ent applies to all sites. The from attribute otherwise gives a URL to match, which may contain up to two asterisks (*) that match any characters in the URL. The match is done against a URL from which the directory and file have been removed, so trying to match a specific page will cause the entire match to fail. (Is this correct?) web-scripts-access.xml Examples These examples are untested! Some
body should test them to make sure they do what is claimed. Allow all services on a site to be accessed from any Web page Note that this is only a sensible thing to do if nothing on the site serves content based on cookies, HTTP authentication, IP address / domain origin, or any other method of authentication. <webScriptAccess xmlns="http://www.mozilla.org/2002/soap/security"/> Allow access to S...
Power profiling overview
Basic physics concepts In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time. In SI units, energy is measured in Joules, and power is measured in Watts, which is equivalent to Joules per second. ...
Performance
ents) How to use Apple's Shark tool to profile Mozilla code. Investigating CSS Performance How to figure out why restyle is taking so long Power profiling Power profiling overview This page provides an overview of relevant information, including details about hardware, what can be measured, and recommended approaches. It should be the starting point for any
body new to power profiling. tools/power/rapl (Mac, Linux) tools/power/rapl is a command-line utility in the Mozilla codebase that uses the Intel RAPL interface to gather direct power estimates for the package, cores, GPU and memory. powermetrics (Mac-only) powermetrics is a command-line utility that gathers and displays a wide range of global and per-process measurements, includin...
javascript.options.strict
JavaScript warnings are generated when code is executed that doesn't cause a run-time error, but is non-standard, poorly written, or prone to cause logic errors. This preference controls whether JavaScript warnings are logged to the JavaScript Console. 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 . var name2= "Peter"; document.getElementById("sample").innerHTML = name1; </script> </
body> </html> Possible values and their effects: True: Show JavaScript errors and warnings. False: Show JavaScript errors only. (Default) See also: http://kb.mozillazine.org/Javascript.options.strict ...
Patches and pushes
, that's short for nit-picky requests), fix those before committing. Also, no new patch attachment will be needed. Commit the patch to your Aurora repo. Only commit the changes you have reviewed. Use a commit message that mentions the bug number, describes the change, and mentions the reviewer. For example: hg ci -m "bug 654321, copied the comment from the doc without reading, r=no
body" path-to-changed-files Close the bug, copying the url to your change in the closing comment. Write up something like this for your comment: Landed this on aurora, http://hg.mozilla.org/releases/l10n/mozilla-aurora/ab-CD/rev/adfe1234feac, marking FIXED. Update your sign-offs on the l10n dashboard to include the change into the next release. And that's it! It can be considered a bit compli...
AsyncTestUtils extended framework
o get fancy about having flags set on the folder, we support that, but please check the method documentation. Get / create the Junk folder let junkFolder = get_junk_folder(); Create a Virtual folder (a folder whose contents are the result of a saved search) let virtualFolder = make_virtual_folder([aFolderToSearch1, aFolderToSearch2, ...], {subject: "",
body: "", from: "", to: "", cc: "", recipient: "", involves: ""}, aAndTermsTogether, aOptionalName); This is a convenience function to help you create a new virtual folder. The first argument is the list of folders we should search. The second argument defines the search query; each attribute defines a "contains" string constraint. If you include the attribute...
Leak And Bloat Tests
id1.valid", true); user_pref("mail.root.none-rel", "[ProfD]Mail"); user_pref("mail.root.pop3-rel", "[ProfD]Mail"); user_pref("mail.server.server1.directory-rel", "[ProfD]Mail/Local Folders"); user_pref("mail.server.server1.hostname", "Local Folders"); user_pref("mail.server.server1.name", "Local Folders"); user_pref("mail.server.server1.type", "none"); user_pref("mail.server.server1.userName", "no
body"); user_pref("mail.server.server2.check_new_mail", false); user_pref("mail.server.server2.directory-rel", "[ProfD]Mail/tinderbox"); user_pref("mail.server.server2.download_on_biff", true); user_pref("mail.server.server2.hostname", "tinderbox"); user_pref("mail.server.server2.login_at_startup", false); user_pref("mail.server.server2.name", "tinderbox@invalid.com"); user_pref("mail.server.server2.t...
An overview of NSS Internals
process data available in the ASN.1 format, the usual approach is to parse it and transfer it to a presentation that requires more space but is easier to work with, such as (nested) C data structures. Over the time NSS has received three different ASN.1 parser implementations, each having their own specific properties, advantages and disadvantages, which is why all of them are still being used (no
body has yet dared to replace the older with the newer ones because of risks for side effects). When using the ASN.1 parser(s), a template definition is passed to the parser, which will analyze the ASN.1 data stream accordingly. The templates are usually closely aligned to definitions found in RFC documents. A data block described as DER is usually in ASN.1 format. You must know which data you are ...
Index
process data available in the ASN.1 format, the usual approach is to parse it and transfer it to a presentation that requires more space but is easier to work with, such as (nested) C data structures. Over the time NSS has received three different ASN.1 parser implementations, each having their own specific properties, advantages and disadvantages, which is why all of them are still being used (no
body has yet dared to replace the older with the newer ones because of risks for side effects). When using the ASN.1 parser(s), a template definition is passed to the parser, which will analyze the ASN.1 data stream accordingly. The templates are usually closely aligned to definitions found in RFC documents. A data block described as DER is usually in ASN.1 format. You must know which data you are ...
Tutorial: Embedding Rhino
is the RunScript example. All it does it read a script from the command line, execute it, and print a result. Here's an example use of RunScript from a shell command line: $ java RunScript "Math.cos(Math.PI)" -1 $ java RunScript "function f(x){return x+1} f(7)" 8 Note that you'll have to have both the Rhino classes and the RunScript example class file in the classpath. Let's step through the
body of main one line at time. Entering a Context The code Context cx = Context.enter(); Creates and enters a Context. A Context stores information about the execution environment of a script. Initializing standard objects The code Scriptable scope = cx.initStandardObjects(); Initializes the standard objects (Object, Function, etc.) This must be done before scripts can be executed. The null ...
Creating JavaScript tests
Focus on writing fast, light tests that cover a single feature. There is basically no cost to adding a new test, so add as many feature tests as needed to cover each feature orthogonally. Remember that whenever a test fails, someone -- probably you -- is going to have to figure out what went wrong. Testing your test Run your new test locally before checking it in (or posting it for review). No
body likes patches that include failing tests! See Running Automated Javascript Tests for instructions on how to run jstests or jit-tests. It's also a good sanity check to run each new test against an unpatched shell or browser. The test should fail if it's working properly. Checking in completed tests Tests are usually reviewed and pushed just like any other code change. Just include the test in ...
Index
s, the converted value is stored in *vp. Typically users of this function set vp to point to v, so that if conversion is successful, v now contains the converted value. 222 JS_DecompileFunction JSAPI Reference, SpiderMonkey JS_DecompileFunction generates the complete source code of a function declaration from a function's compiled form, fun. 223 JS_DecompileFunction
Body JSAPI Reference, SpiderMonkey JS_DecompileFunction
Body generates the source code of a function's
body, minus the function keyword, name, parameters, and braces, from a function's compiled form, fun. 224 JS_DecompileScript JSAPI Reference, Reference, Reference(2), SpiderMonkey JS_DecompileScript returns the source code of script. If script is a function, it calls JS_...
Invariants
(The jsval encoding depends on this.) The JSStackFrame::down chain never forms a cycle. (It's a stack. ...
SpiderMonkey Internals
nning a debugger-supplied function that receives the old value and a pointer to the new one, which it can use to modify the new value being set. Line number to PC and back mapping functions. The line-to-PC direction "rounds" toward the next bytecode generated from a line greater than or equal to the input line, and may return the PC of a for-loop update part, if given the line number of the loop
body's closing brace. Any line after the last one in a script or function maps to a PC one byte beyond the last bytecode in the script. 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. var sumOfDivisors = new ExprArray(n + 1, 1)...
JIT Optimization Strategies
further occurrences of that same kind of operation. Inline caches are an order of magnitude slower than the other optimization strategies, and are an indication that the type inference engine has failed to collect enough information to guide the optimization process. Call Call_Inline A function call f(x) usually pushes a frame onto the call stack. Inlining a call site conceptually copies the
body of the callee function and pastes it in place of the call site and avoids pushing a new execution frame. Usually, hot functions do well to be inlined. This is one of the most important optimizations the JIT performs. Ion inlines both interpreted (i.e., written in JavaScript) functions and native (i.e., built-ins such as Math.sin implemented in C++). A successfully inlined call site has the outc...
JS::CompileFunction
the function. options JS::ReadOnlyCompileOptions & Compile options. name const char * Name to assign the newly compiled function. nargs unsigned Number of arguments to pass to the function. argnames const char *const * Names to assign to the arguments passed to the function. chars const char16_t * String containing the
body of the function to compile. bytes const char * String containing the
body of the function to compile. length size_t The length, in characters, of
body. srcBuf JS::SourceBufferHolder & Source buffer containing the script function compile. fun JS::MutableHandleFunction Out parameter. On success, fun receives the result function. ...
JS::CompileOptions
Methods of JS::OwningCompileOptions Method Description JSObject *element() const Returns the DOM element to which this source code belongs, if any, or NULL if it belongs to no DOM element. Source belongs to a DOM element in the following cases: Source belongs to a <script> element if it is the element's text content (that is, it is written out as the
body of the <script> element in the markup text), or is the source document referenced by its src attribute. Source belongs to a DOM element if it is an event handler content attribute (that is, if it is written out in the markup text as an attribute value). Source belongs to a DOM element if it was assigned to one of the element's event handler IDL attributes as a string. (Note that one may...
JS_DecompileFunction
declaration from a function's compiled form, fun. If successful, JS_DecompileFunction returns a string containing the text of the function. Otherwise, it returns NULL. If you decompile a function that does not make a native C call, then the text created by JS_DecompileFunction is a complete function declaration suitable for re-parsing. If you decompile a function that makes a native C call, the
body of the function contains the text "native code'" and cannot be re-parsed. See Also MXR ID Search for JS_DecompileFunction JS_DecompileScript JS_CallFunction JS_CallFunctionName JS_CallFunctionValue JS_CompileFunction JS_DecompileFunction
Body JS_DefineFunction JS_DefineFunctions JS_GetFunctionObject JS_NewFunction JS_SetBranchCallback JS_ValueToFunction ...
JSAPI reference
UCScriptForPrincipalsVersion Obsolete since JSAPI 19 JS_GetScriptObject Obsolete since JSAPI 8 JS_NewScriptObject Obsolete since JSAPI 8 JS_ExecuteScriptPart Obsolete since JavaScript 1.9.3 JS_DestroyScript Obsolete since JSAPI 8 You can also compile JavaScript code into a function: struct JSFunction JS::CompileFunction Added in SpiderMonkey 17 JS_DecompileFunction JS_DecompileFunction
Body JS_CompileFunction Obsolete since JSAPI 36 JS_CompileFunctionForPrincipals Obsolete since JSAPI 28 JS_CompileUCFunction Obsolete since JSAPI 36 JS_CompileUCFunctionForPrincipals Obsolete since JSAPI 28 Error handling struct JSErrorFormatString Added in SpiderMonkey 17 class JSErrorReport class JS::AutoSaveExceptionState Added in SpiderMonkey 31 enum JSExnType Added in SpiderMonkey ...
SpiderMonkey 1.8.5
Some C++ helpers have been introduced into the API, to help embedders writing C++ projects. Please note that SpiderMonkey reserves the JS:: namespace for itself. JSAutoRequest JSAutoSuspendRequest JSAutoCheckRequest JSAutoEnterCompartment JS::Anchor<> JS::Call Obsolete APIs JS_ClearNewbornRoots JS_Ente...
SpiderMonkey 1.8.7
Some C++ helpers have been introduced into the API, to help embedders writing C++ projects. Please note that SpiderMonkey reserves the JS:: namespace for itself. JSAutoRequest JSAutoSuspendRequest JSAutoCheckRequest JSAutoEnterCompartment JS::Anchor<> JS::Call Obsolete APIs JS_ClearNewbornRoots JS_Ente...
SpiderMonkey 45
ing (bug 1178581) Deleted APIs JS_GetCompartmentStats JS_SetICUMemoryFunctions JS_IsGCMarkingTracer JS_IsMarkingGray JS_IdArrayLength JS_IdArrayGet JS_DestroyIdArray JS_DefaultValue JS_GetParent JS_SetParent JS::ParsePropertyDescriptorObject JS_DeleteProperty2 JS_DeletePropertyById2 JS_DeleteUCProperty2 JS_DeleteElement2 JS_NewFunctionById JS_BindCallable JS_DecompileFunction
Body JS_GetLatin1InternedStringChars JS_GetTwoByteInternedStringChars JS_NewDateObjectMsec JS_ClearDateCaches Changed APIs JS_Init has moved from jsapi.h to js/Initialization.h JS_ShutDown has moved from jsapi.h to js/Initialization.h JS_InitReflect is now implicit JS_AddWeakPointerCallback is replaced with JS_AddWeakPointerZoneGroupCallback and JS_AddWeakPointerCompartmentCallback JS_Rem...
TPS Tab Lists
ab, optional. If specified, only used during verify actions. profile: the name of the profile the tab belongs to. Required for verify actions. 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. Tabs.verify - verifies that the specified tabs can be found in the specified profile. Tabs.verifyNot - verifies that the specified tabs cannot...
TPS Tests
hase declarations (mandatory). Data definitions/asset list (optional, but all current tests have them). Phase implementation (mandatory) It's worth noting that some parts of TPS assume that it can read the number off the end of the phase or profile to get to the next one, so try to stick to the convention established in the other tests. Yes, this is cludgey, but it's effective enough and no
body has changed it. Phase Declarations These map the phases to profiles. Both python and JavaScript read them in. They must look like: var phases = { "phase1": "profile1", "phase2": "profile2", "phase3": "profile1" }; Between { and } it must be strict JSON. e.g. quoted keys, no trailing parentheses, etc. The python testrunner will be parsing it with an unforgiving call to json.loads, so anythin...
Redis Tips
e things to notice: The subscriber blocks forever - not just for the first message. So subscribers are dedicated clients. The message channel doesn't have to be created in any way. The subscriber tells you the name of the channel as well as the message it received. I like pie. The return value from publish tells you how many subscribers received your message! So if that's 0, you know no
body's listening. You might use PSUBSCRIBE in a case where you have message channels named according to application namespaces, as different modules or logging systems might do. In that case, just check the name of the channel on the received message. Subscribe with one client: redis1> psubscribe log.* 1) "psubscribe" 2) "log.*" 3) (integer) 1 Publish with another client: redis2> publish log.b...
Exploitable crashes
table, and to fix exploitable crashes. What is an exploitable crash? A crash report from your debugger, your OS, or Mozilla crash-stats can tell you a lot about whether or not a crash is potentially exploitable. You want to look primarily for three things, in order: Look at the top frame of the stack trace. If you see a hex address such as 0x292c2830 rather than a function name such as nsListBox
BodyFrame::GetRowCount at the top of the stack, a bug has caused the program to transfer control to a "random" part of memory that isn't part of the program. These crashes are almost always exploitable to run arbitrary code. Look at the crash reason, which will usually be something like "KERN_PROTECTION_FAILURE (0x0002) at 0x00000000". This is typically located right above the stack trace. The last n...
Aggregating the In-Memory Datasource
l Details As before, have an nsCOMPtr as your delegate, but this time around,don't derive from nsIRDFDataSource. Also, instead of keeping an nsCOMPtr<nsIRDFDataSource>, you'll just want an nsCOMPtr<nsISupports>: class MyClass : public nsIMyInterface { ... private: nsCOMPtr<nsISupports> mInner; }; Construct the datasource delegate when your object is constructed (or, at worst, when some
body QI's for it): rv = nsComponentManager::CreateInstance( kRDFInMemoryDataSourceCID, this, /* the "outer" */ nsCOMTypeInfo<nsISupports>::GetIID(), getter_AddRefs(mInner)); Note passing this as the "outer" parameter. Now, if the in-memory datasource's implementation of QueryInterface() fails because it doesn't support the requested interface, it willforward the que...
Fun With XBL and XPConnect
the XPCOM Interfaces One somewhat nasty trick you need to do is to manually expose the interfaces of the XPCOM object that you want your widget to support. All you have to do is specifically defining a method on the XBL widget which forwards the method call to the XPCOM object. <method name="autoComplete"> <argument name="aSearchString"/> <argument name="resultListener"/> <
body> <![CDATA[ return this.autoCompleteSession.autoComplete(null, anonymousContent[0], aSearchString, this.autoCompleteListener); ]]> </
body> </method> You can see that the
body of the method is just getting the auto complete session object and calling the auto complete method on it. Implementing a Widget Interface The next thing I needed to do was ...
Component Internals
XPCOM must have a special component loader which knows how to deal with these type of components. XPConnect, for example, provides a component loader that makes the various types, including the interfaces and their parameters, available to JavaScript. Each language supported by XPCOM must have a component loader. Three parts of a XPCOM Component Library XPCOM is like an onionor a parfait! Every
body likes parfaits. XPCOM components have at least three layers. From the innermost and moving outward these layers include: The core XPCOM object The factory code The module code The core XPCOM object is the object that will implement the functionality you need. For example, this is the object that may start a network download and implement interfaces that will listen to the progress. Or the ...
Introduction to XPCOM for the DOM
at implements the interface has to explicitly implement each method and implement the setter and the getter of each attribute defined on the interface. If the attribute is read-only, only a getter is necessary, of course. I have chosen to implement nsIDOMFabian in the nsHTMLDocument class, which is defined in nsHTMLDocument.h. There are three things to do: modify the class declaration, the class
body, then code the functions declared on the interface. Modification of the class declaration and class
body: #include "nsIDOMFabian.h" class nsHTMLDocument: public ... , public nsIDOMFabian { // ... NS_DECL_NSIDOMFABIAN // ... }; First we have to declare nsHTMLDocument as inheriting from nsIDOMFabian. Then, in the class public interface, we use the m...
nsIHttpActivityObserver
on ACTIVITY_TYPE_SOCKET_TRANSPORT 0x0001 Socket transport activity has occurred. ACTIVITY_TYPE_HTTP_TRANSACTION 0x0002 HTTP transport activity has occurred. Activity subtype constants Constant Value Description ACTIVITY_SUBTYPE_REQUEST_HEADER 0x5001 The HTTP request is about to be queued for sending. Observers can look at request headers in aExtraStringData ACTIVITY_SUBTYPE_REQUEST_
BODY_SENT 0x5002 The HTTP request's
body has been sent. ACTIVITY_SUBTYPE_RESPONSE_START 0x5003 The HTTP response has started to arrive. ACTIVITY_SUBTYPE_RESPONSE_HEADER 0x5004 The HTTP response header has arrived. ACTIVITY_SUBTYPE_RESPONSE_COMPLETE 0x5005 The complete HTTP response has been received. ACTIVITY_SUBTYPE_TRANSACTION_CLOSE 0x5006 The HTTP transaction has been closed. Methods obs...
nsIHttpChannel
sIUploadChannel has further details. Exceptions thrown NS_ERROR_IN_PROGRESS If set after the channel has been opened. requestSucceeded boolean Returns true if the HTTP response code indicates success. The value of nsIRequest.status() will be NS_OK even when processing a 404 File Not Found response because such a response may include a message
body that (in some cases) should be shown to the user. Use this attribute to distinguish server error pages from normal pages, instead of comparing the response status manually against the set of valid response codes, if that is required by your application. Read only. Exceptions thrown NS_ERROR_NOT_AVAILABLE If called before the response has been received (before onStartRequest()...
nsIMsgDBHdr
ent database representation, so only internal database code should set this attribute. threadParent nsMsgKey Indicates the parent of this message in its thread. If this is the root of the thread, it will return nsMsgKey_None. messageSize unsigned long Indicates the size of this message in bytes. lineCount unsigned long Indicates the size of the message
body in number of lines. statusOffset unsigned long Indicates the offset within the message of the X-Mozilla-Status header. messageOffset unsigned long Indicates the position of the offline copy of an IMAP or news messages within the offline store. offlineMessageSize unsigned long Indicates the size of the offline copy of an IMAP or news message. d...
nsIMsgSearchCustomTerm
ommended 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. */ readonly attribute ACString id; name /// name to display in term list. This should be localized. */ readonly attribute AString name; needs
Body /// Does this term need the message
body? readonly attribute boolean needs
Body; Methods getEnabled /** * Is this custom term enabled? * * @param scope search scope (nsMsgSearchScope) * @param op search operator (nsMsgSearchOp). If null, determine * if term is available for any operator. * * @return true if enabled ...
nsIRadioInterfaceLayer
ng Description Exceptions thrown Missing Exception Missing Description getDataCallList() void getDataCallList(); Parameters None. Exceptions thrown Missing Exception Missing Description getNumberOfMessagesForText() Returns the number of multi-part SMS needed for a given text (160 characters for one SMS). unsigned short getNumberOfMessagesForText( in DOMString text ); Parameters text The
body text of an SMS. Return value Unsigned short. Number of SMS needed. hangUp() void hangUp( in unsigned long callIndex ); Parameters callIndex Missing Description Exceptions thrown Missing Exception Missing Description registerCallback() void registerCallback( in nsIRILTelephonyCallback callback ); Parameters callback Missing Description Exceptions thrown Missing Exception Missing Desc...
nsITreeBoxObject
tribute Type Description columns nsITreeColumns Readonly: Obtain the columns. view nsITreeView The view that backs the tree and that supplies it with its data. It is dynamically settable, either using a view attribute on the tree tag or by setting this attribute to a new value. focused boolean Whether or not we are currently focused. tree
Body nsIDOMElement Readonly: Obtain the tree
body content node. This is a node that corresponds to the treechildren tag. rowHeight long Readonly: Obtain the height of a row. rowWidth long Readonly: Obtain the width of a row. horizontalPosition long Readonly: Get the pixel position of the horizontal scrollbar. selectionRegion nsIScriptableR...
nsIWebBrowserPersist
MATTED 2 For plain text output. Convert html to plain text that looks like the html. Implies wrap (except inside <pre>), since html wraps. HTML output: always do prettyprinting, ignoring existing formatting. ENCODE_FLAGS_RAW 4 Output without formatting or wrapping the content. This flag may be used to preserve the original formatting as much as possible. ENCODE_FLAGS_
BODY_ONLY 8 Output only the
body section, no HTML tags. ENCODE_FLAGS_PREFORMATTED 16 Wrap even if when not doing formatted output (for example for text fields). ENCODE_FLAGS_WRAP 32 Wrap documents at the specified column. ENCODE_FLAGS_FORMAT_FLOWED 64 For plain text output. Output for format flowed (RFC 2646). This is used when converting to text for ...
nsIWebNavigation
_FLAGS_NONE for this parameter. referrer The referring URI. If this argument is null, then the referring URI will be inferred internally. postData If the URI corresponds to a HTTP request, then this stream is appended directly to the HTTP request headers. It may be prefixed with additional HTTP headers. This stream must contain a \r\n sequence separating any HTTP headers from the HTTP request
body. This parameter may be null. headers If the URI corresponds to a HTTP request, then any HTTP headers contained in this stream are set on the HTTP request. The HTTP header stream is formatted as: ( HEADER \r\n )* This parameter may be null. reload() Tells the Object to reload the current page. There may be cases where the user will be asked to confirm the reload (for example, when it is deter...
nsIXULTemplateQueryProcessor
r the form of the data implies the value. For instance, a datasource that holds a table that can only produce one set of results. The reference variable may be specified in a template by setting the "container" attribute on the <template> element to the variable to use. The member variable may be specified in a similar way using the "member" attribute, or it may be specified in the first <action>
body in the template as the value of a uri attribute on an element. A breadth-first search of the first action is performed to find this element. If unspecified, the default value of the reference variable is ?uri. 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 folde...
nsIXULTemplateResult
urce uri must be the same as the ID property. Read only. type AString The type of the object. The predefined value 'separator' may be used for separators. Other values may be used for application specific purposes. Read only. Methods getBindingFor() Get the string representation of the value of a variable for this result. This string will be used in the action
body from a template as the replacement text. For instance, if the text ?name appears in an attribute within the action
body, it will be replaced with the result of this method. The question mark is considered part of the variable name, thus aVar should be ?name and not simply name. AString getBindingFor( in nsIAtom aVar ); Parameters aVar The variable to look up. Return value The v...
nsMsgRuleActionType
t long ChangePriority=2; const long Delete=3; const long MarkRead=4; const long KillThread=5; const long WatchThread=6; const long MarkFlagged=7; const long Label=8; const long Reply=9; const long Forward=10; const long StopExecution=11; const long DeleteFromPop3Server=12; const long LeaveOnPop3Server=13; const long JunkScore=14; const long Fetch
BodyFromPop3Server=15; const long CopyToFolder=16; const long AddTag=17; const long KillSubthread=18; const long MarkUnread=19; }; ...
nsMsgMessageFlags
0x00000020 Indicates whether or not the thread rooted at this message is open or closed in the UI. Offline 0x00000080 Indicates whether or not we have this message in the offline cache. Watched 0x00000100 Indicates whether or not this thread is being watched. SenderAuthed 0x00000200 Partial 0x00000400 Indicates whether or not the
body we have is a complete message. Queued 0x00000800 Indicates whether or not the message is queued to be delivered. Forwarded 0x00001000 Indicates whether or not the message has been forwarded. Priorities 0x0000E000 The set of bits that indicate the priority. New 0x00010000 Indicates whether or not the message is new since the last time the...
nsMsgViewCommandType
he selected messages. Use with nsIMsgDBView.doCommandWithFolder() to select the destination folder. selectAll 15 Select all messages. downloadSelectedForOffline 16 Download the selected messages for offline. downloadFlaggedForOffline 17 Download all flagged messages for offline. selectThread 18 Select the entire thread. selectFlagged 19 Select all flagged messages. cmdRequiringMsg
Body 20 Used with nsIMsgDBView.getCommandStatus() to determine if commands requiring the message
body (i.e. reload or print preview) are available. label0 21 Attach a label to the selected messages. label1 22 Attach a label to the selected messages. label2 23 Attach a label to the selected messages. label3 24 Attach a label to the selected messages. label4 25 Attach a label to the sele...
Getting Started Guide
you. An nsCOMPtr looks and acts as much like a raw XPCOM interface pointer as C allows, but it knows it owns the object it points to. This takes a little getting used to on your part, but ends up with less typing, clearer, safer code, and less leaks. For instance, here is a typical snippet of code (at its most compact) where you assign a XPCOM interface pointer into a member variable, i.e., the
body of a `setter' function, side-by-side using raw XPCOM interface pointers and nsCOMPtrs. Comparison 1. Setting a member variable. // raw XPCOM interface pointers... // given: |nsIFoo* mFooPtr;| /* |AddRef| the new value if it's not |NULL|; assign it in; and |Release| the old value, if any (so we don't leak it). This order of assignment is special and must be use...
Creating a gloda message query
sation" attribute. query.tags(tag1, tag2, tag3, ...): Add the constraint that the message must have one of the provided nsIMsgTag tags applied. (Use nsIMsgTagService to access message tags.) query.starred(true/false): Add the constraint that the message must be (or not be) starred (flagged). query.read(true/false): Add the constraint that the message must be (or not be) marked as read. query.
bodyMatches(searchString): Perform a full-text search against plaintext message bodies. query.attachmentTypes(mimeType1, mimeType2, ...): Constrain to messages with attachments among the given mime types. In theory, providing no arguments should result in finding messages with any attachment, but this is somewhat untested. More constraints can be found in the three js files given further below. From...
MailNews fakeserver
y to use for new articles) getGroupStats group name array of [size, min, max] the size is an estimate if NNTP_REAL_LENGTH is not specified in the daemon flags. getArticle message ID newsArticle object Pretty self-explanatory newsArticle API Name Arguments Returns Notes [constructor] text (as a string) N/A initializes all fields headers (property) map of header (lower-case) -> value
body (property) text of
body messageID (property) message ID fullText (property) Full text as message without modification except added headers. ...
Tips and Tricks from the newsgroups
ave Attachment and send it Repeat image display using CSS sprites Messages Use ReminderFox to open a message in the default Thunderbird message window (when messageUri, folderUri and gDBView are unknown) Determine whether a message has been flagged as junk IMAP: Getting message key of copied message by nsIMsgCopyService::CopyFileMessage Access the plain text content of the email
body Get information about attachment without selecting message Repeat image display using CSS sprites Scan for new messages at startup and manually scan a folder initiated by user Force listeners to run consecutively to prevent POP messages from getting garbled during message retrieval ...
Standard OS Libraries
onsidered stable, but it's supposed to replace Xorg in the long term. GTK+ and Qt have begun porting their code to Wayland. As Wayland is not out yet in the wild this article does not focus on Wayland, it will focus on GTK+ and Xorg(X11/X). GDK is a stack under GTK+. GTK+ is the toolkit to build apps, GDK is more low-level. To be precise, X is "just" like a display machine. On top of which every
body uses "Window Managers" (known as "WM"s) such as fluxbox, i3, awesome, openbox, Mutter (used by Gnome 3), plasma (used by KDE) etc. Gnome and KDE are "Desktop Environments" (known as "DE"s). WMs on Ubuntu work a little differently but we'll revisit this topic later in this article (Did you know they have a *special* Firefox build for Ubuntu?). So DEs are a stack over WMs. There is also a layer kn...
Using js-ctypes
default_abi, CFStringRef, // return CFAllocatorRef, // alloc UniChar.ptr, // *chars CFIndex // numChars ); // HELPER FUNCTIONS function makeCFStr(jsStr) { // js str is just a string // returns a CFStr that must be released with CFRelease when done return CFStringCreateWithCharacters(null, jsStr, jsStr.length); } // MAIN var myCFStrs = { head: makeCFStr('Core Foundation Says...'),
body: makeCFStr('We just called the equivalent of the "StandardAlert Carbon function" for 64bit OSX from JavaScript!') }; var rez = CFUserNotificationDisplayNotice(0, kCFUserNotificationCautionAlertLevel, null, null, null, myCFStrs.head, myCFStrs.
body, null); console.info('rez:', rez, rez.toString(), uneval(rez)); // CFUserNotificationDisplayNotice does not block till user clicks dialog, it will retu...
Streams - Plugins
ing this function with NPN_NewStream and NPN_Write, see "Example of Sending a Stream." Example of Sending a Stream The following code creates a new stream of HTML text displayed by the browser in a new window, writes it, and destroys the stream. Error handling has been omitted for simplicity. NPStream* stream; char* myData = "<html><head><title>This is a message from my plug-in!</title></head><
body><p><strong>This is a message from my plug-in!</strong></p></
body>/html>"; int32 myLength = strlen(myData) + 1; /* Create the stream. */ err = NPN_NewStream(instance, "text/html", "_blank", &stream); /* Push data into the stream. */ err = NPN_Write(instance, stream, myLength, myData); /* Delete the stream. */ err = NPN_DestroyStream(instance, stream, NPRES_DONE); Your plug-in can create anoth...
DOM Inspector internals - Firefox Developer Tools
viewer subdirectories--viewers/dom and viewers/styleRules--are loaded as a result of overlay directives in DOM Inspector's chrome manifest, rather than being explicitly imported using a xul-overlay processing instruction in the overlaid file.) inspectorOverlay.xul This imports the scripts the top-level inspector needs, including dependencies. Additionally, it defines the content in the main
body of the DOM Inspector window, namely, the panelset, document and object viewer panels, and the document browser pane. (The browser pane is not a viewer panel in the sense that document and object panels are, i.e., the sorts of panels as defined above in relation to the panelset; "pane" is used here with regard to the browser pane in a loose sense to describe the generic UI fixture.) toolboxOver...
Browser Console - Firefox Developer Tools
bject, through the gBrowser global, and that enables you to control the browser through the command line. Try running this code in the Browser Console's command line (remember that to send multiple lines to the Browser Console, use Shift+Enter): var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab); newTabBrowser.addEventListener("load", function() { newTabBrowser.contentDocument.
body.innerHTML = "<h1>this page has been eaten</h1>"; }, true); newTabBrowser.contentDocument.location.href = "https://mozilla.org/"; It adds a listener to the currently selected tab's load event that will eat the new page, then loads a new page. Note: You can restart the browser with the command Ctrl + Alt + R (Windows, Linux) or Cmd + Alt + R (Mac) This command restarts the browser with the same ...
Debugger.Frame - Firefox Developer Tools
ation which caused it to be unwound. In frames returning or throwing an exception, the location is often a return or a throw statement. In frames propagating exceptions, the location is a call. When an onPop call reports the completion of a construction call (that is, a function called via the new operator), the completion value passed to the handler describes the value returned by the function
body. If this value is not an object, it may be different from the value produced by the new expression, which will be the value of the frame's this property. (In ECMAScript terms, the onPop handler receives the value returned by the [[Call]] method, not the value returned by the [[Construct]] method.) When a debugger handler function forces a frame to complete early, by returning a { return:... }, ...
Debugger.Object - Firefox Developer Tools
unction, or not a function at all, this is undefined. This accessor returns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or evaluating a function expression (which binds the function to its name only within the function's
body). displayName The referent's display name, if the referent is a function with a display name. If the referent is not a function, or if it has no display name, this is undefined. If a function has a given name, its display name is the same as its given name. In this case, the displayName and name properties are equal. If a function has no name, SpiderMonkey attempts to infer an appropria...
Debugger.Script - Firefox Developer Tools
Assembly code. For the former, it is the Debugger API's presentation of a JSAPI JSScript object. The two cases are distinguished by their format property being "js" or "wasm". Debugger.Script for JSScripts For Debugger.Script instances referring to a JSScript, they are distinguished by their format property being "js". Each of the following is represented by a single JSScript object: The
body of a function--that is, all the code in the function that is not contained within some nested function. The code passed to a single call to eval, excluding the bodies of any functions that code defines. The contents of a <script> element. A DOM event handler, whether embedded in HTML or attached to the element by other JavaScript code. Code appearing in a javascript: URL. ...
Debugger.Source - Firefox Developer Tools
y's value holds the string that was given. Otherwise, this is null. element The Debugger.Object instance referring to the DOM element to which this source code belongs, if any, or undefined if it belongs to no DOM element. Source belongs to a DOM element in the following cases: Source belongs to a <script> element if it is the element's text content (that is, it is written out as the
body of the <script> element in the markup text), or is the source document referenced by its src attribute. Source belongs to a DOM element if it is an event handler content attribute (that is, if it is written out in the markup text as an attribute value). Source belongs to a DOM element if it was assigned to one of the element's event handler IDL attributes as a string. (Note that...
Debugger-API - Firefox Developer Tools
s This diagram shows the various types of shadow objects that make up the Debugger API (which all follow some general conventions): A Debugger.Object represents a debuggee object, offering a reflection-oriented API that protects the debugger from accidentally invoking getters, setters, proxy traps, and so on. A Debugger.Script represents a block of JavaScript code--either a function
body or a top-level script. Given a Debugger.Script, one can set breakpoints, translate between source positions and bytecode offsets (a deviation from the "source level" design principle), and find other static characteristics of the code. A Debugger.Frame represents a running stack frame. You can use these to walk the stack and find each frame's script and environment. You can also set onStep ...
Debugger.Object - Firefox Developer Tools
unction, or not a function at all, this is undefined. This accessor returns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instantiating a function declaration (which binds the function to its name in the enclosing scope) or evaluating a function expression (which binds the function to its name only within the function's
body). displayName The referent's display name, if the referent is a function with a display name. If the referent is not a function, or if it has no display name, this is undefined. If a function has a given name, its display name is the same as its given name. In this case, the displayName and name properties are equal. If a function has no name, SpiderMonkey attempts to infer an appropria...
DevTools API - Firefox Developer Tools
mplate for a ToolPanel implementation. // In the ToolDefintion object, do // build: (window, target) => new MyPanel(window, target), function MyPanel(window, target) { // The window object that has loaded the URL defined in the ToolDefinition this.window = window; // The Target this toolbox is debugging. this.target = target; // Do synchronous initialization here. window.document.
body.addEventListener("click", this.handleClick); } MyPanel.prototype = { open: function() { // Any asynchronous operations should be done here. return this.doSomethingAsynchronous() .then(() => this); }, destroy: function() { // Synchronous destruction. this.window.document.
body.removeEventListener("click", this.handleClick); // Async destruction. return this.de...
Migrating from Firebug - Firefox Developer Tools
a request is shown within the Remote IP column within Firebug. In the Network Monitor the address is shown at Remote Address in the Headers tab when a request is selected. Search within requests The search field within Firebug allows to search within the requests. The search field in the Firefox DevTools filters the requests by the entered string. Firebug allowed to search within the response
body of the network requests by checking Response Bodies within its search field options. This feature is not available yet within the Network Monitor, but it's requested in bug 1334408. While response bodies can't be searched yet, the Network Monitor allows to filter by different request properties. Storage Inspector The Cookies panel in Firebug displays information related to the cookies created b...
Network request details - Firefox Developer Tools
bar, you can: Filter the headers in the Response Headers and Request Headers sections. Block the domain involved in this request. The domain is added to the Blocking sidebar. Resend the request. The Resend button opens a menu with two items: Resend: Simply resends the request. Edit and Resend: Enables an editing mode, where you can modify the method, URL, request headers, or request
body of the request. Click Send to send the modified request, or Cancel to cancel editing. Request Information The following information is shown only when the section is expanded: Scheme: The scheme used in the URL Host: The server involved in the request Filename: The full path to the file requested Address: The IP address of the host The following information is shown in both the co...
The JavaScript input interpreter - Firefox Developer Tools
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"; } </script> </head> <
body> </
body> </html> You can switch context to the iframe like this: cd("#frame1"); Now you'll see that t...
AbortController.abort() - Web APIs
Syntax controller.abort(); Parameters None. Return value Void. Examples In the following snippet, we aim to download a video using the Fetch API. We first create a controller using the AbortController() constructor, then grab a reference to its associated AbortSignal object using the AbortController.signal property. ...
AbortController - Web APIs
bortSignal object. Constructor AbortController() Creates a new AbortController object instance. Properties AbortController.signal Read only Returns a AbortSignal object instance, which can be used to communicate with/abort a DOM request. Methods AbortController.abort() Aborts a DOM request before it has completed. This is able to abort fetch requests, consumption of any response
Body, and streams. Examples In the following snippet, we aim to download a video using the Fetch API. We first create a controller using the AbortController() constructor, then grab a reference to its associated AbortSignal object using the AbortController.signal property. When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (see {signal...
Animation.commitStyles() - Web APIs
ommits the end styling state of an animation to the element being animated, even after that animation has been removed. It will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. Syntax animation.commitStyles(); Parameters None. Return value None. Examples const divElem = document.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 that specification. Working Draft ...
Animation.onremove - Web APIs
mation is removed (i.e., put into an active replace state). Syntax var removeHandler = animation.onremove; animation.onremove = removeHandler; Value A function to be called to handle the remove event, or null if no remove event handler is set. ...
Animation.persist() - Web APIs
tions API's Animation interface explicitly persists an animation, when it would otherwise be removed due to the browser's Automatically removing filling animations behavior. Syntax animation.persist(); Parameters None. Return value None. ...
Animation.replaceState - Web APIs
the animation has been removed by the browser's Automatically removing filling animations behavior. persisted: The animation has been explicitly persisted by invoking Animation.persist() on it. removed: The animation has been explicitly removed. ...
AudioContext.createMediaElementSource() - Web APIs
e variables to store mouse pointer Y coordinate // and HEIGHT of screen var CurY; var HEIGHT = window.innerHeight; // Get new mouse pointer coordinates when mouse is moved // then set new gain value document.onmousemove = updatePage; function updatePage(e) { CurY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? ...
Background Tasks API - Web APIs
logBox"> <div class="logHeader"> Log </div> <div id="log"> </div> </div> The progress box uses a <progress> element to show the progress, along with a label with sections that are changed to present numeric information about the progress. In addition, there's a "Start" button (creatively given the ID "startButton"), which the user will use to start the data processing. ...
Blob - Web APIs
n image, of course). function typedArrayToURL(typedArray, mimeType) { return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType})) } const bytes = new Uint8Array(59); for(let i = 0; i < 59; i++) { bytes[i] = 32 + i; } const url = typedArrayToURL(bytes, 'text/plain'); const link = document.createElement('a'); link.href = url; link.innerText = 'Open the array URL'; document.
body.appendChild(link); Result Click the link in the example to see the browser decode the object URL. Extracting data from a blob One way to read content from a Blob is to use a FileReader. The following code reads the content of a Blob as a typed array: const reader = new FileReader(); reader.addEventListener('loadend', () => { // reader.result contains the contents of blob as a typed arra...
CSSPrimitiveValue.getFloatValue() - Web APIs
ians. CSS_S The value is a <time> in seconds. Return value A float value in the specified unit. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the CSS value doesn't contain a float value or if the float value can't be converted into the specified unit. 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. Obsolete Initial definition ...
CSSPrimitiveValue.getRGBColorValue() - Web APIs
BColor interface. Syntax var rgbColorValue = cssPrimitiveValue.getRGBColorValue(); Return value An RGBColor object representing the color value. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the attached property can't return an RGB color value (i.e. this is not CSS_RGBCOLOR). 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. Obsolete Initial definition ...
CSSPrimitiveValue.getStringValue() - Web APIs
get a string value. If this CSS value doesn't contain a string value, a DOMException is raised. Syntax var stringValue = cssPrimitiveValue.getStringValue(); Return value A string value. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the CSS value doesn't contain a string value. 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. Obsolete Initial definition ...
CSSPrimitiveValue.primitiveType - Web APIs
CSS_STRING The value is a <string>. The value can be obtained by using the getStringValue() method. CSS_UNKNOWN The value is not a recognized CSS2 value. The value can only be obtained by using the cssText attribute. CSS_URI The value is a <uri>. The value can be obtained by using the getStringValue() method. 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. Obsolete Initial definition ...
CSSRule.cssText - Web APIs
, and silently so. In other words, attempting to set it does absolutely nothing, and doesn't even omit a warning or error. Furthermore, it has no settable sub-properties. Therefore, to modify it, use the stylesheet's cssRules[index] properties .selectorText and .style (or its sub-properties). See Using dynamic styling information for details. Syntax string = cssRule.cssText Example <style>
body { background-color: darkblue; } </style> <script> var stylesheet = document.styleSheets[0]; alert(stylesheet.cssRules[0].cssText); //
body { background-color: darkblue; } </script> Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSRule: cssText' in that specification. Working Draft ...
CSSStyleDeclaration.setProperty() - Web APIs
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-width: 1000px; margin: 0 auto; } .controls { display: flex; justify-content: space-around; align-items: center; } div button { flex: 1; margin: 20px; height: 30px; line-height: 30px; } .box { display: flex; justify-content: center; align-items: center; height: calc(100% - 70px); } .box p { width: 50%; tex...
CSSStyleRule.selectorText - Web APIs
The CSSRule.selectorText property gets the textual representation of the selector for the rule set. This is readonly in some browsers; to set stylesheet rules dynamically cross-browser, see Using dynamic styling information. Syntax string = cssRule.selectorText Example // for cssrule:
body { background-color: darkblue; } var stylesheet = document.styleSheets[0]; alert(stylesheet.cssRules[0].selectorText); //
body Notes The implementation may have stripped out insignificant whitespace while parsing the selector. If set to a selector string which cannot be parsed, a SyntaxError is thrown. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleRule.selectorText' in that specification. Working Draft Brow...
Cache.put() - Web APIs
fire. We construct a custom response like so: Check whether a match for the request is found in the CacheStorage using CacheStorage.match(). If so, serve that. If not, open the v1 cache using open(), put the default network request in the cache using Cache.put() and return a clone of the default network request using return response.clone(). Clone is needed because put() consumes the response
body. If this fails (e.g., because the network is down), return a fallback response. var response; var cachedResponse = caches.match(event.request).catch(function() { return fetch(event.request); }).then(function(r) { response = r; caches.open('v1').then(function(cache) { cache.put(event.request, response); }); return response.clone(); }).catch(function() { return caches.match('/s...
CacheStorage.match() - Web APIs
We construct a custom response like so: Check whether a match for the request is found in the CacheStorage using CacheStorage.match(). If so, serve that. If not, open the v1 cache using open(), put the default network request in the cache using Cache.put() and return a clone of the default network request using return response.clone(). The last is necessary because put() consumes the response
body. If this fails (e.g., because the network is down), return a fallback response. self.addEventListener('fetch', function(event) { event.respondWith(caches.match(event.request).then(function(response) { // caches.match() always resolves // but in case of success response will have value if (response !== undefined) { return response; } else { return fetch(event.reque...
CanvasRenderingContext2D.textBaseline - Web APIs
ble values: "top" The text baseline is the top of the em square. "hanging" The text baseline is the hanging baseline. (Used by Tibetan and other Indic scripts.) "middle" The text baseline is the middle of the em square. "alphabetic" The text baseline is the normal alphabetic baseline. Default value. "ideographic" The text baseline is the ideographic baseline; this is the bottom of the
body of the characters, if the main
body of characters protrudes beneath the alphabetic baseline. (Used by Chinese, Japanese, and Korean scripts.) "bottom" The text baseline is the bottom of the bounding box. This differs from the ideographic baseline in that the ideographic baseline doesn't consider descenders. The default value is "alphabetic". Examples Comparison of property values This exam...
A basic ray-caster - Web APIs
element to do software rendering of a 3D environment using ray-casting. Open in new window Why? After realizing, to my delight, that the nifty <canvas> element I'd been reading about was not only soon to be supported in Firefox, but was already supported in the current version of Safari, I had to try a little experiment. The canvas overview and tutorial I found here at MDN are great, but no
body had written about animation yet, so I thought I'd try a port of a basic raycaster I'd worked on a while ago, and see what sort of performance we can expect from a JavaScript-controlled pixel buffer. How? The basic idea is to use setInterval() at some arbitrary delay that corresponds to a desired frame rate. After every interval an update function will repaint the canvas showing the current view...
Clients.openWindow() - Web APIs
you want to open in the window. Generally this value must be a URL from the same origin as the calling script. Return value A Promise that resolves to a WindowClient object if the URL is from the same origin as the service worker or a null value otherwise. ...
console - Web APIs
the ending time to the console: Notice that the timer's name is displayed both when the timer is started and when it's stopped. Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response
body logging enabled, the time listed for the response header and
body combined should match what you see in the console output. Stack traces The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call console.trace(). Given code like this: function foo() { function bar() { console.trace(); } bar(); } foo(); The...
DOMImplementation.createDocument() - Web APIs
ong to one. qualifiedNameStr Is a DOMString containing the qualified name, that is an optional prefix and colon plus the local root element name, of the document to be created. documentType Optional Is the DocumentType of the document to be created. It defaults to null. 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 HTML
BodyElement] Specifications Specification Status Comment DOMThe definition of 'DOMImplementation.createDocument' in that specification. Living Standard Modified the return type o...
DataTransfer.setDragImage() - Web APIs
ge(); img.src = 'example.gif'; ev.dataTransfer.setDragImage(img, 10, 10); } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); // Get the data, which is the id of the drop target var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } </script> <
body> <h1>Example of <code>DataTransfer.setDragImage()</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div> </
body> </html> Specifications ...
DataTransferItem.webkitGetAsEntry() - Web APIs
ting"> </ul> CSS content The styles used by the example are shown here. #dropzone { text-align: center; width: 300px; height: 100px; margin: 10px; padding: 10px; border: 4px dashed red; border-radius: 10px; } #boxtitle { display: table-cell; vertical-align: middle; text-align: center; color: black; font: bold 2em "Arial", sans-serif; width: 300px; height: 100px; }
body { font: 14px "Arial", sans-serif; } JavaScript content First, let's look at the recursive scanFiles() function. This function takes as input a FileSystemEntry representing an entry in the file system to be scanned and processed (the item parameter), and an element into which to insert the list of contents (the container parameter). Note that to read all files in a directory, readEntries nee...
Using light sensors - Web APIs
ux which is generally treated as shown below. 10 ~ 50 lux : Dim Environment 100 ~ 1000 lux : Normal > 10000 lux : Bright It uses the addEventListener method of the window object. 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. If your app contains a lot of white in the UI, it is usually benefici...
Document: DOMContentLoaded event - Web APIs
asn'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: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } JS const log = document.querySelector('.event-log-contents'); const reload = document.que...
Document.anchors - Web APIs
on init() { var toc = document.getElementById("toc"); var i, li, newAnchor; for (i = 0; i < document.anchors.length; i++) { li = document.createElement("li"); newAnchor = document.createElement('a'); newAnchor.href = "#" + document.anchors[i].name; newAnchor.innerHTML = document.anchors[i].text; li.appendChild(newAnchor); toc.appendChild(li); } } </script> </head> <
body onload="init()"> <h1>Title</h1> <h2><a name="contents">Contents</a></h2> <ul id="toc"></ul> <h2><a name="plants">Plants</a></h2> <ol> <li>Apples</li> <li>Oranges</li> <li>Pears</li> </ol> <h2><a name="veggies">Veggies</a></h2> <ol> <li>Carrots</li> <li>Celery</li> <li>Beats</li> </ol> </
body> </html> View on JSFiddle Notes For reasons of backwards compatibility, the returned s...
Document.bgColor - Web APIs
tring representing the color as a word (e.g., "red") or hexadecimal value (e.g., "#ff0000"). Example document.bgColor = "darkblue"; Notes The default value for this property in Firefox is white (#ffffff in hexadecimal). document.bgColor is deprecated in DOM Level 2 HTML. The recommended alternative is use of the CSS style background-color which can be accessed through the DOM with document.
body.style.backgroundColor. Another alternative is document.
body.bgColor, although this is also deprecated in HTML 4.01 in favor of the CSS alternative. ...
Document.createNodeIterator() - Web APIs
cepted an optional fourth parameter (entityReferenceExpansion) that is not part of the DOM4 specification, and has therefore been removed. This parameter indicated whether or not the children of entity reference nodes were visible to the iterator. Since such nodes were never created in browsers, this paramater had no effect. ...
Document.createTextNode() - Web APIs
var text = document.createTextNode(data); text is a Text node. data is a string containing the data to be put in the text node. 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! ');">YES!</button> <button onclick="addTextNode('NO! ');">NO!</button> <button onclick="addTextNode('WE CAN! ');">WE CAN!</button> <hr /> <p id="p1">First line of paragraph.</p> </
body> </html> Specifications Specification Status Comment DOMThe definition of 'Document: createTextNode' in that specification. Livin...
Document.documentElement - Web APIs
Document.documentElement returns the Element that is the root element of the document (for example, the <html> element for HTML documents). Syntax const element = document.documentElement Example const rootElement = document.documentElement; const firstTier = rootElement.childNodes; // firstTier is a NodeList of the direct children of the root element // such as <head> and <
body> for (const child of firstTier) { // do something with each direct child of the root element } Notes For any non-empty HTML document, documentElement will always be an <html> element. For any non-empty XML document, documentElement will always be whatever element is the root element of the document. Specifications Specification Status Comment DOMThe definition of 'Document.docu...
Document.fgColor - Web APIs
color is a string representing the color as a word (e.g., "red") or hexadecimal value (e.g., "#ff0000"). Example document.fgColor = "white"; document.bgColor = "darkblue"; Notes The default value for this property in Mozilla Firefox is black (#000000 in hexadecimal). document.fgColor is deprecated in DOM Level 2 HTML. The recommended alternative is the CSS property color (e.g., document.
body.style.color = "red"). Another alternative is document.
body.text, although this is deprecated in HTML 4.01 in favor of the CSS alternative above. ...
Document.linkColor - Web APIs
The Document.linkColor property gets/sets the color of links within the document. This property is deprecated. As an alternative, you can set the CSS color property on either HTML anchor links (<a>) or on :link pseudo-classes. Another alternative is document.
body.link, although this is deprecated in HTML 4.01. Syntax color = document.linkColor document.linkColor = color Parameters color is a string representing the color as a word (e.g., red) or hexadecimal value (e.g., #ff0000). Example document.linkColor = 'blue'; Specification HTML5 Document.linkColor is deprecated in DOM Level 2 HTML. ...
Document.links - Web APIs
erty of the Document interface returns a collection of all <area> elements and <a> elements in a document with a value for the href attribute. Syntax nodeList = document.links Value An HTMLCollection. 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. Living Standard Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'document.links' in that specification. Obsolete Initial definition ...
Document.readyState - Web APIs
of readiness switch (document.readyState) { case "loading": // The document is still loading. break; case "interactive": // The document has finished loading. We can now access the DOM elements. // But sub-resources such as images, stylesheets and frames are still loading. var span = document.createElement("span"); span.textContent = "A <span> element."; document.
body.appendChild(span); break; case "complete": // The page is fully loaded. console.log("The first CSS rule is: " + document.styleSheets[0].cssRules[0].cssText); break; } readystatechange as an alternative to DOMContentLoaded event // Alternative to DOMContentLoaded event document.onreadystatechange = function () { if (document.readyState === 'interactive') { initApplicatio...
Document.registerElement() - Web APIs
An object with properties prototype to base the custom element on, and extends, an existing tag to extend. Both of these are optional. Example Here is a very simple example: var Mytag = document.registerElement('my-tag'); Now the new tag is registered in the browser. The Mytag variable holds a constructor that you can use to create a my-tag element in the document as follows: document.
body.appendChild(new Mytag()); This inserts an empty my-tag element that will be visible if you use the browser's developer tools. It will not be visible if you use the browser's view source capability. And it won't be visible in the browser unless you add some content to the tag. Here is one way to add content to the new tag: var mytag = document.getElementsByTagName("my-tag")[0]; mytag.textContent...
Document.scrollingElement - Web APIs
The scrollingElement read-only property of the Document interface returns a reference to the Element that scrolls the document. In standards mode, this is the root element of the document, document.documentElement. When in quirks mode, the scrollingElement attribute returns the HTML
body element if it exists and is not potentially scrollable, otherwise it returns null. 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. Working Draft Initial definition ...
Document.title - Web APIs
document.title = newTitle; newTitle is the new title of the document. The assignment affects the return value of document.title, the title displayed for the document (e.g. in the titlebar of the window or tab), and it also affects the DOM of the document (e.g. the content of the <title> element in an HTML document). 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. For HTML documents the initial value of document.title is the text content of the <title> element. For XUL it's the value of th...
Document.vlinkColor - Web APIs
color as a word (e.g., "red") or hexadecimal value (e.g., "#ff0000"). Notes The default value for this property in Mozilla Firefox is purple (#551a8b in hexadecimal). Document.vlinkColor is deprecated in DOM Level 2 HTML. The recommended alternative is to get/set the color of the CSS :visited pseudo-class on HTML <a> elements (e.g., a:visited {color:red;}). Another alternative is document.
body.vLink, although this is deprecated in HTML 4.01 in favor of the CSS alternative. ...
Document: wheel event - Web APIs
reflect the content's scrolling direction. Therefore, do not rely on the wheel event's delta* properties to get the scrolling direction. Instead, detect value changes of scrollLeft and scrollTop in the scroll event. Examples Scaling an element via the wheel This example shows how to scale an element using the mouse (or other pointing device) wheel. ...
Document.write() - Web APIs
nt.open(), which will clear the document. Syntax document.write(markup); Parameters markup A string containing the text to be written to the document. 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. Writing to a document that has already loaded without calling document.open() will automatically call document.open(). After writing, call document.close() to tell the br...
DocumentOrShadowRoot.activeElement - Web APIs
stems, elements that aren't text input elements are not typically focusable by default. Note: Focus (which element is receiving user input events) is not the same thing as selection (the currently highlighted part of the document). You can get the current selection using window.getSelection(). Syntax element = DocumentOrShadowRoot.activeElement Value The Element which currently has focus, <
body> or null if there is no focused element. 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. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.</textarea> <textarea...
Example - Web APIs
// create a new Text node for the second paragraph var newText = document.createTextNode("This is the second paragraph."); // create a new Element to be the second paragraph var newElement = document.createElement("P"); // put the text in the paragraph newElement.appendChild(newText); // and put the paragraph on the end of the document by appending it to // the
BODY (which is the parent of para) para.parentNode.appendChild(newElement); } </script> </head> <
body> <input type="button" value="Change this document." onclick="change()"> <h1>Header</h1> <p>Paragraph</p> </
body> </head> ...
Element.attachShadow() - Web APIs
turns a reference to its ShadowRoot. Elements you can attach a shadow to Note that you can't attach a shadow root to every type of element. There are some that can't have a shadow DOM for security reasons (for example <a>), and more besides. The following is a list of elements you can attach a shadow root to: Any autonomous custom element with a valid name <article> <aside> <blockquote> <
body> <div> <footer> <h1> <h2> <h3> <h4> <h5> <h6> <header> <main> <nav> <p> <section> <span> Syntax var shadowroot = element.attachShadow(shadowRootInit); Parameters shadowRootInit A ShadowRootInit dictionary, which can contain the following fields: mode A string specifying the encapsulation mode for the shadow DOM tree. This can be one of: open: Elements of the...
Element.attributes - Web APIs
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 attribute name and value" onclick="listAttributes();"> <input id="result" type="text" value=""> </p> </form> </
body> </html> Specifications Specification Status Comment DOMThe definition of 'Element.attributes' in that specifi...
Element: auxclick event - Web APIs
on.oncontextmenu = function(e) { e.preventDefault(); } Notice that in addition to capturing the auxclick event using onauxclick, the contextmenu event is also captured, and preventDefault() called on that event, in order to prevent the context menu from popping up after the color change is applied. ...
Element: click event - Web APIs
elements themselves (i.e. event delegation is being used). See this live example for a demonstration. See also Safari's docs on making elements clickable and the definition of "clickable element". Known workarounds for this bug: Set cursor: pointer; on the element or any of its ancestors. Add a dummy onclick="void(0)" attribute to the element or any of its ancestors up to but not including <
body>. Use a typically interactive element (e.g., <a>) instead of one that isn't typically interactive (e.g., <div>). Stop using click event delegation. Safari Mobile considers the following elements to be typically interactive (and thus they aren't affected by this bug): <a> (but it must have an href) <area> (but it must have an href) <button> <img> <input> <label> (but it must be associa...
Element.clientHeight - Web APIs
property is zero for elements with no CSS or inline layout boxes; otherwise, it's the inner height of an element in pixels. It includes padding but excludes borders, margins, and horizontal scrollbars (if present). clientHeight can be calculated as: CSS height + CSS padding - height of horizontal scrollbar (if present). When clientHeight is used on the root element (the <html> element), (or on <
body> if the document is in quirks mode), the viewport's height (excluding any scrollbar) is returned. This is a special case of clientHeight. Note: This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect(). Syntax var intElemClientHeight = element.clientHeight; intElemClientHeight is an integer corresponding to the clientHeight of ele...
Element: compositionend event - Web APIs
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; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } JS const inputElement = document.querySelector...
Element: compositionstart event - Web APIs
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; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } JS const inputElement = document.querySelector...
Element: compositionupdate event - Web APIs
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; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } JS const inputElement = document.querySelector...
Element.hasPointerCapture() - Web APIs
* ... */ // Check whether element still has pointer capture let pointerCap = el.hasPointerCapture(ev.pointerId); if(pointerCap) { // We've still got pointer capture } else { // oops, we've lost pointer capture! } } function init() { const el = document.getElementById("target"); el.onpointerdown = downHandler; } </script> <
body onload="init();"> <div id="target">Touch this element with a pointer.</div> </
body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'hasPointerCapture()' in that specification. Recommendation ...
Element.innerHTML - Web APIs
ed on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup. Replacing the contents of an element Setting the value of innerHTML lets you easily replace the existing contents of an element with new content. 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 "<", thereby essentially converting the HTML into raw text. This is then wrapped in a <pre> element. Then the value of innerHTML is changed to this new string. As a result, the document contents are replaced with a display of the page's entire ...
Element.querySelector() - Web APIs
ning elements is returned by the querySelector() method. If no matches are found, the returned value is null. Exceptions SyntaxError The specified selectors are invalid. Examples Let's consider a few examples. 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. HTML <div> <h5>Original content</h5> <p> inside paragraph ...
Element: wheel event - Web APIs
ntent's scrolling direction. Therefore, do not rely on the wheel event's delta* properties to get the scrolling direction. Instead, detect value changes of scrollLeft and scrollTop of the target in the scroll event. Examples Scaling an element via the wheel This example shows how to scale an element using the mouse (or other pointing device) wheel. ...
Event.currentTarget - Web APIs
dler to several elements. function hide(e){ e.currentTarget.style.visibility = 'hidden'; console.log(e.currentTarget); // When this function is used as an event handler: this === e.currentTarget } var ps = document.getElementsByTagName('p'); for(var i = 0; i < ps.length; i++){ // Console: print the clicked <p> element ps[i].addEventListener('click', hide, false); } // Console: print <
body> document.
body.addEventListener('click', hide, false); // Click around and make paragraphs disappear Note: The value of event.currentTarget is only available while the event is being handled. If you console.log() the event object, storing it in a variable, and then look for the currentTarget key in the console, its value will be null. Instead, you can either directly console.log(event.current...
Event.target - Web APIs
ce to the object onto which the event was dispatched. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event. 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
s (0.005 ms). In older implementations, the value is a DOMTimeStamp, accurate to a millisecond. Example HTML <p> Focus this iframe and press any key to get the current timestamp for the keypress event. </p> <p>timeStamp: <span id="time">-</span></p> JavaScript function getTime(event) { var time = document.getElementById("time"); time.firstChild.nodeValue = event.timeStamp; } document.
body.addEventListener("keypress", getTime); Result Reduced time precision To offer protection against timing attacks and fingerprinting, the precision of Event.timeStamp might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in Firefox...
HTMLElement.offsetParent - Web APIs
The HTMLElement.offsetParent read-only property returns a reference to the element which is the closest (nearest in the containment hierarchy) positioned ancestor element. If there is no positioned ancestor element, the nearest ancestor td, th, table will be returned, or the
body if there are no ancestor table elements either. NOTE: offsetParent returns null in the following situations: The element or its parent element has the display property set to none. The element has the position property set to fixed (firefox returns <
body>). The element is <
body> or <html>. offsetParent is useful because offsetTop and offsetLeft are relative to its padding edge. Syntax parentObj = element.offsetParent; parentObj is an object reference to the element in which the current element is of...
HTMLFormElement.method - Web APIs
The HTMLFormElement.method property represents the HTTP method used to submit the <form>. Unless explicitly specified, the default method is 'get'. 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. Living Standard ...
HTMLFrameSetElement - Web APIs
g Standard From the HTML5 snapshot, the WindowEventHandlers interface now have a onlanguagechange property. HTML5The definition of 'HTMLFrameSetElement' in that specification. Recommendation Snapshot of a previous HTML Living Standard Frames are now obsolete. Implements WindowEventHandlers. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'HTML
BodyElement' in that specification. Obsolete No change from Document Object Model (DOM) Level 1 Specification. Document Object Model (DOM) Level 1 SpecificationThe definition of 'HTML
BodyElement' in that specification. Obsolete Initial definition. ...
contentDocument - Web APIs
If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null. Example of contentDocument var iframeDocument = document.getElementsByTagName("iframe")[0].contentDocument; iframeDocument.
body.style.backgroundColor = "blue"; // This would turn the iframe blue. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLIFrameElement: contentDocument' in that specification. Living Standard ...
HTMLIFrameElement.contentWindow - Web APIs
indow property returns the Window object of an HTMLIFrameElement. You can use this Window object to access the iframe's document and its internal DOM. This attribute is read-only, but its properties can be manipulated like the global Window object. 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. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLIFrameElement: contentWindow' in that specification. Living Standard ...
HTMLIFrameElement.referrerPolicy - Web APIs
nd no header to a less secure destination (HTTPS->HTTP). unsafe-url Send a full URL when performing a same-origin or cross-origin request. This policy will leak origins and paths from TLS-protected resources to insecure origins. Carefully consider the impact of this setting. 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. Candidate Recommendation Added the referrerPolicy attribute. HTML Living StandardThe definition of...
HTMLIFrameElement.src - Web APIs
The HTMLIFrameElement.src property reflects the HTML referrerpolicy attribute of the <iframe> element defining which referrer is sent when fetching the resource. 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. Living Standard Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/brows...
srcdoc - Web APIs
The srcdoc property of the HTMLIFrameElement specifies the content of the page. 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. Living Standard ...
Image() - Web APIs
ent.width and HTMLImageElement.height of the resulting instance. The intrinsic width and height of the image in CSS pixels are reflected through the properties HTMLImageElement.naturalWidth and HTMLImageElement.naturalHeight. If no size is specified in the constructor both pairs of properties have the same values. 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. Living Standard ...
HTMLImageElement.alt - Web APIs
he layout as shown in the result below. They're not crucial to the concept shown in the HTML above, but you may expand the view below if you wish to read the CSS used. View the CSS Editors: If you change the CSS below, please be sure to close the details box using the toggle at the top of the CSS view before saving. Otherwise, readers will find it open by default, which is not the intent here. ...
HTMLImageElement.crossOrigin - Web APIs
age at ${url}`; container.append(errMsg); }); image.crossOrigin = "anonymous"; image.alt = ""; image.src = url; } loadImage(imageUrl); HTML <div class="container"> <p>Here's a paragraph. It's a very interesting paragraph. You are captivated by this paragraph. Keep reading this paragraph. Okay, now you can stop reading this paragraph. ...
HTMLImageElement.currentSrc - Web APIs
Living Standard Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/b...
HTMLImageElement.decode() - Web APIs
les The following example shows how to use the decode() method to control when an image is appended to the DOM. Without a Promise-returning method, you would add the image to the DOM in a load event handler, such as by using the img.onload event handler, and by handling the error in the error event's handler. const img = new Image(); img.src = 'nebula.jpg'; img.decode() .then(() => { document.
body.appendChild(img); }) .catch((encodingError) => { // Do something with the error. }) Specifications Specification Status Comment HTML Living StandardThe definition of 'decode()' in that specification. Living Standard Initial definition. ...
HTMLScriptElement.referrerPolicy - Web APIs
not explicitly specified on the <script> element, it will adopt a higher-level referrer policy, i.e. one set on the whole document or domain. If a higher-level policy is not available, the empty string is treated as being equivalent to no-referrer-when-downgrade. 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. Candidate Recommendation Added the referrerPolicy attribute. HTML Living StandardThe definition of 'HTMLScriptElement: referrerPolicy' in that specification. Living Standard Browser compatib...
HTMLStyleElement.media - Web APIs
ation. Syntax medium = style.media style.media = medium Parameters medium is a string describing a single medium or a comma-separated list. Example <!doctype html> <html> <head> <link id="LinkedStyle" rel="stylesheet" href="document.css" type="text/css" media="screen" /> <style id="InlineStyle" rel="stylesheet" type="text/css" media="screen, print"> p { color: blue; } </style> </head> <
body> <script> alert('LinkedStyle: ' + document.getElementById('LinkedStyle').media); // 'screen' alert('InlineStyle: ' + document.getElementById('InlineStyle').media); // 'screen, print' </script> </
body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLStyleElement' in that specification. Living Standard ...
HTMLTableCellElement - Web APIs
ows this cell must span; this lets a cell occupy space across multiple rows of the table. It reflects the rowspan attribute. HTMLTableCellElement.scope A DOMString indicating the scope of a <th> cell. Header cells can be configured, using the scope property, the apply to a specified row or column, or to the not-yet-scoped cells within the current row group (that is, the same ancestor <thead>, <t
body>, or <tfoot> element). If no value is specified for scope, the header is not associated directly with cells in this way. Permitted values for scope are: col The header cell applies to the following cells in the same column (or columns, if colspan is used as well), until either the end of the column or another <th> in the column establishes a new scope. colgroup The header cell applies t...
HTMLTableElement.bgColor - Web APIs
The HTMLTableElement.bgcolor property represents the background color of the table. The bgColor attribute is deprecated in HTML 4.01. The CSS background-color property should be used instead by modifying the element's style object or using a style rule. Also available on DOM t
body, row and cell objects. Syntax color = table.bgColor table.bgColor = color Parameters color is a string representing a color value. Example // Set table background colour to lightblue var t = document.getElementById('TableA'); t.bgColor = 'lightblue'; Specification DOM Level 2 HTML:HTMLTableElement .bgColor ...
HTMLTableElement.rows - Web APIs
Although the property itself is read-only, the returned object is live and allows the modification of its content. Syntax HTMLCollectionObject = table.rows; Value An HTMLCollection providing a live-updating list of the HTMLTableRowElement objects representing all of the <tr> elements contained in the table. This provides quick access to all of the table rows, without having to manually search for them. ...
HTMLTableElement.tBodies - Web APIs
The HTMLTableElement.tBodies read-only property returns a live HTMLCollection of the bodies in a <table>. Although the property is read-only, the returned object is live and allows the modification of its content. The collection returned includes implicit <t
body> elements. For example: <table> <tr> <td>cell one</td> </tr> </table> The HTML DOM generated from the above HTML will have a <t
body> 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. mytable.tBodies.length; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: tBodies' in that specification. Living Standard ...
Dragging and Dropping Multiple Items - Web APIs
= 0; t < types.length; t++) { output(" " + types[t] + ": "); try { var data = dt.mozGetDataAt(types[t], i); output("(" + (typeof data) + ") : <" + data + " >\n"); } catch (ex) { output("<<error>>\n"); dump(ex); } } } } function output(text) { document.getElementById("output").textContent += text; dump(text); } </script> </head> <
body> <div id="output" style="min-height: 100px; white-space: pre; border: 1px solid black;" ondragenter="document.getElementById('output').textContent = ''; event.stopPropagation(); event.preventDefault();" ondragover="event.stopPropagation(); event.preventDefault();" ondrop="event.stopPropagation(); event.preventDefault(); dodrop(event);"> <div> Fix</div> </div> </
body> </html> ...
KeyboardEvent.altKey - Web APIs
when the event occured. 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. </p> </
body> </html> Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.altkey' in that specification. Obsolete Initial ...
KeyboardEvent.ctrlKey - Web APIs
cates if the control key was pressed (true) or not (false) when the event occured. 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 of 'KeyboardEvent.ctrlKey' in that specification. Obsolete Initi...
KeyboardEvent - Web APIs
alert(`Combination of ctrlKey + ${keyName}`); } else { alert(`Key pressed ${keyName}`); } }, false); document.addEventListener('keyup', (event) => { const keyName = event.key; // As the user releases the Ctrl key, the key is no longer active, // so event.ctrlKey is false. if (keyName === 'Control') { alert('Control key was released'); } }, false); </script> </head> <
body> </
body> </html> Specifications Specification Status Comment UI EventsThe definition of 'KeyboardEvent' in that specification. Working Draft The KeyboardEvent interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementat...
Location - Web APIs
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-space:nowrap;} [title] {position:relative; display:inline-block; box-sizing:border-box; /*border-bottom:.5em solid;*/ line-height:2em; cursor:pointer;} [title]:before {content:attr(title); font-family:monospace; position...
MediaDevices.getSupportedConstraints() - Web APIs
nts dictionary listing the constraints supported by the user agent. Because only constraints supported by the user agent are included in the list, each of these Boolean properties has the value true. Example This example outputs a list of the constraints supported by your browser. ...
MediaDevices.ondevicechange - Web APIs
rt 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 class="left"> <h2>Audio devices:</h2> <ul class="deviceList" id="audioList"></ul> </div> <div class="right"> <h2>Video devices:</h2> <ul class="deviceList" id="videoList"></ul> </div> <div id="log"></div> CSS content
body { font: 14px "Open Sans", "Arial", sans-serif; } video { margin-top: 20px; border: 1px solid black; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } h2 { margin-bottom: 4px; } .left { float:left; width: 48%; margin-right: 2...
MediaElementAudioSourceNode - Web APIs
e variables to store mouse pointer Y coordinate // and HEIGHT of screen var CurY; var HEIGHT = window.innerHeight; // Get new mouse pointer coordinates when mouse is moved // then set new gain value document.onmousemove = updatePage; function updatePage(e) { CurY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? ...
MediaQueryList - Web APIs
to detect when the media query status changes, running a custom function when it does to change the appearence of the page. 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.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...
Recording a media element - Web APIs
will be used to play back the recorded video. Notice that the playback panel doesn't have autoplay set (so the playback doesn't start as soon as media arrives), and it has controls set, which tells it to show the user controls to play, pause, and so forth. Below the playback element is a button for downloading the recorded video. ...
MediaStream Recording API - Web APIs
t(); function handleDataAvailable(event) { console.log("data-available"); if (event.data.size > 0) { recordedChunks.push(event.data); console.log(recordedChunks); download(); } else { // ... ...
Capabilities, constraints, and settings - Web APIs
ows=8></textarea> </div> <div class="rightside"> <h3>Actual audio settings:</h3> <textarea id="audioSettingsText" cols=32 rows=8 disabled></textarea> </div> </div> <div class="button" id="applyButton"> Apply Constraints </div> </div> <video id="video" autoplay></video> <div class="button" id="stopButton"> Stop Video </div> <div id="log"> </div> CSS content
body { font: 14px "Open Sans", "Arial", sans-serif; } video { margin-top: 20px; border: 1px solid black; } .button { cursor: pointer; width: 150px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } .wrapper { margin-bottom: 10px; width: 600px; } .trackrow { height: 200px; }...
Microdata DOM API - Web APIs
ar itemLi = document.createElement('li'); var inner = document.createElement('ul'); for (var name = 0; name < items[item].properties.names.length; name += 1) { var propLi = document.createElement('li'); propLi.appendChild(document.createTextNode(items[item].properties.names[name])); inner.appendChild(propLi); } itemLi.appendChild(inner); outer.appendChild(itemLi); } document.
body.appendChild(outer); If faced with the following from an earlier example: <section itemscope itemtype="http://example.org/animals#cat"> <h1 itemprop="name http://example.com/fn">Hedral</h1> <p itemprop="desc">Hedral is a male american domestic shorthair, with a fluffy <span itemprop="http://example.com/color">black</span> fur with <span itemprop="http://example.com/color">white</span> paws and b...
msPlayToPreferredSourceUri - Web APIs
indows machine which must be unprotected content. A forward slash ("/") is appended to the URI string when it is sent over the network to a PlayTo device. This is done to conform to URI standards. 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 access and protection technology is a set of technologies that can be used to distribute audio/video content more securely over a network, and help prevent the unauthorized use of this content. ...
Node.appendChild() - Web APIs
Fragment, in which case the empty DocumentFragment is returned. Notes Chaining may not work as expected, due to appendChild() returning the child element: let aBlock = document.createElement('block').appendChild( document.createElement('b') ); Sets aBlock to <b></b> only, which is probably not what you want. 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. Living Standard No change from Document Object Model (DOM) Level 3 Core Specification. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.appendChild()...
Node.compareDocumentPosition() - Web APIs
otherNode's relationship to the calling node. More than one bit is set if multiple scenarios apply. 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. Specifications Specification Status Comment ...
Node.contains() - Web APIs
The Node.contains() method returns a Boolean value indicating whether a node is a descendant of a given node, i.e. the node itself, one of its direct children (childNodes), one of the children's direct children, and so on. Syntax node.contains( otherNode ) Example This function checks to see if an element is in the page's
body. As contains is inclusive and determining if the
body contains itself isn't the intention of isInPage this case explicitly returns false. function isInPage(node) { return (node === document.
body) ? false : document.
body.contains(node); } Specifications Specification Status Comment DOMThe definition of 'Node.contains()' in that specification. Living Standard Initial definition ...
Node.isConnected - Web APIs
t in the case of the normal DOM, or the ShadowRoot in the case of a shadow DOM. Syntax var isItConnected = nodeObjectInstance.isConnected Return value A Boolean that is true if the node is connected to its relevant context object, and false if not. ...
Node.rootNode - Web APIs
pmost node in the tree, or the current node if it's the topmost node in the tree. This is found by walking backward along Node.parentNode until the top is reached. Syntax rootNode = node.rootNode; Value A Node object representing the topmost node in the tree. 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. See Whitespace in the DOM and W3C DOM 3 FAQ: Why are some Text nodes empty? for more information...
NodeIterator.detach() - Web APIs
bility only. Originally, it detached the NodeIterator from the set over which it iterates, releasing any resources used by the set and setting the iterator's state to INVALID. Once this method had been called, calls to other methods on NodeIterator would raise the INVALID_STATE_ERR exception. 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 'NodeIterator.detach' in that specification. Living Standard Transform...
NodeIterator.expandEntityReferences - Web APIs
tity reference nodes are visible to the NodeIterator. If this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected. This takes precedence over the value of the NodeIterator.whatToShow method and the associated filter. 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.expandEntityReferences' in that specification. Obsolete Init...
NodeIterator.filter - Web APIs
ect method acceptNode(node) is called on every single node to determine whether or not to accept it. This function should return the constant NodeFilter.FILTER_ACCEPT for cases when the node should be accepted and NodeFilter.FILTER_REJECT for cases when the node should be rejected. 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. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification. ...
NodeIterator.nextNode() - Web APIs
This method returns null when there are no nodes left in the set. In old browsers, as specified in old versions of the specifications, the method may throws the INVALID_STATE_ERR DOMException if this method is called after the NodeIterator.detach()method. Recent browsers never throw. 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.nextNode' in that specification. Living Standard As detach()...
NodeIterator.pointerBeforeReferenceNode - Web APIs
The NodeIterator.pointerBeforeReferenceNode read-only property returns a Boolean flag that indicates whether the NodeFilter is anchored before (if this value is true) or after (if this value is false) the anchor node indicated by the NodeIterator.referenceNode property. 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. Living Standard Initial definition. ...
NodeIterator.previousNode() - Web APIs
turns null when the current node is the first node in the set. In old browsers, as specified in old versions of the specifications, the method may throws the INVALID_STATE_ERR DOMException if this method is called after the NodeIterator.detach()method. Recent browsers never throw. ...
NodeIterator.referenceNode - Web APIs
The NodeIterator.referenceNode read-only returns the Node to which the iterator is anchored; as new nodes are inserted, the iterator remains anchored to the reference node as specified by this property. 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. Living Standard Initial definition. ...
NodeIterator.root - Web APIs
The NodeIterator.root read-only property represents the Node that is the root of what the NodeIterator traverses. 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. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'NodeIterator.root' in that specification. Obsolete Initial ...
NodeIterator.whatToShow - Web APIs
Notation node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree. NodeFilter.SHOW_PROCESSING_INSTRUCTION 64 Shows ProcessingInstruction nodes. NodeFilter.SHOW_TEXT 4 Shows Text nodes. ...
Notification.close() - Web APIs
yntax Notification.close(); Parameters None. Returns Void. Examples In the following snippet, we have a simple function that when called creates an options object and then a new notification. At the end of the function, it also calls close() inside a addEventListener() function to remove the notification when the relevant content has been read on the webpage. function spawnNotification(the
Body, theIcon, theTitle) { var options = {
body: the
Body, icon: theIcon }; var n = new Notification(theTitle,options); document.addEventListener('visibilitychange', function() { if (document.visibilityState === 'visible') { // The tab has become visible so clear the now-stale Notification. n.close(); } }); } Specifications Specification Status C...
Notification.data - Web APIs
in the data option of the Notification() constructor. The notification's data can be any arbitrary data that you want associated with the notification. Syntax var data = Notification.data; Value A structured clone. Examples The following snippet fires a notification; a simple options object is created, then the notification is fired using the Notification() constructor. var options = {
body: 'Do you like my
body?', data: 'I like peas.' } var n = new Notification('Test notification',options); console.log(n.data) // should return 'I like peas.' Specifications Specification Status Comment Notifications APIThe definition of 'data' in that specification. Living Standard Living standard ...
Notification.dir - Web APIs
: adopts the browser's language setting behaviour (the default.) ltr: left to right. rtl : right to left. Note: Most browsers seem to ignore explicit ltr and rtl settings, and just go with the browser-wide setting. Examples The following snippet fires a notification; a simple options object is created, then the notification is fired using the Notification() constructor. var options = {
body: 'Do you like my
body?', dir: 'rtl' } var n = new Notification('Test notification',options); console.log(n.dir) // should return 'rtl' Specifications Specification Status Comment Notifications APIThe definition of 'dir' in that specification. Living Standard Living standard ...
Notification.icon - Web APIs
property of the Notification interface contains the URL of an icon to be displayed as part of the notification, as specified in the icon option of the Notification() constructor. Syntax var icon = Notification.icon; Value A USVString. 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. var notification = new Notification('To do list', {
body: text, icon: img }); Specifications Specification Status Comment Notifications APIThe definition of 'icon' in that specification. Living Standard Living standard ...
Notification.lang - Web APIs
sing a DOMString representing a BCP 47 language tag. See the Sitepoint ISO 2 letter language codes page for a simple reference. Syntax var language = Notification.lang; Value A DOMString specifying the language tag. Examples The following snippet fires a notification; a simple options object is created, then the notification is fired using the Notification() constructor. var options = {
body: 'Do you like my
body?', lang: 'en-US' } var n = new Notification('Test notification',options); console.log(n.lang) // should return 'en-US' Specifications Specification Status Comment Notifications APIThe definition of 'lang' in that specification. Living Standard Living standard ...
Notification.renotify - Web APIs
) constructor. Syntax var renotify = Notification.renotify; Value A Boolean. false is the default; true makes the notification renotify the user. 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. var options = {
body: 'Do you like my
body?', renotify: true } var n = new Notification('Test notification',options); console.log(n.renotify) // should log true Specifications Specification Status Comment Notifications APIThe definition of 'renotify' in that specification. Living Standard Living standard ...
Notification.requireInteraction - Web APIs
e Notification interface returns a Boolean indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automatically. Note: This can be set when the notification is first created by setting the requireInteraction option to true in the options object of the Notification.Notification() constructor. Syntax function spawnNotification(theTitle,the
Body,shouldRequireInteraction) { var options = {
body: the
Body, requireInteraction: shouldRequireInteraction } var n = new Notification(theTitle,options); } Value A Boolean. Specifications Specification Status Comment Notifications APIThe definition of 'requireInteraction' in that specification. Living Standard Living standard. ...
Notification.silent - Web APIs
This is specified in the silent option of the Notification() constructor. Syntax var silent = Notification.silent; Value A Boolean. false is the default; true makes the notification silent. 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. var options = {
body: 'Do you like my
body?', silent: true } var n = new Notification('Test notification', options); console.log(n.silent) // should log true Specifications Specification Status Comment Notifications APIThe definition of 'silent' in that specification. Living Standard Living standard ...
Notification.timestamp - Web APIs
upcoming meeting could be set in the future, whereas a timestamp for a missed message could be set in the past. Syntax var timestamp = Notification.timestamp; Value A DOMTimeStamp. Examples The following snippet fires a notification; a simple options object is created, then the notification is fired using the Notification() constructor. var dts = Math.floor(Date.now()); var options = {
body: 'Do you like my
body?', timestamp: dts } var n = new Notification('Test notification',options); console.log(n.timestamp) // should log original timestamp Specifications Specification Status Comment Notifications APIThe definition of 'timestamp' in that specification. Living Standard Living standard ...
Notification.title - Web APIs
Note: This feature is available in Web Workers. The title read-only property of the Notification interface indicates the title of the notification, as specified in the title parameter of the Notification() constructor. Syntax var title = Notification.title; Value A DOMString. Examples function spawnNotification(the
Body,theIcon,theTitle) { var options = {
body: the
Body, icon: theIcon } var n = new Notification(theTitle,options); console.log(n.title) } Specifications Specification Status Comment Notifications APIThe definition of 'title' in that specification. Living Standard Living standard ...
Notification.vibrate - Web APIs
brate option of the Notification() constructor. Syntax var vibrate = Notification.vibrate; Value A vibration pattern, as specified in the Vibration API spec. 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. var options = {
body: 'Do you like my
body?', vibrate: [200, 100, 200] } var n = new Notification('Test notification',options); console.log(n.vibrate) // should log [200,100,200] Specifications Specification Status Comment Notifications APIThe definition of 'vibrate' in that specification. Living Standard Living standard ...
Notification - Web APIs
ly Instance properties These properties are available only on instances of the Notification object. Notification.actions Read only The actions array of the notification as specified in the constructor's options parameter. Notification.badge Read only The URL of the image used to represent the notification when there is not enough space to display the notification itself. Notification.
body Read only The
body string of the notification as specified in the constructor's options parameter. Notification.data Read only Returns a structured clone of the notification's data. Notification.dir Read only The text direction of the notification as specified in the constructor's options parameter. Notification.lang Read only The language code of the notification as specified in the c...
NotificationAction - Web APIs
to represent the notification when there is not enough space to display the notification itself. Example Notifications can fire notificationclick events on the ServiceWorkerGlobalScope. Here a service worker shows a notification with a single "Archive" action, allowing users to perform this common task from the notification without having to open the website. The user can also click the main
body of the notification to open their inbox instead. self.registration.showNotification("New mail from Alice", { actions: [ { action: 'archive', title: 'Archive' } ] }); self.addEventListener('notificationclick', function(event) { event.notification.close(); if (event.action === 'archive') { // Archive action was clicked archiveEmail(); } else { // Main bod...
Range.commonAncestorContainer - Web APIs
Chair</li> </ul> </li> </ul> </li> <li>Woodwinds <ul> <li>Clarinet</li> <li>Oboe</li> </ul> </li> </ul> CSS The .highlight class created below uses a set of CSS @keyframes to animate a fading outline. ...
ReadableStream.pipeTo() - Web APIs
ing pipe operations can then be aborted via the corresponding AbortController. Return value A Promise that resolves when the piping process has completed. Exceptions TypeError The writableStream and/or readableStream objects are not a writable stream/readable stream, or one or both of the streams are locked. 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. Living Standard Initial definition. ...
ReadableStream.tee() - Web APIs
eam, returning a two-element array containing the two resulting branches as new ReadableStream instances. This is useful for allowing two readers to read a stream simultaneously, perhaps at different speeds. 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. Since a response
body cannot be consumed more than once, you'd need two copies to do this. To cancel the stream you then need to cancel both resulting branches. Teeing a stream will generally lock it for the duration, preventing other readers from locking it. Syntax var teedStreams = readableStream.tee(); Parameters None. Return value An Array containing two ReadableStream instances. Exceptions TypeError T...
ReadableStreamDefaultReader.read() - Web APIs
} 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. It deals with stream chunks not ending on line boundaries and converting from Uint8Array to strings. ...
ReadableStreamDefaultReader - Web APIs
l queue. ReadableStreamDefaultReader.releaseLock() Releases the reader's lock on the stream. Examples In the following example, an artifical Response is created to stream HTML fragments fetched from another resource to the browser. It demonstrates the usage of a ReadableStream in combination with a Uint8Array. ...
Report.type - Web APIs
and crash. 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. "deprecation" console.log(firstReport.type); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'Report.
body' in that specification. Editor's Draft ...
Request.mode - Web APIs
e resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains. cors -- Allows cross-origin requests, for example to access various APIs offered by 3rd party vendors. These are expected to adhere to the CORS protocol. Only a limited set of headers are exposed in the Response, but the
body is readable. navigate -- A mode for supporting navigation. The navigate value is intended to be used only by HTML navigation. A navigate request is created only while navigating between documents. Default mode Requests can be initiated in a variety of ways, and the mode for a request depends on the particular means by which it was initiated. For example, when a Request object is created...
ResizeObserver - Web APIs
spond to changes in an element's size, even if they have nothing to do with the viewport. We also provide a checkbox to turn the observer off and on. If it is turned off, the text will not change in response to the <div>'s width changing. ...
Resource Timing API - Web APIs
This would be a nice place to have a diagram showing the relationships between these segments of the resource loading time. Resource size The PerformanceResourceTiming interface has three properties that can be used to obtain size data about a resource. The transferSize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload
body. The encoded
BodySize property returns the size (in octets) received from the fetch (HTTP or cache), of the payload
body, before removing any applied content-codings. decoded
BodySize returns the size (in octets) received from the fetch (HTTP or cache) of the message
body, after removing any applied content-codings. Other properties The nextHopProtocol property returns the network protocol used ...
Response.headers - Web APIs
nly property of the Response interface contains the Headers object associated with the response. Syntax var myHeaders = response.headers; Value A Headers object. 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. We then fetch this request using fetch(), extract a blob from the response using
Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response headers value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.headers); // returns a Headers{} object response.blo...
Response.ok - Web APIs
se interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. Syntax var myOK = response.ok; Value A Boolean. 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. We then fetch this request using fetch(), extract a blob from the response using
Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note: at the top of the fetch() block we log the response ok value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.ok); // returns true if the response returned successfully ...
Response.status - Web APIs
ace contains the status code of the response (e.g., 200 for a success). Syntax var myStatus = response.status; Value A number (to be precise, an unsigned short). 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. We then fetch this request using fetch(), extract a blob from the response using
Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response status value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.status); // returns 200 response.blob().then(function...
Response.statusText - Web APIs
status message corresponding to the status code (e.g., OK for 200). Syntax var myStatusText = response.statusText; Value A ByteString. The default value is "". 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. We then fetch this request using fetch(), extract a blob from the response using
Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response statusText value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.statusText); // returns "OK" if the response return...
Response.url - Web APIs
s the URL of the response. The value of the url property will be the final URL obtained after any redirects. Syntax var myURL = response.url; Value A USVString. 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. We then fetch this request using fetch(), extract a blob from the response using
Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note that at the top of the fetch() block we log the response URL to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.url); // returns /docs/Web/API/Response/flowers.jpg response.b...
SVGAElement - Web APIs
SVGAElement.download See HTMLAnchorElement.download. SVGAElement.href See HTMLAnchorElement.href. SVGAElement.hreflang Is a DOMString that reflects the hreflang attribute, indicating the language of the linked resource. SVGAElement.ping Is a DOMString that reflects the ping attribute, containing a space-separated list of URLs to which, when the hyperlink is followed, POST requests with the
body PING will be sent by the browser (in the background). Typically used for tracking. SVGAElement.referrerPolicy See HTMLAnchorElement.referrerPolicy. SVGAElement.rel See HTMLAnchorElement.rel. SVGAElement.relList See HTMLAnchorElement.relList. SVGAElement.target Read only It corresponds to the target attribute of the given element. SVGAElement.text Is a DOMString being a synonym for the ...
Selection.collapse() - Web APIs
ation will be within this node. This value can also be set to null -- if null is specified, the method will behave like Selection.removeAllRanges(), i.e. all ranges will be removed from the selection. offset Optional The offset in node to which the selection will be collapsed. If not specified, the default value 0 is used. Examples /* Place the caret at the beginning of an HTML document's
body. */ var
body = document.getElementsByTagName("
body")[0]; window.getSelection().collapse(
body,0); Specifications Specification Status Comment Selection APIThe definition of 'Selection.collapse()' in that specification. Working Draft ...
Selection.containsNode() - Web APIs
node The node that is being looked for in the selection. partialContainment Optional When true, containsNode() returns true when a part of the node is part of the selection. When false, containsNode() only returns true when the entire node is part of the selection. If not specified, the default value false is used. 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. It uses addEventListener() to check for selectionchange events. HTML <p>Can you find the secret word?</p> <p>Hmm, where <span id="secret" style="color:transparent">SECRET</span> could it be?</p> <p id="win" hidden>...
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
tens for a pushsubscriptionchange event and re-subscribes to the lapsed subscription. self.addEventListener("pushsubscriptionchange", event => { event.waitUntil(swRegistration.pushManager.subscribe(event.oldSubscription.options) .then(subscription => { return fetch("register", { method: "post", headers: { "Content-type": "application/json" },
body: JSON.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); When a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe() method. When the returned promise is resolved, we receive the new subscription. This is delivered to the app server using a fetch() call to post a...
SpeechRecognition.abort() - Web APIs
salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition(); var speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.
body.onclick = function() { recognition.start(); console.log('Ready to receive a color command.'); } abortBtn.onclick = function() { recognition.abort(); console.log('Speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('Speech recognition has stopped.'); } Specifications Specification Status Comment Web Speech...
SpeechRecognition.start() - Web APIs
salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition(); var speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.
body.onclick = function() { recognition.start(); console.log('Ready to receive a color command.'); } abortBtn.onclick = function() { recognition.abort(); console.log('Speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('Speech recognition has stopped.'); } Specifications Specification Status Comment Web Speech...
SpeechRecognition.stop() - Web APIs
salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new SpeechRecognition(); var speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.
body.onclick = function() { recognition.start(); console.log('Ready to receive a color command.'); } abortBtn.onclick = function() { recognition.abort(); console.log('Speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('Speech recognition has stopped.'); } Specifications Specification Status Comment Web Speech...
SpeechRecognition - Web APIs
eechRecognition(); var speechRecognitionList = new SpeechGrammarList(); speechRecognitionList.addFromString(grammar, 1); recognition.grammars = speechRecognitionList; recognition.continuous = false; recognition.lang = 'en-US'; recognition.interimResults = false; recognition.maxAlternatives = 1; var diagnostic = document.querySelector('.output'); var bg = document.querySelector('html'); document.
body.onclick = function() { recognition.start(); console.log('Ready to receive a color command.'); } recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textContent = 'Result received: ' + color; bg.style.backgroundColor = color; } Specifications Specification Status Comment Web Speech APIThe definition of 'SpeechRecognit...
Stylesheet.href - Web APIs
f property of the StyleSheet interface returns the location of the style sheet. Syntax uri = stylesheet.href Parameters uri is a string containing the stylesheet's URI. 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. For inline style sheets, the value of this attribute is NULL. This property is read-only in Firefox, Opera, Google Chrome, and Safari, and it is read/w...
StyleSheet.ownerNode - Web APIs
The ownerNode property of the StyleSheet interface returns the node that associates this style sheet with the document. This is usually an HTML <link> or <style> element, but can also return a processing instruction node in the case of <?xml-stylesheet ?>. 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. Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'StyleSheet:...
TextRange - Web APIs
xample gets the TextRange through document.selection, and sets the specified element to be selected. IE9 supports the standard alternative Range. var range = document.selection.createRange(); var element = document.getElementById("test"); range.moveToElementText(element); range.select(); // Selected "SomeTextToBeSelected" <!DOCTYPE html> <html> <head> <title>TextRange Example</title> </head> <
body> <p id="test">SomeTextToBeSelected</p> </
body> </html> Notes Use TextRange to Operate the Selection Valid only under IE9. The selection interface should be used first, if the browser allows it. document.selection property returns a non-standard selection object, and the selection.createRange() method creates a TextRange object consistent with the currently selection. var sel = document.s...
TreeWalker.currentNode - Web APIs
The TreeWalker.currentNode property represents the Node on which the TreeWalker is currently pointing at. 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! Specifications Specification Status Comment DOMThe definition of 'TreeWalker.currrentNode' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'TreeWalker.cu...
TreeWalker.expandEntityReferences - Web APIs
dren of entity reference nodes are visible to the TreeWalker. If this value is false, the children of entity reference nodes (as well as all of their descendants) are rejected. This takes precedence over the value of the TreeWalker.whatToShow method and the associated filter. 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. Obsolete Initial definition. ...
TreeWalker.filter - Web APIs
y property returns a NodeFilter that is the filtering object associated with the TreeWalker. When creating the TreeWalker, the filter object is passed in as the third parameter, and its method NodeFilter.acceptNode() is called on every single node to determine whether or not to accept it. 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. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and...
TreeWalker.firstChild() - Web APIs
The TreeWalker.firstChild() method moves the current Node to the first visible child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, returns null and the current node is not changed. 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. Living Standard No change from Document Object Model (DOM) Level 2 Travers...
TreeWalker.lastChild() - Web APIs
The TreeWalker.lastChild() method moves the current Node to the last visible child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, returns null and the current node is not changed. 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. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range ...
TreeWalker.nextNode() - Web APIs
The TreeWalker.nextNode() method moves the current Node to the next visible node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, returns null and the current node is not changed. 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. Living Standard No change from Document Object Model (DOM) Level 2 Tra...
TreeWalker.nextSibling() - Web APIs
The TreeWalker.nextSibling() method moves the current Node to its next sibling, if any, and returns the found sibling. If there is no such node, return null and the current node is not changed. 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. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specificatio...
TreeWalker.parentNode() - Web APIs
The TreeWalker.parentNode() method moves the current Node to the first visible ancestor node in the document order, and returns the found node. If no such node exists, or if it is above the TreeWalker's root node, returns null and the current node is not changed. 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. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Sp...
TreeWalker.previousNode() - Web APIs
the current Node to the previous visible node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists,or if it is before that the root node defined at the object construction, returns null and the current node is not changed. 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. Living Standard No change from Document Object Model (DOM) ...
TreeWalker.previousSibling() - Web APIs
The TreeWalker.previousSibling() method moves the current Node to its previous sibling, if any, and returns the found sibling. If there is no such node, return null and the current node is not changed. 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. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification Document Object...
TreeWalker.root - Web APIs
The TreeWalker.root read-only property returns the node that is the root of what the TreeWalker traverses. 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. Living Standard No change from Document Object Model (DOM) Level 2 Traversal and Range Specification Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'TreeWalker.root' in that specification. Obsolete Initial definition. ...
TreeWalker.whatToShow - Web APIs
osition of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree. NodeFilter.SHOW_PROCESSING_INSTRUCTION 64 Shows ProcessingInstruction nodes. NodeFilter.SHOW_TEXT 4 Shows Text nodes. ...
WebGLRenderingContext - Web APIs
d clear() to draw a square in the center of the canvas, by specifying its position and size in pixels. In the first canvas, we get the desired result. In the second, the square has the wrong shape, size, and position. ...
Basic scissoring - Web APIs
L. We first tweak WebGL state. In this case, enabling the scissor test and establishing a rectangular mask. Only when the WebGL state has been satisfactorily tweaked, we execute the drawing command (in this case, clear()) that starts the processing of fragments down the graphics pipeline. ...
Canvas size and WebGL - Web APIs
clear() to draw a square in the center of the canvas, by specifying its position and size in pixels. In the first canvas, we get the desired result. In the second, the square has the wrong shape, size, and position. ...
Clearing by clicking - Web APIs
d the WebGL function calls inside the event handler function. <p>A very simple WebGL program that still shows some color and user interaction.</p> <p>You can repeatedly click the empty canvas or the button below to change color.</p> <canvas id="canvas-view">Your browser does not seem to support HTML5 canvas.</canvas> <button id="color-switcher">Press here to switch color</button>
body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : inline-block; font-size : inherit; margin : auto; padding : 0.6em; } window.addEventListener("load", function setupWebGL (evt) { "use strict" // Cleaning after ourselves. The event handler removes...
Clearing with colors - Web APIs
e note that color in WebGL is usually in RGBA format, that is four numerical components for red, green, blue and alpha (opacity). Therefore, clearColor() takes four arguments. <p>A very simple WebGL program that shows some color.</p> <!-- Text within a canvas element is displayed only if canvas is not supported. --> <canvas>Your browser does not seem to support HTML5 canvas.</canvas>
body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } // Run everything inside window load event handler, to make sure // DOM is fully loaded and styled before trying to manipulate it, // and to not mess up the global scope. We are giving the event // handler a name (setupWebGL) so...
Color masking - Web APIs
occurs later in the pipeline, and modifies the pixel color value, so the final result on the screen is that of the clear color, tinted by the color mask. ...
Detect WebGL - Web APIs
g the state of the graphics machine within a single context interface is not unique to WebGL. This is also done in other graphics {{Glossary("API")}}, such as the canvas 2D rendering context. However, the properties and variables you can tweak are different for each API. <p>[ Here would go the result of WebGL feature detection ]</p> <button>Press here to detect WebGLRenderingContext</button>
body { text-align : center; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } // Run everything inside window load event handler, to make sure // DOM is fully loaded and styled before trying to manipulate it. window.addEventListener("load", function() { var paragraph = document.querySelector("p"), button = document.querySelector("button"); // Adding...
Hello GLSL - Web APIs
wsers. If the canvas remains blank, you can check the output of the next example, which draws exactly the same thing. But remember to read through the explanations and code on this page, before moving on to the next. Hello World program in GLSL A very simple first shader program. ...
Hello vertex attributes - Web APIs
g and user interaction by sending user input to the shader using vertex attributes. Hello World program in GLSL How to send input to a shader program by saving data in GPU memory. <p>First encounter with attributes and sending data to GPU. ...
Raining rectangles - Web APIs
xample demonstrates how to integrate the WebGL function calls within a game loop. The game loop is responsible for drawing the animation frames, and keeping the animation responsive to user input. Here, the game loop is implemented using timeouts. <p>You caught <strong>0</strong>. ...
Scissor animation - Web APIs
me. The clear color state of WebGL remains at the set value, until we change it again when a new square is created. ...
Textures from code - Web APIs
ration of procedural texturing with fragment shaders. That is, using code to generate textures for use in shading WebGL objects. Drawing textures with code Texturing a point sprite with calculations done per-pixel in the fragment shader. <p>Texture from code. ...
Getting started with WebGL - Web APIs
series of articles introduces WebGL itself; however, there are a number of frameworks available that encapsulate WebGL's capabilities, making it easier to build 3D applications and games, such as THREE.js and BABYLON.js. Preparing to render in 3D The first thing you need in order to use WebGL for rendering is a canvas. The HTML fragment below declares a canvas that our sample will draw into. <
body> <canvas id="glCanvas" width="640" height="480"></canvas> </
body> Preparing the WebGL context The main() function in our JavaScript code, is called when our script is loaded. Its purpose is to set up the WebGL context and start rendering content. // // start here // function main() { const canvas = document.querySelector("#glCanvas"); // Initialize the GL context const gl = canvas.get...
Signaling and video calling - Web APIs
call, is defined and configured to start disabled (setting this as our default for when no call is connected) and apply the function hangUpCall() on click. This function's role is to close the call, and send a signalling server notification to the other peer, requesting it also close. The JavaScript code We'll divide this code into functional areas to more easily describe how it works. The main
body of this code is found in the connect() function: it opens up a WebSocket server on port 6503, and establishes a handler to receive messages in JSON object format. This code generally handles text chat messages as it did previously. Sending messages to the signaling server Throughout our code, we call sendToServer() in order to send messages to the signaling server. This function uses the WebSoc...
Writing WebSocket servers - Web APIs
Forbidden if you don't like what you see. However, be warned that non-browser agents can send a faked Origin. Most applications reject requests without this header. If any header is not understood or has an incorrect value, the server should send a 400 ("Bad Request")} response and immediately close the socket. As usual, it may also give the reason why the handshake failed in the HTTP response
body, but the message may never be displayed (browsers do not display it). If the server doesn't understand that version of WebSockets, it should send a Sec-WebSocket-Version header back that contains the version(s) it does understand. In the example above, it indicates version 13 of the WebSocket protocol. The most interesting header here is Sec-WebSocket-Key. Let's look at that next. Note: Regul...
Web Video Text Tracks Format (WebVTT) - Web APIs
e these tracks and the data needed to perform the playback of the text at the correct times. WebVTT files The MIME type of WebVTT is text/vtt. A WebVTT file (.vtt) contains cues, which can be either a single line or multiple lines, as shown below: WEBVTT 00:01.000 --> 00:04.000 - Never drink liquid nitrogen. 00:05.000 --> 00:09.000 - It will perforate your stomach. - You could die. WebVTT
body The structure of a WebVTT consists of the following components, some of them optional, in this order: An optional byte order mark (BOM). The string "WEBVTT". An optional text header to the right of WEBVTT. There must be at least one space after WEBVTT. You could use this to add a description to the file. You may use anything in the text header except newlines or the string "-->"...
Geometry and reference spaces in WebXR - Web APIs
pands upon the geometry of WebGL, and how the positions and orientations of objects--both physical and virtual--are described in relation to one another using spaces and, in particular, reference spaces. The article Spatial tracking in WebXR builds upon the information provided here to cover how the physical position and orientation of the user's head, as well as potentially other parts of their
body such as the hands, are mapped into the digital world, as well as how the relative positions of both physical and virtual objects are tracked as they move around, so that the scene can be properly rendered and composited. Fundamentals of 3D geometry While we'll examine here the required math operations used to compute the positions, orientations, and movement of objects in virtual space--plus th...
Rendering and the WebXR frame animation callback - Web APIs
Updating object positions Most (though not all) scenes include some form of animation, in which things move and react to one another in appropriate ways. For example, a virtual reality or augmented reality game might have enemy non-player characters being controlled by the computer and moving around the scene. Not only are their locations in the world changing over time, but each NPC likely has
body parts or components that are moving in relation to one another. Arms and legs swing as a creature walks, heads bob and turn, hair bounces and sways, torsos expand and contract as the character breathes. In addition, there may be objects and structures in motion. In a sports game, there may be a ball arcing through the air, its movement needing to be simulated. In racing games there may be cars o...
Starting up and shutting down a WebXR session - Web APIs
ction shutdownXR(session) { if (session) { await session.end(); /* At this point, WebXR is fully shut down */ } } When shutdownXR() returns to its caller, the WebXR session is fully and safely shut down. If you have work that must be done when the session ends, such as releasing resources and the like, you should do that work in your end event handler rather than in your main code
body. That way, you handle the cleanup regardless of whether the shutdown was automatically or manually triggered. Detecting when the session has ended As previously established, you can detect when the WebXR session has ended--whether because you've called its end() method, the user turned off their headset, or some sort of irresolvable error occurred in the XR system--by watching for the end event...
WebXR Device API - Web APIs
his guide, the required concepts of 3D geometry are briefly reviewed, and the fundamentals of how that geometry is represented in WebXR are detailed. Learn how reference spaces are used to position objects--and the viewer--and the differences among the available types of reference space, as well as their use cases. Spatial tracking in WebXR This guide describes how objects--including the user's
body and its parts--are located in space, and how their movement and orientation relative to one another is monitored and managed over time. This article explains the relationship between spaces, poses, viewers, and views. Rendering and the WebXR frame animation callback Starting with how you schedule frames to be rendered, this guide then continues to cover how to determine the placement of objects...
Web audio spatialization basics - Web APIs
First, we'll get references to the elements we want to move, then we'll store references to the values we'll change when we set up CSS transforms to actually do the movement. ...
Using the Web Speech API - Web APIs
ment.querySelector('.output'); var bg = document.querySelector('html'); var hints = document.querySelector('.hints'); var colorHTML= ''; colors.forEach(function(v, i, a){ console.log(v, i); colorHTML += '<span style="background-color:' + v + ';"> ' + v + ' </span>'; }); hints.innerHTML = 'Tap/click then say a color to change the background color of the app. ...
Window: blur event - Web APIs
er property onblur Sync / Async Sync Composed Yes Examples Live example This example changes the appearance of a document when it loses focus. It uses addEventListener() to monitor focus and blur events. HTML <p id="log">Click on this document to give it focus.</p> CSS .paused { background: #ddd; color: #555; } JavaScript function pause() { document.
body.classList.add('paused'); log.textContent = 'FOCUS LOST!'; } function play() { document.
body.classList.remove('paused'); log.textContent = 'This document has focus. Click outside the document to lose focus.'; } const log = document.getElementById('log'); window.addEventListener('blur', pause); window.addEventListener('focus', play); Result Specifications Specification Sta...
Window.captureEvents() - Web APIs
USEDOWN, Event.MOUSEMOVE, Event.MOUSEOUT, Event.MOUSEOVER, Event.MOUSEUP, Event.MOVE, Event.RESET, Event.RESIZE, Event.SELECT, Event.SUBMIT, Event.UNLOAD. Example <!DOCTYPE html> <html lang="en"> <head> <!-- ... --> <script> function reg() { window.captureEvents(Event.CLICK); window.onclick = page_click; } function page_click() { alert('page click event detected!'); } </script> </head> <
body onload="reg();"> <p>click anywhere on this page.</p> </
body> </html> Notes Events raised in the DOM by user activity (such as clicking buttons or shifting focus away from the current document) generally pass through the high-level window and document objects first before arriving at the object that initiated the event. When you call the captureEvents() method on the window, events of the type...
Window.defaultStatus - Web APIs
ure is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Summary Gets/sets the status bar text for the given window. Syntax var sMsg = window.defaultStatus; window.defaultStatus = sMsg; Parameters sMsg is a string containing the text to be displayed by default in the statusbar. 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. Specification HTML5 ...
Window.devicePixelRatio - Web APIs
pixel ratio information. <div class="container"> <div class="inner-container"> <p>This example demonstrates the effect of zooming the page in and out (or moving it to a screen with a different scaling factor) on the value of the property <code>Window.devicePixelRatio</code>. ...
Window: focus event - Web APIs
r property onfocus Sync / Async Sync Composed Yes Examples Live example This example changes the appearance of a document when it loses focus. It uses addEventListener() to monitor focus and blur events. HTML <p id="log">Click on this document to give it focus.</p> CSS .paused { background: #ddd; color: #555; } JavaScript function pause() { document.
body.classList.add('paused'); log.textContent = 'FOCUS LOST!'; } function play() { document.
body.classList.remove('paused'); log.textContent = 'This document has focus. Click outside the document to lose focus.'; } const log = document.getElementById('log'); window.addEventListener('blur', pause); window.addEventListener('focus', play); Result Specifications Specification Sta...
Window.frames - Web APIs
M element (i.e., window.frames[0] is the same thing as document.getElementsByTagName("iframe")[0].contentWindow). For more details about the returned value, refer to this thread on mozilla.dev.platform. 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. Living Standard HTML5The definition of 'Window.frames' in that specification. Recommendation ...
Window: load event - Web APIs
s 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>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 const log = document.querySelector('.event-log-contents'); const reload = document.quer...
Window.locationbar - Web APIs
Returns the locationbar object, whose visibility can be checked. Syntax objRef = window.locationbar Example The following complete HTML example shows how the visible property of the locationbar object is used. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Various DOM Tests</title> <script> var visible = window.locationbar.visible; </script> </head> <
body> <p>Various DOM Tests</p> </
body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.locationbar' in that specification. Living Standard HTML5The definition of 'Window.locationbar' in that specification. Recommendation ...
Window.menubar - Web APIs
The Window.menubar property returns the menubar object, whose visibility can be checked. Syntax objRef = window.menubar Example The following complete HTML example demonstrates how the visible property of the menubar object is used. <html> <head> <title>Various DOM Tests</title> <script> var visible = window.menubar.visible; </script> </head> <
body> <p>Various DOM Tests</p> </
body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.menubar' in that specification. Living Standard HTML5The definition of 'Window.menubar' in that specification. Recommendation ...
Window.ondragdrop - Web APIs
a file is dragged and dropped onto this window, the alert is fired. Note how event.stopPropagation(); prevents the browser from loading the dropped tab, link or file. <html> <head><title>dragdroptest</title> <script type="text/javascript"> window.addEventListener("dragdrop", testfunc, false); function testfunc(event) { alert("dragdrop!"); event.stopPropagation(); } </script> </head> <
body> I am
bodytext </
body> </html> Specification Not part of specification. ...
Window.personalbar - Web APIs
his functionality can not be used in web pages. EnablePrivilege is disabled in Firefox 15 and will be removed in Firefox 17. <!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. Also be aware that dynamically updating the visibilty of the various toolbars can change the size of the window rather dramati...
Window.scrollX - Web APIs
crollX; // always true For cross-browser compatibility, use window.pageXOffset instead of window.scrollX. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example: var x = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.
body.parentNode || document.
body).scrollLeft; var y = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.
body.parentNode || document.
body).scrollTop; Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'window.scrollX' in that specification. Working Draft ...
Window.scrollY - Web APIs
rsions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example: var supportPageOffset = window.pageXOffset !== undefined; var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"); var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.
body.scrollLeft; var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.
body.scrollTop; Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'window.scrollY' in that specification. Working Draft ...
Window.scrollbars - Web APIs
The Window.scrollbars property returns the scrollbars object, whose visibility can be checked. Syntax objRef = window.scrollbars Example The following complete HTML example shows how the visible property of the scrollbars object is used. <!doctype html> <html> <head> <title>Various DOM Tests</title> <script> let visibleScrollbars = window.scrollbars.visible; </script> </head> <
body> <p>Various DOM Tests</p> </
body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'Window.scrollbars' in that specification. Living Standard HTML5The definition of 'Window.scrollbars' in that specification. Recommendation ...
Window.statusbar - Web APIs
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. Also be aware that dynamically updating the visibilty of the various toolbars can change the size of the window rather dramati...
Window.toolbar - Web APIs
ivilege this functionality can not be used in web pages. EnablePrivilege is disabled in Firefox 15 and will be removed in Firefox 17. <!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. Also be aware that dynamically updating the visibilty of the various toolbars can change the size of the window rather dramatic...
WindowEventHandlers.onhashchange - Web APIs
The WindowEventHandlers.onhashchange property of the WindowEventHandlers mixin is the EventHandler for processing hashchange events. The hashchange event fires when a window's hash changes (see Window.location and HTMLHyperlinkElementUtils.hash). Syntax Using an event handler: window.onhashchange = funcRef; Using an HTML event handler: <
body onhashchange="funcRef();"> Using an event listener: To add an event listener, use addEventListener(): window.addEventListener("hashchange", funcRef, false); Parameters funcRef A reference to a function. Examples Using an event handler This example uses an event handler (window.onhashchange) to check the new hash value whenever it changes. If it equals #cool-feature, the script logs a message to the console. function locationHashChang...
WindowEventHandlers - Web APIs
Each of these interfaces can implement additional specific event handlers. Note: WindowEventHandlers is a mixin and not an interface; you can't actually create an object of type WindowEventHandlers. Properties The events properties, of the form onXYZ, are defined on the WindowEventHandlers, and implemented by Window, and WorkerGlobalScope for Web Workers. WindowEventHandlers.onafterprint Is an EventHandler representing the code to be called when the afterprint event is raised. ...
XDomainRequest.responseText - Web APIs
Returns the response
body of an XDomainRequest as a string. Note: This property is valid during the XDomainRequest.onprogress and XDomainRequest.onload events. Syntax var response = xdr.responseText; This sets response to contain the response
body of the request, as a string. Example var response = xdr.responseText; Specification Not part of any specification. ...
XDomainRequest - Web APIs
ny other browser, you need to use standard HTTP access control. This interface can send both GET and POST requests. Syntax var xdr = new XDomainRequest(); Returns a new XDomainRequest object, which can then be used to make and manage these requests. Properties XDomainRequest.timeout Gets or sets the amount of time until a request times out. XDomainRequest.responseText Gets the response
body as a string. Methods XDomainRequest.open() Opens the request, specifing the method (GET/POST) and URL. XDomainRequest.send() Sends the request. POST data is specified in this method. XDomainRequest.abort() Aborts the request. Event handlers XDomainRequest.onprogress A handler for when the request has made progress between the send method call and the onload event. XDomainRequest.
HTML in XMLHttpRequest - Web APIs
pport is only available if the responseType property has been set to "document". This limitation avoids wasting time parsing HTML uselessly when legacy code uses XMLHttpRequest in the default mode to retrieve responseText for text/html resources. Also, this limitation avoids problems with legacy code that assumes that responseXML is null for HTTP error pages (which often have a text/html response
body). Usage Retrieving an HTML resource as a DOM using XMLHttpRequest works just like retrieving an XML resource as a DOM using XMLHttpRequest, except you can't use the synchronous mode and you have to explicitly request a document by assigning the string "document" to the responseType property of the XMLHttpRequest object after calling open() but before calling send(). var xhr = new XMLHttpReques...
XMLHttpRequest.readyState - Web APIs
UNSENT The XMLHttpRequest client has been created, but the open() method hasn't been called yet. OPENED open() method has been invoked. During this state, the request headers can be set using the setRequestHeader() method and the send() method can be called which will initiate the fetch. HEADERS_RECEIVED send() has been called and the response headers have been received. LOADING Response's
body is being received. If responseType is "text" or empty string, responseText will have the partial text response as it loads. DONE The fetch operation is complete. This could mean that either the data transfer has been completed successfully or failed. The state names are different in versions of Internet Explorer earlier than 11. Instead of UNSENT, OPENED, HEADERS_RECEIVED, LOADING and DONE, ...
XMLHttpRequest.setRequestHeader() - Web APIs
counter a "not allowed by Access-Control-Allow-Headers in preflight response" exception when you send requests across domains. In this situation, you need to set up the Access-Control-Allow-Headers in your response header at server side. Syntax XMLHttpRequest.setRequestHeader(header, value) Parameters header The name of the header whose value is to be set. value The value to set as the
body of the header. Return value undefined. Specifications Specification Status Comment XMLHttpRequestThe definition of 'setRequestHeader()' in that specification. Living Standard WHATWG living standard ...
XMLHttpRequest - Web APIs
LHttpRequest.onreadystatechange An EventHandler that is called whenever the readyState attribute changes. XMLHttpRequest.readyState Read only Returns an unsigned short, the state of the request. XMLHttpRequest.response Read only Returns an ArrayBuffer, Blob, Document, JavaScript object, or a DOMString, depending on the value of XMLHttpRequest.responseType, that contains the response entity
body. XMLHttpRequest.responseText Read only Returns a DOMString that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent. XMLHttpRequest.responseType Is an enumerated value that defines the response type. XMLHttpRequest.responseURL Read only Returns the serialized URL of the response or the empty string if the URL is null. XMLHttpRequ...
XRInputSource.handedness - Web APIs
The input controller is being held in, worn on, or is attached to the user's right hand. Usage notes If the input source is not a device associated with a user's hand (whether by being held, attached, or worn), the value of handedness is none. 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. function updateInputSources(session, frame, refSpace) { for (let source of session.inputSources) { if (source.gripSpace) { let gripPose = frame.getPose(source.gripSpace, refSpace...
XRPose.emulatedPosition - Web APIs
rom other sources to determine the user's position, so the value of emulatedPosition is false. The same notion applies not just to the user's head, but to any object. A hand controller that can directly report its position would have a value of false for this property as well. If its position is computed as an offset from another object (such as by basing it off the model representing the user's
body), then this value is true. This information is important because devices whose position is emulated are prone to their offset drifting relative to the real world space over time. This is because emulating a position based on accelerometer inputs and models tends to introduce minor errors which accumulate over time. Specifications Specification Status Comment WebXR D...
msCapsLockWarningOff - Web APIs
sOff() { if (document.msCapsLockWarningOff == false) { document.msCapsLockWarningOff = true; document.getElementById("caps").innerHTML = "Warning off"; } else { document.msCapsLockWarningOff = false; document.getElementById("caps").innerHTML = "Warning on"; } } </script> </head> <
body> <label>Type a password: <input type="password" /></label><br /> <button id="caps" onclick="capsOff();">Warning off</button> </
body> </html> ...
Using the aria-invalid attribute - Accessibility
if (invalid) { elem.setAttribute("aria-invalid", "true"); updateAlert(aMsg); } else { elem.setAttribute("aria-invalid", "false"); updateAlert(); } } The snippet below shows the alert functions, which add (or remove) the error message: function updateAlert(msg) { var oldAlert = document.getElementById("alert"); if (oldAlert) { document.
body.removeChild(oldAlert); } if (msg) { var 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...
ARIA: application role - Accessibility
me 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. Think hard on if you actually need it and cannot just use a set of other, known, widgets to accomplish the same task. If used, the application role should be added to the lowest common container possible, not on the <
body> element, for example. Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'application' in that specification. Recommendation Precedence order Applying the application role will cause this and all of the descendant elements of this element to be treated like application content, not web content. Any reading m...
ARIA: banner role - Accessibility
a site-specific search tool, and is generally what your marketing team would call the header or top banner of the site. If the header element technique is not being used for that banner, a declaration of role="banner" should be used to define a banner landmark to assistive technologies. Assistive technologies can identify the main header element of a page as the banner if is a descendant of the
body element, and not nested within an article, aside, main, nav or section subsection. Each page may have a banner landmark, but each page should be limited to only one header with the role of banner. In the case of a page containing nested document and/or application roles, each nested document or application role may also have one banner landmark. If a page includes more than one banner landmark, ...
Web applications and ARIA FAQ - Accessibility
t HTML5-aware, you may want to consider gracefully degrading to the use of ARIA where necessary. So, using the example of a progress bar, you can degrade gracefully to a role="progressbar" in cases where the <progressbar> tag isn't supported. Here is an example of the markup used for an HTML5 progress bar: <!DOCTYPE html> <html> <head><title>Gracefully degrading progress bar</title></head> <
body> <progress id="progress-bar" value="0" max="100">0% complete</progress> <button id="update-button">Update</button> </
body> </html> ... and here is the JavaScript code that will ensure the progress bar still works in older browsers: var progressBar = document.getElementById("progress-bar"); // Check to see if the browser supports the HTML5 <progress> tag. var supportsHTML5Progress = (...
Web accessibility for seizures and physical reactions - Accessibility
) There is a powerful tool available to developers via Window.matchMedia(). A great resource is MDN's document on Window.matchMedia() media update feature The more often the screen is refreshed, the more stable it appears to the human eye, and the less it "flickers". The vast majority of modern technology refreshes at a rate that does not cause problems with photosensitivity. However, not every
body is wealthy enough to be able to afford the most recent technology: older or underpowered computers can have low refresh rates. AbilityNet's Factsheet (November 2015) Computers and Epilepsy (pdf) describes more of the details on refresh rates. A very old article, Tech Republic's Epilepsy and CRT/LCD screen flicker, had an interesting response concerning the refresh rates in Hz. "This effect is...
Color contrast - Accessibility
The color contrast between background and foreground content (that is, usually text) should be great enough to ensure legibility. When designing readable interfaces for different vision capabilities, the WCAG guidelines recommend the following contrast ratios: Type of content Minimum ratio (AA rating) Enhanced ratio (AAA rating)
Body text 4.5 : 1 7 : 1 Large-scale text (120-150% larger than
body text) 3 : 1 4.5 : 1 Active user interface components and graphical objects such as icons and graphs 3 : 1 Not defined These ratios do not apply to "incidental" text, such as inactive controls, logotypes, or purely decorative text. See the Solution section below for further information. Having good color contrast on your ...
-webkit-mask-attachment - CSS: Cascading Style Sheets
the mask image. fixed If fixed is specified, the mask image does not scroll with its containing element, instead remaining stationary within the viewport. 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. ...
:empty - CSS: Cascading Style Sheets
lime; } Syntax :empty Examples HTML <div class="box"><!-- I will be lime. --></div> <div class="box">I will be pink.</div> <div class="box"> <!-- I will be pink in older browsers because of the whitespace around this comment. --> </div> <div class="box"> <p><!-- I will be pink in all browsers because of the non-collapsible whitespace and elements around this comment. --></p> </div> CSS
body { display: flex; justify-content: space-around; } .box { background: pink; height: 80px; width: 80px; } .box:empty { background: lime; } Result Accessibility concerns Assistive technology such as screen readers cannot parse interactive content that is empty. All interactive content must have an accessible name, which is created by providing a text value for the interactive con...
aural - CSS: Cascading Style Sheets
SS media type--which has been deprecated in favor of the speech media type--was used to specify a block of CSS that applied only when the content is being presented using a speech synthesis device. @media aural { /* speech-specific styles here */ } Updating existing CSS to use the speech media type should be as simple as replacing aural with speech. 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. Deprecated Initial definition. ...
display-mode - CSS: Cascading Style Sheets
minimal-ui The application will look and feel like a standalone application, but will have a minimal set of UI elements for controlling navigation. The elements will vary by browser. browser browser The application opens in a conventional browser tab or new window, depending on the browser and platform. (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. Working Draft Initial definition. ...
orientation - CSS: Cascading Style Sheets
Syntax The orientation feature is specified as a keyword value chosen from the list below. Keyword values portrait The viewport is in a portrait orientation, i.e., the height is greater than or equal to the width. landscape The viewport is in a landscape orientation, i.e., the width is greater than the height. 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 'orientation' in that specification. Candidate Recommendation No c...
@viewport - CSS: Cascading Style Sheets
ht and max-height. zoom Sets the initial zoom factor. min-zoom Sets the minimum zoom factor. max-zoom Sets the maximum zoom factor. user-zoom Controls whether or not the user should be able to change the zoom factor. orientation Controls the document's orientation. viewport-fit Controls the display of the document on non-rectangular displays. 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. Working Draft Defined t...
Box-shadow generator - CSS: Cascading Style Sheets
ft: 34px; background-position: center left 10px; } .ui-checkbox .left { padding-right: 34px; padding-left: 1.666em; background-position: center right 10px; } .ui-checkbox > label:hover { cursor: pointer; } .ui-checkbox > input:checked + label { background-image: url("https://mdn.mozillademos.org/files/5681/checked.png"); background-color: #379B4A; } /* * BOX SHADOW GENERATOR TOOL */
body { max-width: 1000px; height: 800px; margin: 20px auto 0; font-family: "Segoe UI", Arial, Helvetica, sans-serif; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; } #container { width: 100%; padding: 2px; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-s...
Typical use cases of Flexbox - CSS: Cascading Style Sheets
s an image or other element to one side and text to the right. Ideally a media object should be able to be flipped -- moving the image from left to right. We see this pattern everywhere, used for comments, and anywhere we need to display images and descriptions. With flexbox we can allow the part of the media object containing the image to take its sizing information from the image, and then the
body of the media object flexes to take up the remaining space. In the live example below you can see our media object. I have used the alignment properties to align the items on the cross axis to flex-start, and then set the .content flex item to flex: 1. As with our column layout card pattern above, using flex: 1 means this part of the card can grow. Some things that you might want to try in thi...
Stacking context example 1 - CSS: Cascading Style Sheets
ass="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; border: 1px dashed #990000; background-co...
Using CSS transitions - CSS: Cascading Style Sheets
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 <
body> <p>The box below combines transitions for: width, height, background-color, transform. Hover over the box to see these properties animated.</p> <div class="box">Sample</div> </
body> CSS Content .box { border-style: solid; border-width: 1px; display: block; width: 100px; height: 100px; background-color: #0000FF; transition: width 2s, height 2s, background-co...
Questions about CSS - CSS: Cascading Style Sheets
With CSS, the sources of style definition for a given document element are in this order of precedence: The STYLE attribute on an individual element tag The STYLE element that defines a specific style sheet containing style declarations or a LINK element that links to a separate document containing the STYLE element. In a Web page, the STYLE element is placed between the TITLE statement and the
BODY statement. An imported style sheet, using the CSS @import notation to automatically import and merge an external style sheet with the current style sheet Style attributes specified by the viewer to the browser The default style sheet assumed by the browser In general, the Web page creator's style sheet takes precedence, but it's recommended that browsers provide ways for the viewer to overri...
Sticky footers - CSS: Cascading Style Sheets
viewport when content is short. If the content of the page extends past the viewport bottom, the footer then sits below the content as normal. 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. You could also achieve this for a full page by setting a min-height of 100vh on the <
body> and then using it as your grid container. Choices made In the above example we achieve the sticky footer using CSS Grid Layout. The .wrapper has a minimum height of 100% which means it is as tall as the container it is in. We then create a single column grid layout with three rows, one row for each part of our layout. Grid auto-placement will place our items in source order and so the header...
CSS Tutorials - CSS: Cascading Style Sheets
ir best quality. Understanding z-index Controlling superposition of boxes is a basic feature that is very quickly needed by Web developers. Though not that difficult, it requires a basic knowledge of CSS. Intermediate-level CSS tutorials After the release of CSS 2 (Level 1), new features have been added to CSS. Some of them are fancy and are pretty self contained. They are easy to use for any
body with a fair knowledge of basic concepts. CSS Counters Counting items and pages is an easy task in CSS. Learn to use counter-reset, counter-increment, counters(), and counter(). CSS Animations CSS3 Animations allow you to define configurations of style, as keyframes, and to transition between them defining an animation. CSS Transitions CSS3 Transitions allow you to define an animation betw...
Viewport concepts - CSS: Cascading Style Sheets
rome */ document.documentElement.clientHeight /* 533 */ window.innerHeight /* 533 */ window.outerHeight /* 596 in Firefox, 900 in chrome */ The viewport was originally 1200 x 800 pixels. Upon zooming in, the viewport became 800 x 533 pixels. This is the layout viewport. Sticky headers or footers, with the following styles, will stick to the top and bottom of the layout viewport respectively.
body > header { position: fixed; top: 0; }
body > footer { position: fixed; bottom: 0; } We got the 800 x 533 measurement when we zoomed in using the keyboard. The header and footer stayed flush against the top and bottom of the window. But what if we had pinched-zoomed on a tablet? What if a dynamic keyboard pops open on a phone? The web contains two viewports, the layout viewport and the ...
animation - CSS: Cascading Style Sheets
verlay">animation: 3s linear 1s slidein;</div> <div class="animation a2"></div> </div> </div> <div class="row"> <div class="cell"> <button class="pause" title="PAUSE"></button> </div> <div class="cell flx"> <div class="overlay">animation: 3s slidein;</div> <div class="animation a3"></div> </div> </div> </div> </div> html,
body { height: 100%; box-sizing: border-box; } pre { margin-bottom: 0; } svg { width: 1.5em; height: 1.5em; } button { width: 27px; height: 27px; background-size: 16px; background-position: center; background-repeat: no-repeat; border-radius: 3px; cursor: pointer; } button.play { background-image: url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%...
background-clip - CSS: Cascading Style Sheets
a, the background-clip property has no effect when specified on it. See "The backgrounds of special elements." Note: For documents whose root element is an HTML element: if the computed value of background-image on the root element is none and its background-color is transparent, user agents must instead propagate the computed values of the background properties from that element's first HTML <
body> child element. The used values of that <
body> element's background properties are their initial values, and the propagated values are treated as if they were specified on the root element. It is recommended that authors of HTML documents specify the canvas background for the <
body> element rather than the HTML element. Syntax /* Keyword values */ background-clip: border-box; background-clip: ...
break-inside - CSS: Cascading Style Sheets
olestie nec nisi.</p> <p>In finibus viverra enim vel suscipit. Quisque consequat velit eu orci malesuada, ut interdum tortor molestie. Proin sed pellentesque augue. Nam risus justo, faucibus non porta a, congue vel massa. Cras luctus lacus nisl, sed tincidunt velit pharetra ac. ...
clip-path - CSS: Cascading Style Sheets
cell"> <span>SVG</span> <div class="container viewbox"> <svg viewBox="0 0 192 192"> <g class="shape9"> <rect x="24" y="24" width="144" height="144" /> <text x="96" y="91">I LOVE</text> <text x="96" y="109" class="em">clipping</text> </g> </svg> </div> </div> </div> </div> </div> html,
body { height: 100%; box-sizing: border-box; background: #EEE; } .grid { width: 100%; height: 100%; display: flex; font: 1em monospace; } .row { display: flex; flex: 1 auto; flex-direction: row; flex-wrap: wrap; } .col { flex: 1 auto; } .cell { margin: .5em; padding: .5em; background-color: #FFF; overflow: hidden; text-align: center; flex: 1; } .note { backgr...
display - CSS: Cascading Style Sheets
type of block. Internal <display-internal> Some layout models such as table and ruby have a complex internal structure, with several different roles that their children and descendants can fill. This section defines those "internal" display values, which only have meaning within that particular layout mode. Valid <display-internal> values: table-row-group These elements behave like <t
body> HTML elements. table-header-group These elements behave like <thead> HTML elements. table-footer-group These elements behave like <tfoot> HTML elements. table-row These elements behave like <tr> HTML elements. table-cell These elements behave like <td> HTML elements. table-column-group These elements behave like <colgroup> HTML elements. table-column These elements behave like <col> ...
<easing-function> - CSS: Cascading Style Sheets
selected>linear</option> <option>ease</option> <option>ease-in</option> <option>ease-in-out</option> <option>ease-out</option> <option>cubic-bezier(0.1, -0.6, 0.2, 0)</option> <option>cubic-bezier(0, 1.1, 0.8, 4)</option> <option>steps(5, end)</option> <option>steps(3, start)</option> <option>steps(4)</option> </select> </li> </ul> CSS
body > div { position: relative; height: 100px; } div > div { position: absolute; width: 50px; height: 50px; background-color: blue; background-image: radial-gradient(circle at 10px 10px, rgba(25,255,255,0.8),rgba(25,255,255,0.4)); border-radius: 50%; top: 25px; animation: 1.5s infinite alternate; } @keyframes move-right { from { left: 10%; } to { left: 90%; } } ...
env() - CSS: Cascading Style Sheets
user-agent defined rather than user-defined, environment variables are globally scoped to a document, whereas custom properties are scoped to the element(s) on which they are declared. To tell the browser to use the whole available space on the screen, and so enabling us to use the env() variables, we need to add a new viewport meta value: <meta name="viewport" content="viewport-fit=cover" />
body { padding: env(safe-area-inset-top, 20px) env(safe-area-inset-right, 20px) env(safe-area-inset-bottom, 20px) env(safe-area-inset-left, 20px); } In addition, unlike custom properties, which cannot be used outside of declarations, the env() function can be used in place of any part of a property value, or any part of a descriptor (e.g. in Media query rules). As the spec evolves, ...
font-style - CSS: Cascading Style Sheets
der the terms of its license: https://github.com/TypeNetwork/Amstelvar/blob/master/OFL.txt */ @font-face { src: url('https://mdn.mozillademos.org/files/16044/AmstelvarAlpha-VF.ttf'); font-family:'AmstelvarAlpha'; font-style: normal; } label { font: 1rem monospace; } .container { max-height: 150px; overflow: scroll; } .sample { font: 2rem 'AmstelvarAlpha', sans-serif; } html,
body { max-height: 100vh; max-width: 100vw; overflow: hidden; }
body { display: flex; flex-direction: column; } header { margin-bottom: 1.5rem; } .container { flex-grow: 1; } .container > p { margin-top: 0; margin-bottom: 0; } JavaScript let slantLabel = document.querySelector('label[for="slant"]'); let slantInput = document.querySelector('#slant'); let sampleText = document.
font-weight - CSS: Cascading Style Sheets
hub.com/LettError/mutatorSans/blob/master/LICENSE */ @font-face { src: url('https://mdn.mozillademos.org/files/16011/MutatorSans.ttf'); font-family:'MutatorSans'; font-style: normal; } label { font: 1rem monospace; white-space: nowrap; } .container { max-height: 150px; overflow-y: auto; } .sample { text-transform: uppercase; font: 1.5rem 'MutatorSans', sans-serif; } html,
body { max-height: 100vh; max-width: 100vw; overflow: hidden; }
body { display: flex; flex-direction: column; } header { margin-bottom: 1.5rem; } .container { flex-grow: 1; } .container > p { margin-top: 0; margin-bottom: 0; } JavaScript let weightLabel = document.querySelector('label[for="weight"]'); let weightInput = document.querySelector('#weight'); let sampleText = docum...
mix-blend-mode - CSS: Cascading Style Sheets
tem firefox"></div> <svg viewBox="0 0 150 150"> <ellipse class="item R" cx="75" cy="75" rx="25" ry="70"></ellipse> <ellipse class="item G" cx="75" cy="75" rx="25" ry="70"></ellipse> <ellipse class="item B" cx="75" cy="75" rx="25" ry="70"></ellipse> </svg> </div> </div> </div> </div> </div> </div> html,
body { height: 100%; box-sizing: border-box; background: #EEE; } .grid { width: 100%; display: flex; font: 1em monospace; } .row { display: flex; flex: 1 auto; flex-direction: row; flex-wrap: wrap; height: auto; } .col { display: flex; flex: 1 auto; flex-direction: column; height: auto; } .cell { margin: .5em; padding: .5em; background-color: #FFF; overflow: h...
Guide to scroll anchoring - CSS: Cascading Style Sheets
y to opt out of the new behavior. The only possible values are auto or none: auto is the initial value; as long as the user has a supported browser the scroll anchoring behavior will happen, and they should see fewer content jumps. none means that you have explicitly opted the document, or part of the document, out of scroll anchoring. To opt out the entire document, you can set it on the <
body> element:
body { overflow-anchor: none; } To opt out a certain part of the document use overflow-anchor: none on its container element: .container { overflow-anchor: none; } Note: The specification details that once scroll anchoring has been opted out of, you cannot opt back into it from a child element. For example, if you opt out for the entire document, you will not be able to set ove...
overflow-anchor - CSS: Cascading Style Sheets
auto The element becomes a potential anchor when adjusting scroll position. none The element won't be selected as a potential anchor. 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.
body { overflow-anchor: none; } Specifications Specification Status Comment CSS Scroll Anchoring Module Level 1The definition of 'overflow-anchor' in that specification. Editor's Draft Initial definition. ...
overflow - CSS: Cascading Style Sheets
[1] Use overflow: hidden instead. -moz-scrollbars-horizontal [1] Use overflow-x: scroll and overflow-y: hidden, or overflow: hidden scroll instead. -moz-scrollbars-vertical [1] Use overflow-x: hidden and overflow-y: scroll, or overflow: scroll hidden instead. -moz-hidden-unscrollable Intended mainly for internal use and by themes. Disables scrolling of XML root elements, <html>, and <
body> with the keyboard's arrow keys and the mouse wheel. [1] As of Firefox 63, this feature is behind a feature preference setting. In about:config, set layout.css.overflow.moz-scrollbars.enabled to true Description Overflow options include clipping, showing scrollbars, or displaying the content flowing out of its container into the surrounding area. Specifying a value other than visible (the de...
overscroll-behavior - CSS: Cascading Style Sheets
or would also work) on the chat window, like this: .messages { height: 220px; overflow: auto; overscroll-behavior-y: contain; } We also wanted to get rid of the standard overscroll effects when the contacts are scrolled to the top or bottom (e.g. Chrome on Android refreshes the page when you scroll past the top boundary). This can be prevented by setting overscroll-behavior: none on the <
body> element:
body { margin: 0; overscroll-behavior: none; } Specifications Specification Status Comment CSS Overscroll Behavior Module Level 1The definition of 'overscroll-behavior' in that specification. Working Draft ...
position - CSS: Cascading Style Sheets
an>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. ...
scroll-behavior - CSS: Cascading Style Sheets
red in a GitHub repository. If 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 any other scrolls, such as those performed by the user, are not affected by this property. When this property is specified on the root element, it applies to the viewport instead. This property specified on the
body element will not propagate to the viewport. User agents are allowed to ignore this property. Syntax /* Keyword values */ scroll-behavior: auto; scroll-behavior: smooth; /* Global values */ scroll-behavior: inherit; scroll-behavior: initial; scroll-behavior: unset; The scroll-behavior property is specified as one of the keyword values listed below. Values auto The scrolling box scrolls ...
scroll-snap-stop - CSS: Cascading Style Sheets
er must not "pass over" a possible snap position; and must snap to the first of this elements' snap positions. 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. ...
scroll-snap-type - CSS: Cascading Style Sheets
/div> <div>3</div> <div>4</div> <div>5</div> </div> <div class="container y mandatory-scroll-snapping" dir="rtl"> <div>Y Mand. RTL</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </div> <div class="container y proximity-scroll-snapping" dir="rtl"> <div>Y Prox. ...
text-transform - CSS: Cascading Style Sheets
?</strong> </p> <p>text-transform: full-width <strong><span>?????????????????</span></strong> </p> span { text-transform: full-width; } strong { width: 100%; float: right; } The Japanese half-width katakana was used to represent katakana in 8-bit character codes. Unlike regular (full-width) katakana characters, a letter with dakuten (voiced sound mark) is represented as two code points, the
body of letter and dakuten. The full-width combines these into a single code point when converting these characters into full-width. full-size-kana <p>???? ???? ???? ???? ???? ???? ????</p> <p>???? ???? ???? ???? ???? ???? ????</p> </p> p:nth-of-type(2) { text-transform: full-size-kana; } Specifications Specification Status Comment CSS Text Module Level 3The defi...
top - CSS: Cascading Style Sheets
, or the auto keyword. 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 specification. ...
matrix3d() - CSS: Cascading Style Sheets
anslation and scale example Another transform3d() example, which implements an animated combined translate and scale. HTML <div class="foo"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. ...
rotate3d() - CSS: Cascading Style Sheets
rdinates on RP2 Cartesian coordinates on R3 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 RP3 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: 800px; } div { width: 80px; height: 80px; background-color: skyblue; } .rotated { transfo...
var() - CSS: Cascading Style Sheets
g beyond what is presented here. <declaration-value> The custom property's fallback value, which is used in case the custom property is invalid in the used context. This value may contain any character except some characters with special meaning like newlines, unmatched closing brackets, i.e. ), ], or }, top-level semicolons, or exclamation marks. ...
Ajax - Developer guides
his article provides a working (minimalist) example of a pure-Ajax website composed only of three pages. Sending and Receiving Binary Data The responseType property of the XMLHttpRequest object can be set to change the expected response type from the server. Possible values are the empty string (default), arraybuffer, blob, document, json, and text. The response property will contain the entity
body according to responseType, as an ArrayBuffer, Blob, Document, JSON, or string. This article will show some Ajax I/O techniques. XML The Extensible Markup Language (XML) is a W3C-recommended general-purpose markup language for creating special-purpose markup languages. It is a simplified subset of SGML, capable of describing many different kinds of data. Its primary purpose is to facilitate the ...
Parsing and serializing XML - Developer guides
erialize using serializeToString(), but there is a simpler option: just use the Element.innerHTML property (if you want just the descendants of the specified node) or the Element.outerHTML property if you want the node and all its descendants. var docHTML = document.documentElement.innerHTML; As a result, docHTML is a DOMString containing the HTML of the contents of the document; that is, the <
body> element's contents. You can get HTML corresponding to the <
body> and its descendants with this code: var docHTML = document.documentElement.outerHTML; ...
Writing forward-compatible websites - Developer guides
es that they follow these guidelines too. If they don't, you can't rely on that library not breaking in the future. Unfortunately, libraries are common transgressors of these guidelines. Sniffing Sniff for specific features If you plan to use some feature, use object-detection to sniff for that exact feature, if possible. 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. will have a window.event object available in event handlers. Don't assume that browsers with support for a given DOM feature must also have some other, especially nonstandard, DOM feature. Or, conversely, that they don't have support for some other feature (e.g., don't assume that a browser that supports onload on script elem...
HTML attribute: rel - HTML: Hypertext Markup Language
ents, the bookmark provides a permalink for ancestor section, which is the nearest ancestor <article> or <section>, if there is at least one, otherwise, the nearest heading sibling or ancestor descendant, to the next.. canonical Valid for <link>, it defines the preferred URL for the current document, which is useful for search engines. dns-prefetch Relevant for the <link> element both in the <
body> and <head>, it tells the browser to preemptively perform DNS resolution for the target resource's origin. Useful for resources the user will likely need, it helps reduce latency and thereby improves performance when the user does access the resources as the browser preemptively performed DNS resolution for the origin of the specified resource. See dns-prefetch described in resource hints. exter...
Block-level elements - HTML: Hypertext Markup Language
ll width available (stretches out to the left and right as far as it can). 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. Block-level vs. inline There are a couple of key differences between block-level elements and inline elements: Content model Generally, block-level elements may contain inline elements and (sometimes) other block-level elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements. Default formatting By default,...
<area> - HTML: Hypertext Markup Language
et for the area. Its value is a valid URL. This attribute may be omitted; if so, the <area> element does not represent a hyperlink. hreflang Indicates the language of the linked resource. Allowed values are determined by BCP47. Use this attribute only if the href attribute is present. ping Contains a space-separated list of URLs to which, when the hyperlink is followed, POST requests with the
body PING will be sent by the browser (in the background). Typically used for tracking. referrerpolicy A string indicating which referrer to use when fetching the resource: "no-referrer" meaning that the Referer: header will not be sent. "no-referrer-when-downgrade" meaning that no Referer: header will be sent when navigating to an origin without TLS (HTTPS). This is a user agent's default b...
<blink>: The Blinking Text element (obsolete) - HTML: Hypertext Markup Language
ndard element which causes the enclosed text to flash slowly. Do not use this element as it is obsolete and is bad design practice. Blinking text is frowned upon by several accessibility standards and the CSS specification allows browsers to ignore the <blink> element. DOM interface This element is unsupported and thus implements the HTMLUnknownElement interface. Example <blink>Why would some
body use this?</blink> Result (toned down!) Specification This element is non-standard and not part of any specification. If you don't believe us, see for yourself in the HTML spec. CSS polyfill If you really do need a polyfill, then you can use the following CSS polyfill. Works in IE10+. blink { -webkit-animation: 2s linear infinite condemned_blink_effect; /* for Safari 4.0 - 8.0 */ anim...
<button>: The Button element - HTML: Hypertext Markup Language
ldn't be used for real form submission. If this attribute is specified, it overrides the enctype attribute of the button's form owner. formmethod HTML5 If the button is a submit button (it's inside/associated with a <form> and doesn't have type="button"), this attribute specifies the HTTP method used to submit the form. Possible values: post: The data from the form are included in the
body of the HTTP request when sent to the server. Use when the form contains information that shouldn't be public, like login credentials. get: The form data are appended to the form's action URL, with a ? as a separator, and the resulting URL is sent to the server. Use this method when the form has no side effects, like search forms. If specified, this attribute overrides the method attribute o...
<colgroup> - HTML: Hypertext Markup Language
t Tag omission The start tag may be omitted, if it has a <col> element as its first child and if it is not preceded by a <colgroup> whose end tag has been omitted. The end tag may be omitted, if it is not followed by a space or a comment. Permitted parents A <table> element. The <colgroup> must appear after any optional <caption> element but before any <thead>, <th>, <t
body>, <tfoot> and <tr> element. Implicit ARIA role No corresponding role Permitted ARIA roles No role permitted DOM interface HTMLTableColElement Attributes This element's attributes include the global attributes. span This attribute contains a positive integer indicating the number of consecutive columns the <colgroup> element spans. If not present, ...
<form> - HTML: Hypertext Markup Language
ata: Use this if the form contains <input> elements with type=file. text/plain: Introduced by HTML5 for debugging purposes. This value can be overridden by formenctype attributes on <button>, <input type="submit">, or <input type="image"> elements. method The HTTP method to submit the form with. Possible (case insensitive) values: post: The POST method; form data sent as the request
body. get: The GET method; form data appended to the action URL with a ? separator. Use this method when the form has no side-effects. dialog: When the form is inside a <dialog>, closes the dialog on submission. This value is overridden by formmethod attributes on <button>, <input type="submit">, or <input type="image"> elements. novalidate This Boolean attribute indicates that the form sh...
<hgroup> - HTML: Hypertext Markup Language
ce (": ") 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(s) Consider the following HTML document: <!DOCTYPE html> <title>HTML Standard</title> <
body> <hgroup id="document-title"> <h1>HTML</h1> <h2>Living Standard -- Last Updated 12 August 2016</h2> </hgroup> <p>Some intro to the document.</p> <h2>Table of contents</h2> <ol id=toc>...</ol> <h2>First section</h2> <p>Some intro to the first section.</p> </
body> A rendered outline for that document might look like the following: That is, the rendered outline might show t...
<image>: The obsolete Image element - HTML: Hypertext Markup Language
this! In order to display images, use the standard <img> element. While some browsers will attempt to automatically convert this into an <img> element, they won't always do so, and won't always succeed when they try, due to various ways in which the options can be interpreted. So just don't use it if you like your users. Specifications This might have once been part of a specification, but no
body seems to remember. It certainly isn't anymore. Just avoid it like the plague. ...
<input type="email"> - HTML: Hypertext Markup Language
ess and a message describing the problem they need help with. We want to ensure that not only does the user provide a valid e-mail address, but for security purposes, we require that the address be an internal corporate e-mail address. Since inputs of type email validate against both the standard e-mail address validation and the specified pattern, you can implement this easily. ...
<input type="submit"> - HTML: Hypertext Markup Language
n or action attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by formenctype or the form's enctype attribute. This URL is then sent to the server using an HTTP get request. This method works well for simple forms that contain only ASCII characters and have no side effects. This is the default value. post The form's data is included in the
body of the request that is sent to the URL given by the formaction or action attribute using an HTTP post method. This method supports complex data and file attachments. dialog This method is used to indicate that the button simply closes the dialog with which the input is associated, and does not transmit the form data at all. This attribute is also available on <input type="image"> and <button>...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
nymous"> A rel value of preload indicates that the browser should preload this resource (see Preloading content with rel="preload" for more details), with the as attribute indicating the specific class of content being fetched. The crossorigin attribute indicates whether the resource should be fetched with a CORS request. Other usage notes: A <link> element can occur either in the <head> or <
body> element, depending on whether it has a link type that is
body-ok. For example, the stylesheet link type is
body-ok, and therefore <link rel="stylesheet"> is permitted in the
body. However, this isn't a good practice to follow; it makes more sense to separate your <link> elements from your
body content, putting them in the <head>. When using <link> to establish a favicon for a site, and your sit...
<noframes>: The Frame Fallback element - HTML: Hypertext Markup Language
lback element, <noframes>, provides content to be presented in browsers that don't support (or have disabled support for) the <frame> element. Although most commonly-used browsers support frames, there are exceptions, including certain special-use browsers including some mobile browsers, as well as text-mode browsers. A <noframes> element can contain any HTML elements that are allowed within the
body of an HTML document, with the exception of the <frameset> and <frame> elements, since using frames when they aren't supported doesn't make sense. <noframes> can be used to present a message explaining that the user's browser doesn't support frames, but ideally should be used to present an alternate form of the site that doesn't use frames but still offers the same or similar functionality. In ...
<pre>: The Preformatted Text element - HTML: Hypertext Markup Language
Though technically still implemented, this attribute has no visual effect; to achieve such an effect, use CSS width instead. wrap Is a hint indicating how the overflow must happen. In modern browser this hint is ignored and no visual effect results in its present; to achieve such an effect, use CSS white-space instead. 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. The alternate description should clearly and concisely describe the image or diagram's content. People experiencing low vision conditions and browsing with the aid of assistive technology such as a screen reader may not under...
<rb>: The Ruby Base element - HTML: Hypertext Markup Language
he ruby base text. The annotation on the other hand is delimited by two <rt> elements. Note that we could also write this example with the two base text parts annotated completely separately. In this case we don't need to include <rb> elements: <ruby> ? <rp>(</rp><rt>Kan</rt><rp>)</rp> ? <rp>(</rp><rt>ji</rt><rp>)</rp> </ruby> <ruby> <rb>?<rb>? <rp>(</rp><rt>kan<rt>ji<rp>)</rp> </ruby>
body { font-size: 22px; } The output looks like so: The HTML above might look something like this when rendered by a browser without ruby support: ?? (kan ji)
body { font-size: 22px; } Note: See the article about the <ruby> element for further examples. Specifications Specification Status Comment HTML5The definition of '<rb>' in that specification. ...
<rp>: The Ruby Fallback Parenthesis element - HTML: Hypertext Markup Language
. The <rp> element is used in the case of lack of <ruby> element support; the <rp> content provides what should be displayed in order to indicate the presence of a ruby annotation, usually parentheses. 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. Specifications Specification Status Comment HTML Living StandardThe definition of '<rp>' in that spe...
<rt>: The Ruby Text element - HTML: Hypertext Markup Language
itted parents A <ruby> element. Implicit ARIA role No corresponding role Permitted ARIA roles Any DOM interface HTMLElement Attributes This element only includes the global attributes. 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 Specification Status Comment HTML Living StandardThe definition of '<rt>' in that specification. Living Standard HTML5The definition of '<rt>' in ...
<td>: The Table Data Cell element - HTML: Hypertext Markup Language
e default value (1). headers This attribute contains a list of space-separated strings, each corresponding to the id attribute of the <th> elements that apply to this element. rowspan This attribute contains a non-negative integer value that indicates for how many rows the cell extends. Its default value is 1; if its value is set to 0, it extends until the end of the table section (<thead>, <t
body>, <tfoot>, even if implicitly defined), that the cell belongs to. Values higher than 65534 are clipped down to 65534. Deprecated attributes abbr This attribute contains a short abbreviated description of the cell's content. Some user-agents, such as speech readers, may present this description before the content itself. Note: Do not use this attribute as it is obsolete in the latest stan...
<tfoot>: The Table Foot element - HTML: Hypertext Markup Language
teractive-examples and send us a pull request. Content categories None. Permitted content Zero or more <tr> elements. Tag omission The start tag is mandatory. The end tag may be omitted if there is no more content in the parent <table> element. Permitted parents A <table> element. The <tfoot> must appear after any <caption>, <colgroup>, <thead>, <t
body>, or <tr> element. Note that this is the requirement as of HTML5. HTML 4 The <tfoot> element cannot be placed after any <t
body> and <tr> element. Note that this directly contradicts the above normative requirement from HTML5. Implicit ARIA role rowgroup Permitted ARIA roles Any DOM interface HTMLTableSectionElement Attributes This element includes t...
<th> - HTML: Hypertext Markup Language
e default value (1). headers This attribute contains a list of space-separated strings, each corresponding to the id attribute of the <th> elements that apply to this element. rowspan This attribute contains a non-negative integer value that indicates for how many rows the cell extends. Its default value is 1; if its value is set to 0, it extends until the end of the table section (<thead>, <t
body>, <tfoot>, even if implicitly defined), that the cell belongs to. Values higher than 65534 are clipped down to 65534. scope This enumerated attribute defines the cells that the header (defined in the <th>) element relates to. It may have the following values: row: The header relates to all cells of the row it belongs to. col: The header relates to all cells of the column it belongs to. ...
<thead>: The Table Head element - HTML: Hypertext Markup Language
GitHub repository. If 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 categories None. Permitted content Zero or more <tr> elements. Tag omission The start tag is mandatory. The end tag may be omitted if the <thead> element is immediately followed by a <t
body> or <tfoot> element. Permitted parents A <table> element. The <thead> must appear after any <caption> or <colgroup> element, even implicitly defined, but before any <t
body>, <tfoot> and <tr> element. Implicit ARIA role rowgroup Permitted ARIA roles Any DOM interface HTMLTableSectionElement Attributes This element includes the global attribut...
Quirks Mode and Standards Mode - HTML: Hypertext Markup Language
ers determine which mode to use? For HTML documents, browsers use a DOCTYPE in the beginning of the document to decide whether to handle it in quirks mode or standards mode. 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. Earlier versions of the HTML standard recommended other variants, but all existing browsers today will use full standards mode for this DOCTYPE, even the dated Internet Explorer 6. There are no valid reasons to use a more complicated DOCTYPE. If you do use another DOC...
HTML: Hypertext Markup Language
r, either within a single website or between websites. Links are a fundamental aspect of the Web. By uploading content to the Internet and linking it to pages created by other people, you become an active participant in the World Wide Web. HTML uses "markup" to annotate text, images, and other content for display in a Web browser. HTML markup includes special "elements" such as <head>, <title>, <
body>, <header>, <footer>, <article>, <section>, <p>, <div>, <span>, <img>, <aside>, <audio>, <canvas>, <datalist>, <details>, <embed>, <nav>, <output>, <progress>, <video>, <ul>, <ol>, <li> and many others. An HTML element is set off from other text in a document by "tags", which consist of the element name surrounded by "<" and ">". The name of an element inside a tag is case insensitive. That is,...
Cross-Origin Resource Sharing (CORS) - HTTP
to user data. The following is an example of a request that will be preflighted: const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://bar.other/resources/post-here/'); xhr.setRequestHeader('X-PINGOTHER', 'pingpong'); xhr.setRequestHeader('Content-Type', 'application/xml'); xhr.onreadystatechange = handler; xhr.send('<person><name>Arun</name></person>'); The example above creates an XML
body to send with the POST request. Also, a non-standard HTTP X-PINGOTHER request header is set. Such headers are not part of HTTP/1.1, but are generally useful to web applications. Since the request uses a Content-Type of application/xml, and since a custom header is set, this request is preflighted. Note: As described below, the actual POST request does not include the Access-Control-Request-* h...
Content Security Policy (CSP) - HTTP
located at http://example.com/signup.html. It uses the following policy, disallowing everything but stylesheets from cdn.example.com. Content-Security-Policy: default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports The HTML of signup.html looks like this: <!DOCTYPE html> <html> <head> <title>Sign Up</title> <link rel="stylesheet" href="css/style.css"> </head> <
body> ... Content ... </
body> </html> Can you spot the mistake? Stylesheets are allowed to be loaded only from cdn.example.com, yet the website tries to load one from its own origin (http://example.com). A browser capable of enforcing CSP would send the following violation report as a POST request to http://example.com/_/csp-reports, when the document is visited: { "csp-report": { "docum...
Cross-Origin Resource Policy (CORP) - HTTP
ents Cross-Origin Read Blocking (CORB), which is a mechanism to prevent some cross-origin reads by default. The policy is only effective for no-cors requests, which are issued by default for CORS-safelisted methods/headers. As this policy is expressed via a response header, the actual request is not prevented--rather, the browser prevents the result from being leaked by stripping the response
body. History The concept was originally proposed in 2012 (as From-Origin), but resurrected in Q2 of 2018 and implemented in Safari and Chromium. In early 2018, two side-channel hardware vulnerabilities known as Meltdown and Spectre were disclosed. These vulnerabilities allowed sensitive data disclosure due to a race condition which arose as part of speculative execution functionality, designed to ...
Accept-Encoding - HTTP
quest HTTP header advertises which content encoding, usually a compression algorithm, the client is able to understand. Using content negotiation, the server selects one of the proposals, uses it and informs the client of its choice with the Content-Encoding response header. Even if both the client and the server supports the same compression algorithms, the server may choose not to compress the
body of a response, if the identity value is also acceptable. Two common cases lead to this: The data to be sent is already compressed and a second compression won't lead to smaller data to be transmitted. This may be the case with some image formats; The server is overloaded and cannot afford the computational overhead induced by the compression requirement. Typically, Microsoft recommends not to...
Content-Encoding - HTTP
It lets the client know how to decode in order to obtain the media-type referenced by the Content-Type header. The recommendation is to compress data as much as possible and therefore to use this field, but some types of resources, such as jpeg images, are already compressed. Sometimes, using additional compression doesn't reduce payload size and can even make the payload longer. ...
Content-Length - HTTP
Header type Entity header Forbidden header name yes Syntax Content-Length: <length> Directives <length> The length in decimal number of octets. ...
Content-Range - HTTP
Header type Response header Forbidden header name no CORS-safelisted response-header no Syntax Content-Range: <unit> <range-start>-<range-end>/<size> Content-Range: <unit> <range-start>-<range-end>/* Content-Range: <unit> */<size> Directives <unit> The unit in which ranges are specified. This is usually bytes. <range-start> An integer in the given unit indicating the beginning of the request range. <range-end> An integer in the given unit indicating the end of the requested range. <size> The total size of the document (or '*' if unknown). ...
CSP: font-src - HTTP
n example. In CSP 2.0 this applied only to inline scripts. CSP 3.0 allows it in the case of script-src for external scripts. Examples Violation cases Given this CSP header: Content-Security-Policy: font-src https://example.com/ The following font resource loading is blocked and won't load: <style> @font-face { font-family: "MyFont"; src: url("https://not-example.com/font"); }
body { font-family: "MyFont"; } </style> Specifications Specification Status Comment Content Security Policy Level 3The definition of 'font-src' in that specification. Working Draft No changes. Content Security Policy Level 2The definition of 'font-src' in that specification. Recommendation Initial definition. ...
Content-Security-Policy-Report-Only - HTTP
http://example.com/signup.html. It uses the following policy, disallowing everything but stylesheets from cdn.example.com. Content-Security-Policy-Report-Only: default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports The HTML of signup.html looks like this: <!DOCTYPE html> <html> <head> <title>Sign Up</title> <link rel="stylesheet" href="css/style.css"> </head> <
body> ... Content ... </
body> </html> Can you spot the violation? Stylesheets are only allowed to be loaded from cdn.example.com, yet the website tries to load one from its own origin (http://example.com). A browser capable of enforcing CSP will send the following violation report as a POST request to http://example.com/_/csp-reports, when the document is visited: { "csp-report": { "docu...
Digest - HTTP
es a digest of the requested resource. In RFC 7231 terms this is the selected representation of a resource. The selected representation depends on the Content-Type and Content-Encoding header values: so a single resource may have multiple different digest values. The digest is calculated over the entire representation. 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). Header type Response header Forbidden header name no Syntax Digest: <digest-algorithm>=<digest-value> Digest: <digest-algorithm>=<digest-value>,<digest-algorithm>=<digest-value> Direc...
ETag - HTTP
Specifications Specification Title RFC 7232, section 2.3: ETag Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests ...
If-Range - HTTP
If the condition is not fulfilled, the full resource is sent back, with a 200 OK status. This header can be used either with a Last-Modified validator, or with an ETag, but not with both. The most common use case is to resume a download, to guarantee that the stored resource has not been modified since the last fragment has been received. ...
Keep-Alive - HTTP
s as another request will be sent in the next response. An HTTP pipeline can use it to limit the pipelining. ...
Server-Timing - HTTP
tional values where possible) to minimize the HTTP overhead. // Single metric without value Server-Timing: missedCache // Single metric with value Server-Timing: cpu;dur=2.4 // Single metric with description and value Server-Timing: cache;desc="Cache Read";dur=23.2 // Two metrics with value Server-Timing: db;dur=53, app;dur=47.2 // Server-Timing as trailer Trailer: Server-Timing --- response
body --- Server-Timing: total;dur=123.4 Privacy and security The Server-Timing header may expose potentially sensitive application and infrastructure information. Consider to control which metrics are returned when and to whom on the server side. For example, you could only show metrics to authenticated users and nothing to the public. PerformanceServerTiming interface In addition to having Serve...
Trailer - HTTP
The TE request header needs to be set to "trailers" to allow trailer fields. Header type Response header Forbidden header name yes Syntax Trailer: header-names Directives header-names HTTP header fields which will be present in the trailer part of chunked messages. ...
Transfer-Encoding - HTTP
The Transfer-Encoding header specifies the form of encoding used to safely transfer the payload
body to the user. HTTP/2 doesn't support HTTP 1.1's chunked transfer encoding mechanism, as it provides its own, more efficient, mechanisms for data streaming. Transfer-Encoding is a hop-by-hop header, that is applied to a message between two nodes, not to a resource itself. Each segment of a multi-node connection can use different Transfer-Encoding values. If you want to compress data over the whole connection, use the end-to-end Content-Encoding header instead. When present on a response to a HEAD request that has no
body, it indicates the value that would have applied to the corresponding GET message. Header type Response header Forbidden header name yes Syntax...
CONNECT - HTTP
used to access websites that use SSL (HTTPS). The client asks an HTTP Proxy server to tunnel the TCP connection to the desired destination. The server then proceeds to make the connection on behalf of the client. Once the connection has been established by the server, the Proxy server continues to proxy the TCP stream to and from the client. CONNECT is a hop-by-hop method. 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. See also the Proxy-Authorization header. CONNECT server.example.com:80 HTTP/1.1 Host: server.example.com:80 Proxy-Au...
HTTP request methods - HTTP
TTP verbs. Each of them implements a different semantic, but some common features are shared by a group of them: e.g. a request method can be safe, idempotent, or cacheable. GET The GET method requests a representation of the specified resource. Requests using GET should only retrieve data. HEAD The HEAD method asks for a response identical to that of a GET request, but without the response
body. POST The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server. PUT The PUT method replaces all current representations of the target resource with the request payload. DELETE The DELETE method deletes the specified resource. CONNECT The CONNECT method establishes a tunnel to the server identified by the tar...
A typical HTTP session - HTTP
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-Options: DENY X-XSS-Protection: 1; mode=block Vary: Accept-Encoding,Cookie Age: 7 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>A simple webpage</title> </head> <
body> <h1>Simple HTML5 webpage</h1> <p>Hello, world!</p> </
body> </html> Notification that the requested resource has permanently moved: HTTP/1.1 301 Moved Permanently Server: Apache/2.4.37 (Red Hat) Content-Type: text/html; charset=utf-8 Date: Thu, 06 Dec 2018 17:33:08 GMT Location: https://developer.mozilla.org/ (this is the new link to the resource; it is expected that the user-agent will fe...
100 Continue - HTTP
The HTTP 100 Continue informational status response code indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished. To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request and receive a 100 Continue status code in response before sending the
body. Status 100 Continue Specifications Specification Title RFC 7231, section 6.2.1: 100 Continue Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
200 OK - HTTP
The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET: The resource has been fetched and is transmitted in the message
body. HEAD: The entity headers are in the message
body. POST: The resource describing the result of the action is transmitted in the message
body. TRACE: The message
body contains the request message as received by the server. The successful result of a PUT or a DELETE is often not a 200 OK but a 204 No Content (or a 201 Created when the resource is uploaded for the first time). Status 200 OK Specifications Specification Title RFC 7231, section 6.3.1: 200 OK Hypertext Transfer Protocol (HTTP/1.1): Semant...
201 Created - HTTP
The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource. The new resource is effectively created before this response is sent back and the new resource is returned in the
body of the message, its location being either the URL of the request, or the content of the Location header. The common use case of this status code is as the result of a POST request. Status 201 Created Specifications Specification Title RFC 7231, section 6.3.2: 201 Created Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
206 Partial Content - HTTP
If there is only one range, the Content-Type of the whole response is set to the type of the document, and a Content-Range is provided. If several ranges are sent back, the Content-Type is set to multipart/byteranges and each fragment covers one range, with Content-Range and Content-Type describing it. ...
301 Moved Permanently - HTTP
nsfer Protocol (HTTP) 301 Moved Permanently redirect status response code indicates that the resource requested has been definitively moved to the URL given by the Location headers. A browser redirects to this page and search engines update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is sent to the new URL). Even if the specification requires the method (and the
body) not to be altered when the redirection is performed, not all user-agents align with it - you can still find this type of bugged software out there. It is therefore recommended to use the 301 code only as a response for GET or HEAD methods and to use the 308 Permanent Redirect for POST methods instead, as the method change is explicitly prohibited with this status. Status 301 Moved Permanently ...
302 Found - HTTP
Transfer Protocol (HTTP) 302 Found redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Location header. A browser redirects to this page but search engines don't update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is not sent to the new URL). Even if the specification requires the method (and the
body) not to be altered when the redirection is performed, not all user-agents conform here - you can still find this type of bugged software out there. It is therefore recommended to set the 302 code only as a response for GET or HEAD methods and to use 307 Temporary Redirect instead, as the method change is explicitly prohibited in that case. In the cases where you want the method used to be change...
307 Temporary Redirect - HTTP
HTTP 307 Temporary Redirect redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Location headers. The method and the
body of the original request are reused to perform the redirected request. In the cases where you want the method used to be changed to GET, use 303 See Other instead. This is useful when you want to give an answer to a PUT method that is not the uploaded resources, but a confirmation message (like "You successfully uploaded XYZ"). The only difference between 307 and 302 is that 307 guarantees that the method and the
body will not be changed when the redirected request is made. With 302, some old clients were incorrectly changing the method to GET: the behavior with non-GET methods and 302 is then unpredictabl...
308 Permanent Redirect - HTTP
The HyperText Transfer Protocol (HTTP) 308 Permanent Redirect redirect status response code indicates that the resource requested has been definitively moved to the URL given by the Location headers. A browser redirects to this page and search engines update their links to the resource (in 'SEO-speak', it is said that the 'link-juice' is sent to the new URL). The request method and the
body will not be altered, whereas 301 may incorrectly sometimes be changed to a GET method. Note: Some Web applications may use the 308 Permanent Redirect in a non-standard way and for other purposes. 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 ...
406 Not Acceptable - HTTP
oding Accept-Language In practice, this error is very rarely used. Instead of responding using this error code, which would be cryptic for the end user and difficult to fix, servers ignore the relevant header and serve an actual page to the user. It is assumed that even if the user won't be completely happy, they will prefer this to an error code. If a server returns such an error status, the
body of the message should contain the list of the available representations of the resources, allowing the user to choose among them. Status 406 Not Acceptable Specifications Specification Title RFC 7231, section 6.5.6: 406 Not Acceptable Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
431 Request Header Fields Too Large - HTTP
code indicates that the server refuses to process the request because the request's HTTP headers are too long. The request may be resubmitted after reducing the size of the request headers. 431 can be used when the total size of request headers is too large, or when a single header field is too large. To help those running into this error, indicate which of the two is the problem in the response
body -- ideally, also include which headers are too large. This lets users attempt to fix the problem, such as by clearing their cookies. Servers will often produce this status if: The Referer URL is too long There are too many Cookies sent in the request Status 431 Request Header Fields Too Large Specifications Specification Title RFC 6585, section 5: 431 Request He...
HTTP response status codes - HTTP
ut no response is available yet. 103 Early Hints This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response. Successful responses 200 OK The request has succeeded. The meaning of the success depends on the HTTP method: GET: The resource has been fetched and is transmitted in the message
body. HEAD: The entity headers are in the message
body. PUT or POST: The resource describing the result of the action is transmitted in the message
body. TRACE: The message
body contains the request message as received by the server 201 Created The request has succeeded and a new resource has been created as a result. This is typically the response sent after POST requests, or some PUT req...
Unicode property escapes - JavaScript
are available to define a more precise categorization. It is possible to use both short or long forms in Unicode property escapes. They can be used to match letters, numbers, symbols, punctuations, spaces, etc. For a more exhaustive list of general categories, please refer to the Unicode specification. ...
JavaScript technologies overview - JavaScript
nd DOM Range. From the ECMAScript point of view, objects defined in the DOM specification are called "host objects". HTML DOM HTML, the Web's markup language, is specified in terms of the DOM. Layered above the abstract concepts defined in DOM Core, HTML also defines the meaning of elements. The HTML DOM includes such things as the className property on HTML elements, or APIs such as document.
body. 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. In general, it also forbids using elements and attributes that aren't defined in a standard. Looking for the Document object, Window object, and the other DOM elements? Read the DOM docume...
Public class fields - JavaScript
) // expected output: "base static method output" Public instance fields Public instance fields exist on every created instance of a class. By declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting. Public instance fields are added with Object.defineProperty() either at construction time in the base class (before the constructor
body runs), or just after super() returns in a subclass. class ClassWithInstanceField { instanceField = 'instance field' } const instance = new ClassWithInstanceField() console.log(instance.instanceField) // expected output: "instance field" Fields without initializers are initialized to undefined. class ClassWithInstanceField { instanceField } const instance = new ClassWithInstanceField() co...
Error: Permission denied to access property "x" - JavaScript
t domain for which you violated the same-origin policy. 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> ...
JavaScript error reference - JavaScript
ag "x"SyntaxError: missing ) after argument listSyntaxError: missing ) after conditionSyntaxError: missing : after property idSyntaxError: missing ; before statementSyntaxError: missing = in const declarationSyntaxError: missing ] after element listSyntaxError: missing formal parameterSyntaxError: missing name after . ...
arguments.callee - JavaScript
This is useful when the name of the function is unknown, such as within a function expression with no name (also called "anonymous functions"). Warning: The 5th edition of ECMAScript (ES5) forbids use of arguments.callee() in strict mode. ...
Array.isArray() - JavaScript
Array(null); Array.isArray(undefined); Array.isArray(17); Array.isArray('Array'); Array.isArray(true); Array.isArray(false); Array.isArray(new Uint8Array(32)); Array.isArray({ __proto__: Array.prototype }); instanceof vs isArray When checking for Array instance, Array.isArray is preferred over instanceof because it works through iframes. var iframe = document.createElement('iframe'); document.
body.appendChild(iframe); xArray = window.frames[window.frames.length-1].Array; var arr = new xArray(1,2,3); // [1,2,3] // Correctly checking for Array Array.isArray(arr); // true // Considered harmful, because doesn't work through iframes arr instanceof Array; // false Specifications Specification ECMAScript (ECMA-262)The definition of 'Array.isArray' in that specification. ...
AsyncFunction - JavaScript
The AsyncFunction constructor creates a new async function object. In JavaScript, every asynchronous function is actually an AsyncFunction object. Note that AsyncFunction is not a global object. It can be obtained with the following code: Object.getPrototypeOf(async function(){}).constructor Syntax new AsyncFunction([arg1[, arg2[, ...argN]],] function
Body) Parameters arg1, arg2, ... argN Names to be used by the function as formal argument names. 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". function
Body A string containing the JavaScript statements comprising the function definition. Description async function objects created with the AsyncFunction constructor are ...
Error.prototype.stack - JavaScript
set this value at different times. 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. ...
Function.prototype.toString() - JavaScript
n built-in function objects or a function created by Function.prototype.bind, toString() returns a native function string which looks like "function () {\n [native code]\n}" If the toString() method is called on a function created by the Function constructor, toString() returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function
body. 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)...
GeneratorFunction - JavaScript
The GeneratorFunction constructor creates a new generator function object. In JavaScript, every generator function is actually a GeneratorFunction object. Note that GeneratorFunction is not a global object. It could be obtained by evaluating the following code. Object.getPrototypeOf(function*(){}).constructor Syntax new GeneratorFunction ([arg1[, arg2[, ...argN]],] function
Body) Parameters arg1, arg2, ... argN Names to be used by the function as formal argument names. 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". function
Body A string containing the JavaScript statements comprising the function definition. Description generator function objects created with the Gen...
Object.setPrototypeOf() - JavaScript
ect.prototype.__proto__ permits appending a whole prototype chain to a new prototype object: /** *** Object.appendChain(@object, @prototype) * * Appends the first non-native prototype of a chain to a new prototype. * Returns @object (if it was a primitive value it will transformed into an object). * *** Object.appendChain(@object [, "@arg_name_1", "@arg_name_2", "@arg_name_3", "..."], "@function_
body") *** Object.appendChain(@object [, "@arg_name_1, @arg_name_2, @arg_name_3, ..."], "@function_
body") * * Appends the first non-native prototype of a chain to the native Function.prototype object, then appends a * new Function(["@arg"(s)], "@function_
body") to that chain. * Returns the function. * **/ Object.appendChain = function(oChain, oProto) { if (arguments.length < 2) { throw new Type...
Object - JavaScript
sider injecting code by wrapping your extension before or after the existing logic. For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed. When a function is called, the arguments to the call are held in the array-like "variable" arguments. 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). When modifying prototypes with hooks, pass this and the arguments (the call state) to the current behavior by calling apply() on the function. This pattern can be used for any prototype, such as Node.prototype, Function.prototype, etc. var current = Object.prototype.valueOf; // Since my property "-prop-value" is cross-cutting and i...
Set - JavaScript
logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} // (key and value are the same here) for (let [key, value] of mySet.entries()) console.log(key) // convert Set object to an Array object, with Array.from let myArr = Array.from(mySet) // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}] // the following will also work if run in an HTML document mySet.add(document.
body) mySet.has(document.querySelector('
body')) // true // converting between Set and Array mySet2 = new Set([1, 2, 3, 4]) mySet2.size // 4 [...mySet2] // [1, 2, 3, 4] // intersect can be simulated via let intersection = new Set([...set1].filter(x => set2.has(x))) // difference can be simulated via let difference = new Set([...set1].filter(x => !set2.has(x))) ...
String.prototype.anchor() - JavaScript
..."> start tag. Return value A string beginning with an <a name="name"> start tag, then the text str, and then an </a> end tag Description Don't use this method. Use DOM APIs instead. Also, the HTML specification no longer allows the <a> element to have a name attribute, so this method doesn't even create valid markup. 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. ...
async function expression - JavaScript
can be used to define async functions inside expressions. You can also define async functions using an async function statement. Syntax async function [name]([param1[, param2[, ..., paramN]]]) { statements } As of ES2015, you can also use arrow functions. Parameters name The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function
body. paramN The name of an argument to be passed to the function. statements The statements which comprise the
body of the function. Description An async function expression is very similar to, and has almost the same syntax as, an async function statement. The main difference between an async function expression and an async function statement is the function name, which can be omitted in asy...
function* expression - JavaScript
d in a GitHub repository. If 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 function* [name]([param1[, param2[, ..., paramN]]]) { statements } Parameters name Optional The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function
body. paramN Optional The name of an argument to be passed to the function. A function can have up to 255 arguments. statements The statements which comprise the
body of the function. Description A function* expression is very similar to and has almost the same syntax as a function* statement. The main difference between a function* expression and a function* statement is the function name, wh...
void operator - JavaScript
result in an Uncaught SyntaxError. JavaScript URIs When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is undefined. The void operator can be used to return undefined. For example: <a href="javascript:void(0);"> Click here to do nothing </a> <a href="javascript:void(document.
body.style.backgroundColor='green');"> Click here for green background </a> Note: javascript: pseudo protocol is discouraged over other alternatives, such as unobtrusive event handlers. Non-leaking Arrow Functions Arrow functions introduce a short-hand braceless syntax that returns an expression. This can cause unintended side effects by returning the result of a function call that previously ...
break - JavaScript
witch, this is required. Description The break statement includes an optional label that allows the program to break out of a labeled statement. The break statement needs to be nested within the referenced label. The labeled statement can be any block statement; it does not have to be preceded by a loop statement. A break statement, with or without a following label, cannot be used within the
body of a function that is itself nested within the current loop, switch, or label statement that the break statement is intended to break out of. 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. function testBreak(x) { var i = 0; while (i < 6) { if (i == 3) { break; } i +=...
class - JavaScript
like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. You can also define a class using a class expression. But unlike a class expression, a class declaration doesn't allow an existing class to be declared again and will throw a SyntaxError if attempted. Syntax class name [extends otherName] { // class
body } Description The class
body of a class declaration is executed in strict mode. The constructor method is optional. Class declarations are not hoisted (unlike function declarations). 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. Note that super(), used in the constructor, can only be used ...
for await...of - JavaScript
{ reader.releaseLock(); } } // Fetches data from url and calculates response size using the async generator. async function getResponseSize(url) { const response = await fetch(url); // Will hold the size of the response, in bytes. let responseSize = 0; // The for-await-of loop. Async iterates over each portion of the response. for await (const chunk of streamAsyncIterable(response.
body)) { // Incrementing the total response length. responseSize += chunk.length; } console.log(`Response Size: ${responseSize} bytes`); // expected output: "Response Size: 1071472" return responseSize; } getResponseSize('https://jsonplaceholder.typicode.com/photos'); Iterating over sync iterables and generators for await...of loop also consumes sync iterables and generators. In tha...
for - JavaScript
al for expressions All three expressions in the head of the for loop are optional. For example, in the initialization block it is not required to initialize variables: var i = 0; for (; i < 9; i++) { console.log(i); // more statements } Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the
body in order to not create an infinite loop. for (let i = 0;; i++) { console.log(i); if (i > 3) break; // more statements } You can also omit all three blocks. Again, make sure to use a break statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point. var i = 0; for (;;) { if (i > 3) break; console.log(i); i+...
function declaration - JavaScript
ive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax function name([param[, param,[..., param]]]) { [statements] } name The function name. param Optional The name of an argument to be passed to the function. Maximum number of arguments varies in different engines. statements Optional The statements which comprise the
body of the function. Description A function created with a function declaration is a Function object and has all the properties, methods and behavior of Function objects. See Function for detailed information on functions. A function can also be created using an expression (see function expression). By default, functions return undefined. To return any other value, the function must have a retur...
return - JavaScript
teractive example is stored in a GitHub repository. If 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 return [[expression]]; expression The expression whose value is to be returned. If omitted, undefined is returned instead. Description When a return statement is used in a function
body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x, where x is a number. function square(x) { return x * x; } var demo = square(3); // demo will equal 9 If the value is omitted, undefined is returned instead. The following return statements all break the functio...
with - JavaScript
Any statement. To execute multiple statements, use a block statement ({ ... }) to group those statements. Description JavaScript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement
body. If an unqualified name used in the
body matches a property in the scope chain, then the name is bound to the property and the object containing the property. Otherwise a ReferenceError is thrown. Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable. Performanc...
Strict mode - JavaScript
oach of wrapping the entire contents of a script in a function and having that outer function use strict mode. This eliminates the concatenation problem and it means that you have to explicitly export any shared variables out of the function scope. Strict mode for functions Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's
body before any other statements. function strict() { // Function-level strict mode syntax 'use strict'; function nested() { return 'And so am I!'; } return "Hi! I'm a strict mode function! " + nested(); } function notStrict() { return "I'm not strict."; } Strict mode for modules ECMAScript 2015 introduced JavaScript modules and therefore a 3rd way to enter strict mode. The entire conte...
Critical rendering path - Web Performance
step determines where and how the elements are positioned on the page, determining the width and height of each element, and where they are in relation to each other. What is the width of an element? Block level elements, by definition, have a default width of 100% of the width of their parent. An element with a width of 50%, will be half of the width of its parent. Unless otherwise defined, the
body has a width of 100%, meaning it will be 100% of the width of the viewport. This width of the device impacts layout. The viewport meta tag defines the width of the layout viewport, impacting the layout. Without it, the browser uses the default viewport width, which on by-default full screen browsers is generally 960px. On by-default full screen browsers, like your phone's browser, by setting <met...
Using dns-prefetch - Web Performance
resolution latency. The HTML <link> element offers this functionality by way of a rel attribute value of dns-prefetch. 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. Best practices There are 3 main things to keep in mind: For one, dns-prefetch is only effective for DNS lookups on cross-origin domains, so avoid using it to point to your site or...
Introduction to progressive web apps - Progressive web apps (PWAs)
ow the progressive enhancement rule: use technologies that enhance the appearance and utility of your app when they're available, but still offer the basic functionality of your app when those features are unavailable. Presenting a trusted website with a good performance is a consequence of using these enhancements; this in turn means building web apps which follow better practices. This way every
body will be able to use the app, but those with modern browsers will benefit from PWA features even more. An example application In this series of articles we will examine the source code of a super simple website that lists information about games submitted to the A-Frame category in the js13kGames 2017 competition. You don't have to think about what the actual content on the website is; the main ...
attributeName - SVG: Scalable Vector Graphics
The attributeName attribute indicates the name of the CSS property or attribute of the target element that is going to be changed during an animation. Four elements are using this attribute: <animate>, <animateColor>, <animateTransform>, and <set> html,
body, svg { height: 100%; } <svg viewBox="0 0 250 250" xmlns="http://www.w3.org/2000/svg"> <rect x="50" y="50" width="100" height="100"> <animate attributeType="XML" attributeName="y" from="0" to="50" dur="5s" repeatCount="indefinite"/> </rect> </svg> Usage notes Value <name> Default value None Animatable No <name> This value indicates the name of the CSS property or attribute of the target element to be animated. Specifications Specification Status Co...
attributeType - SVG: Scalable Vector Graphics
The attributeType attribute specifies the namespace in which the target attribute and its associated values are defined. Four elements are using this attribute: <animate>, <animateColor>, <animateTransform>, and <set> html,
body, svg { height: 100%; } <svg viewBox="0 0 250 250" xmlns="http://www.w3.org/2000/svg"> <rect x="50" y="50" width="100" height="100"> <animate attributeType="XML" attributeName="y" from="0" to="50" dur="5s" repeatCount="indefinite"/> </rect> </svg> Usage notes Value CSS | XML | auto Default value auto Animatable No CSS This value specifies that the value of attributeName is the name of a CSS property defined as animatable. XML This value specifies that the value of attributeName is the name o...
by - SVG: Scalable Vector Graphics
The by attribute specifies a relative offset value for an attribute that will be modified during an animation. The starting value for the attribute is either indicated by specifying it as value for the attribute given in the attributeName or the from attribute. ...
clip - SVG: Scalable Vector Graphics
ess values, which indicate current user coordinates, are permitted on the coordinate values on the rect(). The value of auto defines a clipping path along the bounds of the viewport created by the given element. ...
color-rendering - SVG: Scalable Vector Graphics
be applied to any element but it only has an effect on the following 29 elements: <a>, <animate>, <animateColor>, <circle>, <clipPath>, <defs>, <ellipse>, <foreignObject>, <g>, <glyph>, <image>, <line>, <linearGradient>, <marker>, <mask>, <missing-glyph>, <path>, <pattern>, <polygon>, <polyline>, <radialGradient>, <rect>, <svg>, <switch>, <symbol>, <text>, <textPath>, <tspan>, and <use> html,
body, svg { height: 100%; } <svg viewBox="0 0 480 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="white"/> <stop offset="100%" stop-color="darkseagreen"/> </radialGradient> </defs> <circle cx="100" cy="100" r="100" fill="url(#gradient)" color-rendering="opti...
color - SVG: Scalable Vector Graphics
or attributes. Note: As a presentation attribute, color can be used as a CSS property. See CSS color for further information. As a presentation attribute, it can be applied to any element, but as noted above, it has no direct effect on SVG elements. ...
diffuseConstant - SVG: Scalable Vector Graphics
The diffuseConstant attribute represents the kd value in the Phong lighting model. In SVG, this can be any non-negative number. It's used to determine the final RGB value of a given pixel. The brighter the lighting-color, the smaller this number should be. ...
media - SVG: Scalable Vector Graphics
The media attribute specifies a media query that must be matched for a style sheet to apply. Only one element is using this attribute: <style> html,
body, svg { height: 100%; } <svg viewBox="0 0 240 220" xmlns="http://www.w3.org/2000/svg"> <style> rect { fill: black; } </style> <style media="all and (min-width: 600px)"> rect { fill: seagreen; } </style> <text y="15">Resize the window to see the effect</text> <rect y="20" width="200" height="200" /> </svg> Usage notes Value <media-query-list> Default value all Animatable Yes <media-query-list> This value holds a media query that needs to match in order for the style sheet to be applied. If not specified, the style sheet is applied unconditionally. Specifica...
numOctaves - SVG: Scalable Vector Graphics
noise function defined by its frequency and amplitude. A turbulence is built by accumulating several octaves with increasing frequencies and decreasing amplitudes. The higher the number of octaves, the more natural the noise looks. Though more octaves also require more calculations, resulting in a negative impact on performance. ...
onclick - SVG: Scalable Vector Graphics
bute: <a>, <altGlyph>, <animate>, <animateMotion>, <animateTransform>, <circle>, <defs>, <desc>, <ellipse>, <foreignObject>, <g>, <image>, <line>, <linearGradient>, <marker>, <metadata>, <mpath>, <path>, <pattern>, <polygon>, <polyline>, <radialGradient>, <rect>, <script>, <set>, <stop>, <style>, <svg>, <switch>, <symbol>, <text>, <textPath>, <title>, <tref>, <tspan>, <use>, <view> html,
body, svg { height: 100%; margin: 0; } <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <circle cx="100" cy="100" r="100" onclick="alert('You have clicked the circle.')" /> </svg> Usage notes Value <anything> Default value None Animatable No Specifications Specification Status Comment Scalable Vector Gra...
overflow - SVG: Scalable Vector Graphics
element, and the <marker> element to be hidden by default. Note: As a presentation attribute, overflow can be used as a CSS property. See the css opacity property for more information. ...
path - SVG: Scalable Vector Graphics
The path attribute has two different meanings, either it defines a text path along which the characters of a text are rendered, or a motion path along which a referenced element is animated. Two elements are using this attribute: <animateMotion> and <textPath> html,
body, svg { height: 100%; } <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path id="MyPath" fill="none" stroke="silver" d="M10,90 Q90,90 90,45 Q90,10 50,10 Q10,10 10,40 Q10,70 45,70 Q70,70 75,50" /> <text> <textPath path="M10,90 Q90,90 90,45 Q90,10 50,10 Q10,10 10,40 Q10,70 45,70 Q70,70 75,50"> Quick brown fox jumps over the lazy dog. </textPath> </text> </svg> animateMotion For <animateMotion>, path defines the motion path, expressed in the same format and interpreted the...
pathLength - SVG: Scalable Vector Graphics
aths; including text paths, animation paths, and various stroke operations. Basically, all computations that require the length of the path. stroke-dasharray, for example, will assume the start of the path being 0 and the end point the value defined in the pathLength attribute. Seven elements are using this attribute: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, and <rect> html,
body,svg { height:100% } <svg viewBox="0 0 100 60" xmlns="http://www.w3.org/2000/svg"> <style> path { fill: none; stroke: black; stroke-width: 2; stroke-dasharray: 10; } </style> <!-- No pathLength, the real length of the path is used. In that case, 100 user units --> <path d="M 0,10 h100"/> <!-- compute everything like if the path length was 90 user units long --> ...
patternContentUnits - SVG: Scalable Vector Graphics
The patternContentUnits attribute indicates which coordinate system to use for the contents of the <pattern> element. Note: That this attribute has no effect if attribute viewBox is specified on the <pattern> element. Only one element is using this attribute: <pattern> html,
body,svg { height:100% } <svg viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <!-- A pattern tile that content coordinates and values are computed against the current coordinate user space. Note that the size of the tile is computed against the bounding box of the target element --> <pattern id="p1" width="20%" height="20%" patternContentUnits="userSpaceOnUse"> <circle cx="10" cy="10" r="10" /> </pattern> <!-- A pattern tile that content coordinates and values are com...
patternTransform - SVG: Scalable Vector Graphics
The patternTransform attribute defines a list of transform definitions that are applied to a pattern tile. Only one element is using this attribute: <pattern> html,
body,svg { height:100% } <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <!-- Apply a transform on the tile --> <pattern id="p1" width=".25" height=".25" patternTransform="rotate(20) skewX(30) scale(1 0.5)"> <circle cx="10" cy="10" r="10" /> </pattern> <!-- Apply the transformed pattern tile --> <rect x="10" y="10" width="80" height="80" fill="url(#p1)" /> </svg> pattern For <pattern>, patternTransform defines a list of transform definitions that are applied to a pattern tile. Note: As of SVG2, it is also allowe...