Search completed in 1.37 seconds.
253 results for "forEach":
Your results are loading. Please wait...
Array.prototype.forEach() - JavaScript
the foreach() method executes a provided function once for each array element.
... syntax arr.foreach(callback(currentvalue [, index [, array]])[, thisarg]) parameters callback function to execute on each element.
... array optional the array foreach() was called upon.
...And 20 more matches
TypedArray.prototype.forEach() - JavaScript
the foreach() method executes a provided function once per array element.
... this method has the same algorithm as array.prototype.foreach().
... syntax typedarray.foreach(callback[, thisarg]) parameters callback function that produces an element of the new typed array, taking three arguments: currentvalue the current element being processed in the typed array.
...And 8 more matches
Set.prototype.forEach() - JavaScript
the foreach() method executes a provided function once for each value in the set object, in insertion order.
... syntax myset.foreach(callback[, thisarg]) parameters callback function to execute for each element, taking three arguments: currentvalue, currentkey the current element being processed in the set.
... set the set object which foreach() was called upon.
...And 7 more matches
NodeList.prototype.forEach() - Web APIs
WebAPINodeListforEach
the foreach() method of the nodelist interface calls the callback given in parameter once for each value pair in the list, in insertion order.
... syntax somenodelist.foreach(callback[, thisarg]); parameters callback a function to execute on each element of somenodelist.
... listobj optional the somenodelist that foreach() is being applied to.
...And 5 more matches
Map.prototype.forEach() - JavaScript
the foreach() method executes a provided function once per each key/value pair in the map object, in insertion order.
... syntax mymap.foreach(callback([value][,key][,map])[, thisarg]) parameters callback function to execute for each entry of mymap.
... description the foreach method executes the provided callback once for each key of the map which actually exist.
...And 5 more matches
forEach - Archive of obsolete content
feel free to alter the text as english is not my mother tongue and i'm more concerned with the code quality that the english grammar ;-s dotnetcarpenter 30 june 2012 <hr> the compatibility section goes to extraordinary lengths in providing a foreach implementation.
...jswisher 01 october 2011 <hr> there is some mistype in array.prototype.foreach: kvalue = o[ pk ]; should be kvalue = o[ k ]; <hr> this page has been the target of a revert war, and so write access to it has been restricted.
...those extra features like foreach are gecko only, and it should be mentioned that they should *_not_* be used on web pages.
...And 3 more matches
DOMTokenList.forEach() - Web APIs
the foreach() method of the domtokenlist interface calls the callback given in parameter once for each value pair in the list, in insertion order.
... syntax tokenlist.foreach(callback [, thisarg]); parameters callback function to execute for each element, eventually taking three arguments: currentvalue the current element being processed in the array.
... listobj the array that foreach() is being applied to.
...And 3 more matches
CSSUnparsedValue.forEach() - Web APIs
the cssunparsedvalue.foreach() method executes a provided function once for each element of the cssunparsedvalue.
... syntax cssunparsedvalue.foreach(function callback(currentvalue[, index[, array]]) { // your iterator }[, thisarg]); parameters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed.
... arrayoptional the cssunparsedvalue that foreach() is being called on.
... specifications specification status comment css typed om level 1the definition of 'foreach()' in that specification.
KeyboardLayoutMap.forEach() - Web APIs
the foreach() method of the keyboardlayoutmap interface executes a provided function once for each element of the map.
... syntax keyboardlayoutmap.foreach(function callback(currentvalue[, index[, array]]) { //your iterator }[, thisarg]); parameters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed.
... array optional the keyboardlayoutmap that foreach() is being called on.
... specifications specification status comment keyboard mapthe definition of 'foreach()' in that specification.
MediaKeyStatusMap.forEach() - Web APIs
the foreach property of the mediakeystatusmap interface calls callback once for each key-value pair in the status map, in insertion order.
... syntax mediakeystatusmap.foreach(callback[, thisarg]) parameters callback function to execute for each element, taking three arguments: currentvalue the current element being processed in the array.
... array which array foreach() is being applied to.
... desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetforeach experimentalchrome full support 42edge full support 13firefox ?
StylePropertyMapReadOnly.forEach() - Web APIs
the stylepropertymapreadonly.foreach() method executes a provided function once for each element of stylepropertymapreadonly.
... syntax stylepropertymapreadonly.foreach(function callback(currentvalue[, index[, array]]) { //your code }[, thisarg]); parameters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed.
... arrayoptional the stylepropertymapreadonly thatforeach() is being called on.
... example // tbd specifications specification status comment css typed om level 1the definition of 'foreach()' in that specification.
XRInputSourceArray.forEach() - Web APIs
the xrinputsourcearray method foreach() executes the specified callback once for each input source in the array, starting at index 0 and progressing until the end of the list.
... syntax xrinputsourcearray.foreach(callback, thisarg); parameters callback a function to execute once for each entry in the array xrinputsourcearray.
... let inputsources = xrsession.inputsources; inputsources.foreach((input) => { if (input.gamepad) { checkgamepad(input.gamepad); } else { if (input.targetraymode === "tracked-pointer" && input.handedness === player.handedness) { /* handle main hand controller */ handlemainhandinput(input); } else { /* handle other inputs */ } } }); for each input in the llist, the callback dispatches gamepad inputs to a checkgam...
... specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like methods in information contained in a webidl file for information on how an iterable declaration in an interface definition causes entries(), foreach(), keys(), and values() methods to be exposed from objects that implement the interface.
URLSearchParams.forEach() - Web APIs
the foreach() method of the urlsearchparams interface allows iteration through all values contained in this object via a callback function.
... syntax searchparams.foreach(callback); parameters callback a callback function that is executed against each parameter, with the param value provided as its parameter.
... examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // log the values searchparams.foreach(function(value, key) { console.log(value, key); }); the result is: value1 key1 value2 key2 specifications specification status comment urlthe definition of 'foreach() (see "iterable")' in that specification.
How to build custom form controls - Learn web development
the features we plan to use are the following: classlist addeventlistener() foreach queryselector() and queryselectorall() beyond the availability of those specific features, there is still one issue remaining before starting.
...this is important because array objects support the foreach function, but nodelist doesn't.
... because nodelist really looks like an array and because foreach is so convenient to use, we can easily add the support of foreach to nodelist in order to make our life easier, like so: nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } if you need to support legacy browsers, ensure the browsers support these features.
...And 7 more matches
Indexed collections - JavaScript
the foreach() method provides another way of iterating over an array: let colors = ['red', 'green', 'blue'] colors.foreach(function(color) { console.log(color) }) // red // green // blue alternatively, you can shorten the code for the foreach parameter with es2015 arrow functions: let colors = ['red', 'green', 'blue'] colors.foreach(color => console.log(color)) // red // green // blue the function pa...
...ssed to foreach is executed once for every item in the array, with the array item passed as the argument to the function.
... unassigned values are not iterated in a foreach loop.
...And 6 more matches
Index - Web APIs
WebAPIIndex
488 cssunparsedvalue.foreach() api, css typed object model api, cssunparsedvalue, constructor, experimental, houdini, method, needsexample, reference, foreach() the cssunparsedvalue.foreach() method executes a provided function once for each element of the cssunparsedvalue.
... 771 domtokenlist.foreach() dom, domtokenlist, iterable, method, reference, web, foreach the foreach() method of the domtokenlist interface calls the callback given in parameter once for each value pair in the list, in insertion order.
... 2225 keyboardlayoutmap.foreach() api, experimental, keyboard api, keyboard map, keyboardlayoutmap, method, reference, foreach(), keyboard the foreach() method of the keyboardlayoutmap interface executes a provided function once for each element of the map.
...And 4 more matches
StringView - Archive of obsolete content
this.makeindex(nsublen, nrawsuboffset) - nrawsuboffset : 0; } else { nrawsuboffset = nsuboffset; nrawsublen = nsublen; } if (this.encoding === "utf-16") { nrawsuboffset <<= 1; } else if (this.encoding === "utf-32") { nrawsuboffset <<= 2; } return new stringview(this.buffer, this.encoding, this.rawdata.byteoffset + nrawsuboffset, nrawsublen); }; stringview.prototype.foreachchar = function (fcallback, othat, nchroffset, nchrlen) { var asource = this.rawdata, nrawend, nrawidx; if (this.encoding === "utf-8" || this.encoding === "utf-16") { var fgetinptchrsize, fgetinptchrcode; if (this.encoding === "utf-8") { fgetinptchrsize = stringview.getutf8charlength; fgetinptchrcode = stringview.loadutf8charcode; } else if (this.encoding === "utf-1...
... stringview.uint6tob64(unsigned char uint6); instances' methods unsigned long stringview.makeindex(optional unsigned long characterslength, optional unsigned long startfrom); domstring stringview.tobase64(optional boolean wholebuffer); stringview stringview.subview(unsigned long characteroffset, optional unsigned long characterslength); void stringview.foreachchar(function callback, optional object thisobject, optional unsigned long characteroffset, optional unsigned long characterslength); domstring stringview.valueof(); domstring stringview.tostring(); properties overview attribute type description encoding read only domstring a string expressing the encoding type.
...*/ var nhindistart = mystringview.makeindex(19); var nhindiend = mystringview.makeindex(6, nhindistart); var mysubview2 = new stringview(mystringview.rawdata.subarray(nhindistart, nhindiend), "utf-8"); alert(mysubview1.rawdata.length); // 18 alert(mysubview2.rawdata.length); // 18 see also: stringview.foreachchar().
...And 3 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
add the following import statement below the existing ones: import moreactions from './moreactions.svelte' then add the described functions at the end of the <script> section: const checkalltodos = (completed) => todos.foreach(t => t.completed = completed) const removecompletedtodos = () => todos = todos.filter(t => !t.completed) now go to the bottom of the todos.svelte markup section and replace the btn-group <div> that we copied into moreactions.svelte with a call to the moreactions component, like so: <!-- moreactions --> <moreactions on:checkall={e => checkalltodos(e.detail)} on:removecompleted={remov...
... update your existing checkalltodos() function to the following: const checkalltodos = (completed) => { todos.foreach(t => t.completed = completed) console.log('todos', todos) } go back to your browser, open your devtools console, and click check all/uncheck all a few times.
... in our checkalltodos() function, when we run: todos.foreach(t => t.completed = completed) svelte will not mark todos as changed because it does not know that when we update our t variable inside the foreach() method, we are also modifying the todos array.
...And 3 more matches
NodeList - Web APIs
WebAPINodeList
although nodelist is not an array, it is possible to iterate over it with foreach().
... however, some older browsers have not implemented nodelist.foreach() nor array.from().
... this can be circumvented by using array.prototype.foreach() — see this document's example.
...And 3 more matches
Signaling and video calling - Web APIs
function handleuserlistmsg(msg) { var i; var listelem = document.queryselector(".userlistbox"); while (listelem.firstchild) { listelem.removechild(listelem.firstchild); } msg.users.foreach(function(username) { var item = document.createelement("li"); item.appendchild(document.createtextnode(username)); item.addeventlistener("click", invite, false); listelem.appendchild(item); }); } after getting a reference to the <ul> which contains the list of user names into the variable listelem, we empty the list by removing each of its child elements.
... then we iterate over the array of user names using foreach().
...that would be weird."); return; } targetusername = clickedusername; createpeerconnection(); navigator.mediadevices.getusermedia(mediaconstraints) .then(function(localstream) { document.getelementbyid("local_video").srcobject = localstream; localstream.gettracks().foreach(track => mypeerconnection.addtrack(track, localstream)); }) .catch(handlegetusermediaerror); } } this begins with a basic sanity check: is the user already connected?
...And 2 more matches
passwords - Archive of obsolete content
so if you pass in an empty set of properties, all stored credentials are returned: function show_all_passwords() { require("sdk/passwords").search({ oncomplete: function oncomplete(credentials) { credentials.foreach(function(credential) { console.log(credential.username); console.log(credential.password); }); } }); } if you pass it a single property, only credentials matching that property are returned: function show_passwords_for_joe() { require("sdk/passwords").search({ username: "joe", oncomplete: function oncomplete(credentials) { credentials.foreach(...
... console.log(credential.username); console.log(credential.password); }); } }); } if you pass more than one property, returned credentials must match all of them: function show_google_password_for_joe() { require("sdk/passwords").search({ username: "joe", url: "https://www.google.com", oncomplete: function oncomplete(credentials) { credentials.foreach(function(credential) { console.log(credential.username); console.log(credential.password); }); } }); } to retrieve only credentials associated with your add-on, use the url property, initialized from self.uri: function show_my_addon_passwords() { require("sdk/passwords").search({ url: require("sdk/self").uri, oncomplete: function oncomplete(credenti...
...als) { credentials.foreach(function(credential) { console.log(credential.username); console.log(credential.password); }); } }); } parameters options : object required options: name type oncomplete function the callback function that is called once the function completes successfully.
...for example, to remove all of joe's stored credentials: require("sdk/passwords").search({ username: "joe", oncomplete: function oncomplete(credentials) { credentials.foreach(require("sdk/passwords").remove); }) }); to change an existing credential just call store after remove succeeds: require("sdk/passwords").remove({ realm: "user registration", username: "joe", password: "secret123" oncomplete: function oncomplete() { require("sdk/passwords").store({ realm: "user registration", username: "joe", password: "{new password}" }) }...
E4X for templating - Archive of obsolete content
file templates (to be eval()d at a later time, taking into account security considerations, such as escaping with the above), e4x content using such functions can also be easily serialized inline (and then perhaps converted to the dom) as needed: var list = <>{_if(elems.length(), function () <> <markup/> <markup/> </>)}</>.toxmlstring(); iterating functions such as the following foreach (which can work with arrays, objects, or e4x objects) are quite convenient in iterating over complex structures such as e4x would not normally allow.
... /* the first two arguments are optional: (h is a handler with an explicit argument v only, or beginning with k, v) lev is optional argument to note recursive depth (if part of recursion) */ function foreach (min, max, arr, h, lev) { var k, ret=<></>, it = 1; lev = lev || 0; if (typeof min === 'number') { if (typeof max !== 'number') { lev = h; h = arr; arr = max; max = min; min = 1; } } else { lev = arr; h = max; arr = min; max = number.positive_infinity; min = 1; } if (h.length === 1) { for (k in arr) { if (it < min) { ++it; continue; } if (it > max) { break; ...
...f (it < min) { ++it; continue; } if (it > max) { break; } ret+=h(k, arr[k], it, lev); ++it; } } return ret; } the following real case example iterates over an array of the lines in an e4x child element to produce an xmllist of multiple vbox's representing each line: <vbox> {foreach(e(someel.somechild[0]).split('\n'), function (line) <description>{line}</description> )} </vbox> the following example shows iteration over an e4x object itself: {foreach(elems, function (k, elem, iter) <> <row>{k}: {elem}</row> <row><image src="chrome://myext/skin/images/fillerrow.jpg" /></row> </>)} or if the e4x child element had its own children and text: {foreach(elems, func...
...()} {elem.somechild}</row> <row><image src="chrome://myext/skin/images/fillerrow.jpg" /></row> </>)} sorting /* @param {xmllist} xmllist the xmllist to sort @param {function} h the sorting handler */ function sort (xmllist, h) { var k, arr=[], ret = <></>; for (k in xmllist) { if (xmllist.hasownproperty(k)) { arr.push(xmllist[k]); } } arr.sort(h).foreach(function (item) { if (typeof item === 'xml') { ret += item; } else if (typeof item === 'string') { ret += new xml(item); } else { var ser = (new xmlserializer()).serializetostring(item); ret += new xml(ser); } }); return ret; } example: var fruits = <fruits> <item>pear</item> <item>ba...
Example 4 - Learn web development
.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('hidden'); select.classlist.remove('active'); } function activeselect(selec...
...t, selectlist) { if (select.classlist.contains('active')) return; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.queryselector('.optlist'); optlist.classlist.toggle('hidden'); } function highlightoption(select, option) { var optionlist = select.queryselectorall('.option'); optionlist.foreach(function (other) { other.classlist.remove('highlight'); }); option.classlist.add('highlight'); }; function updatevalue(select, index) { var nativewidget = select.previouselementsibling; var value = select.queryselector('.value'); var optionlist = select.queryselectorall('.option'); nativewidget.selectedindex = index; value.innerhtml = optionlist[index].innerhtml; highlightoption(sele...
...mentsibling; return nativewidget.selectedindex; }; // ------------- // // event binding // // ------------- // window.addeventlistener("load", function () { var form = document.queryselector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); window.addeventlistener('load', function () { var selectlist = document.queryselectorall('.select'); selectlist.foreach(function (select) { var optionlist = select.queryselectorall('.option'); optionlist.foreach(function (option) { option.addeventlistener('mouseover', function () { highlightoption(select, option); }); }); select.addeventlistener('click', function (event) { toggleoptlist(select); }); select.addeventlistener('focus', function (event) { activ...
...eselect(select, selectlist); }); select.addeventlistener('blur', function (event) { deactivateselect(select); }); }); }); window.addeventlistener('load', function () { var selectlist = document.queryselectorall('.select'); selectlist.foreach(function (select) { var optionlist = select.queryselectorall('.option'), selectedindex = getindex(select); select.tabindex = 0; select.previouselementsibling.tabindex = -1; updatevalue(select, selectedindex); optionlist.foreach(function (option, index) { option.addeventlistener('click', function (event) { updatevalue(select, index); }); }); select.addeventlistener('keyup', function (event) { var length = optionlist.length, index = getindex(select); i...
Parser API
forinstatement(left, right, body, isforeach[, loc]) left: customvariabledeclaration | customexpression right: customexpression body: customstatement isforeach: boolean loc: sourcelocation returns: customstatement callback to produce a custom for-in statement node.
... the isforeach flag indicates whether the node is a for each statement.
... comprehensionblock(left, right, isforeach[, loc]) left: custompattern right: customexpression isforeach: boolean loc: sourcelocation returns: customcomprehensionblock callback to produce a custom comprehension block node.
... the isforeach flag indicates whether the node is a for each block.
Using IndexedDB - Web APIs
var customerobjectstore = db.transaction("customers", "readwrite").objectstore("customers"); customerdata.foreach(function(customer) { customerobjectstore.add(customer); }); }; }; as indicated previously, onupgradeneeded is the only place where you can alter the structure of the database.
... // the added records would be like: // key : 1 => value : "bill" // key : 2 => value : "donna" customerdata.foreach(function(customer) { objstore.add(customer.name); }); }; for more details about the key generator, please see "w3c key generators".
...}; var objectstore = transaction.objectstore("customers"); customerdata.foreach(function(customer) { var request = objectstore.add(customer); request.onsuccess = function(event) { // event.target.result === customer.ssn; }; }); the result of a request generated from a call to add() is the key of the value that was added.
...ctive:hover { background-color: #ff8000; } .destructive:active { background-color: red; } javascript content (function () { var compat_envs = [ ['firefox', ">= 16.0"], ['google chrome', ">= 24.0 (you may need to get google chrome canary), no blob storage support"] ]; var compat = $('#compat'); compat.empty(); compat.append('<ul id="compat-list"></ul>'); compat_envs.foreach(function(val, idx, array) { $('#compat-list').append('<li>' + val[0] + ': ' + val[1] + '</li>'); }); const db_name = 'mdn-demo-indexeddb-epublications'; const db_version = 1; // use a long long for this value (don't use a float) const db_store_name = 'publications'; var db; // used to keep track of which view is displayed to avoid uselessly reloading it var current_view_pub_k...
Intersection Observer API - Web APIs
the callback receives a list of intersectionobserverentry objects and the observer: let callback = (entries, observer) => { entries.foreach(entry => { // each entry describes an intersection change for one observed // target element: // entry.boundingclientrect // entry.intersectionratio // entry.intersectionrect // entry.isintersecting // entry.rootbounds // entry.target // entry.time }); }; the list of entries received by the callback includes one entry for each target which rep...
... observers[i] = new intersectionobserver(intersectioncallback, observeroptions); observers[i].observe(document.queryselector("#" + boxid)); } // scroll to the starting position document.scrollingelement.scrolltop = wrapper.firstelementchild.getboundingclientrect().top + window.scrolly; document.scrollingelement.scrollleft = 750; } intersectioncallback = (entries) => { entries.foreach((entry) => { let box = entry.target; let visiblepct = (math.floor(entry.intersectionratio * 100)) + "%"; box.queryselector(".topleft").innerhtml = visiblepct; box.queryselector(".topright").innerhtml = visiblepct; box.queryselector(".bottomleft").innerhtml = visiblepct; box.queryselector(".bottomright").innerhtml = visiblepct; }); } startup(); clipping and the int...
... intersectioncallback(entries) => { entries.foreach(entry => { if (entry.isintersecting) { let elem = entry.target; if (entry.intersectionratio >= 0.75) { intersectioncounter++; } } }); } interfaces intersectionobserver the primary interface for the intersection observer api.
... handling intersection changes when the browser detects that the target element (in our case, the one with the id "box") has been unveiled or obscured such that its visibility ratio crosses one of the thresholds in our list, it calls our handler function, handleintersect(): function handleintersect(entries, observer) { entries.foreach((entry) => { if (entry.intersectionratio > prevratio) { entry.target.style.backgroundcolor = increasingcolor.replace("ratio", entry.intersectionratio); } else { entry.target.style.backgroundcolor = decreasingcolor.replace("ratio", entry.intersectionratio); } prevratio = entry.intersectionratio; }); } for each intersectionobserverentry in the list entries, we look t...
ARIA: grid role - Accessibility
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.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt...
... && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.queryselector('table').addeventlistener("keydown", function(event) { switch (event.key) { case "arrowright": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) + 1); break; case "arrowleft": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) - 1); break; case "arrowdown": moveto(parseint(event.target.dataset.row, 10) + 1, parseint(event.target.dataset.col, 10)); break; ...
...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.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt...
... && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.queryselector('table').addeventlistener("keydown", function(event) { switch (event.key) { case "arrowright": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) + 1); break; case "arrowleft": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) - 1); break; case "arrowdown": moveto(parseint(event.target.dataset.row, 10) + 1, parseint(event.target.dataset.col, 10)); break; ...
TypeError: X.prototype.y called on incompatible type - JavaScript
examples invalid cases var myset = new set; ['bar', 'baz'].foreach(myset.add); // myset.add is a function, but "myset" is not captured as this.
... var myfun = function () { console.log(this); }; ['bar', 'baz'].foreach(myfun.bind); // myfun.bind is a function, but "myfun" is not captured as this.
... valid cases var myset = new set; ['bar', 'baz'].foreach(myset.add.bind(myset)); // this works due to binding "myset" as this.
... var myfun = function () { console.log(this); }; ['bar', 'baz'].foreach(x => myfun.bind(x)); // this works using the "bind" function.
Example 3 - Learn web development
.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('hidden'); select.classlist.remove('active'); } function activeselect(selec...
...t, selectlist) { if (select.classlist.contains('active')) return; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.queryselector('.optlist'); optlist.classlist.toggle('hidden'); } function highlightoption(select, option) { var optionlist = select.queryselectorall('.option'); optionlist.foreach(function (other) { other.classlist.remove('highlight'); }); option.classlist.add('highlight'); }; // ------------- // // event binding // // ------------- // window.addeventlistener("load", function () { var form = document.queryselector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); window.addeventlistener('load', function () { var selectlist = document...
....queryselectorall('.select'); selectlist.foreach(function (select) { var optionlist = select.queryselectorall('.option'); optionlist.foreach(function (option) { option.addeventlistener('mouseover', function () { highlightoption(select, option); }); }); select.addeventlistener('click', function (event) { toggleoptlist(select); }, false); select.addeventlistener('focus', function (event) { activeselect(select, selectlist); }); select.addeventlistener('blur', function (event) { deactivateselect(select); }); select.addeventlistener('keyup', function (event) { if (event.keycode === 27) { deactivateselect(select); } }); }); }); result ...
Example 5 - Learn web development
.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('hidden'); select.classlist.remove('active'); } function activeselect(selec...
...t, selectlist) { if (select.classlist.contains('active')) return; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.queryselector('.optlist'); optlist.classlist.toggle('hidden'); } function highlightoption(select, option) { var optionlist = select.queryselectorall('.option'); optionlist.foreach(function (other) { other.classlist.remove('highlight'); }); option.classlist.add('highlight'); }; function updatevalue(select, index) { var nativewidget = select.previouselementsibling; var value = select.queryselector('.value'); var optionlist = select.queryselectorall('.option'); optionlist.foreach(function (other) { other.setattribute('aria-selected', 'false'); }); optionlist...
...mentsibling; return nativewidget.selectedindex; }; // ------------- // // event binding // // ------------- // window.addeventlistener("load", function () { var form = document.queryselector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); window.addeventlistener('load', function () { var selectlist = document.queryselectorall('.select'); selectlist.foreach(function (select) { var optionlist = select.queryselectorall('.option'), selectedindex = getindex(select); select.tabindex = 0; select.previouselementsibling.tabindex = -1; updatevalue(select, selectedindex); optionlist.foreach(function (option, index) { option.addeventlistener('mouseover', function () { highlightoption(select, option); }); ...
Animation.playState - Web APIs
so they must be paused as soon as they are animated like so: // setting up the tear animations tears.foreach(function(el) { el.animate( tearsfalling, { delay: getrandommsrange(-1000, 1000), // randomized for each tear duration: getrandommsrange(2000, 6000), // randomized for each tear iterations: infinity, easing: 'cubic-bezier(0.6, 0.04, 0.98, 0.335)' }); el.pause(); }); // play the tears falling when the ending needs to be shown.
... tears.foreach(function(el) { el.play(); }); // reset the crying tears animations and pause them.
... tears.foreach(function(el) { el.pause(); el.currenttime = 0; }); specifications specification status comment web animationsthe definition of 'playstate' in that specification.
AudioTrack - Web APIs
usage notes to get an audiotrack for a given media element, use the element's audiotracks property, which returns an audiotracklist object from which you can get the individual tracks contained in the media: var el = document.queryselector("video"); var tracks = el.audiotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach().
... tracks.foreach(function(track) { if (track.language === userlanguage) { track.enabled = true; } else { track.enabled = false; } }); the language is in standard (rfc 5646) format.
... function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "main-desc", "translation", "commentary" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return tracklist; } the resulting tracklist contains an array of audio tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label.
Basic animations - Web APIs
le = this.cc; c.moveto(ls.x, ls.y); c.lineto(this.x, this.y); c.stroke(); c.closepath(); } } function anim() { requestanimationframe(anim); c.fillstyle = "rgba(0,0,0,0.05)"; c.fillrect(0, 0, cn.width, cn.height); a.foreach(function(e, i) { e.dr(); }); } </script> <style> #cw { position: fixed; z-index: -1; } body { margin: 0; padding: 0; background-color: rgba(0,0,0,0.05); } </style> </head> <body> <c...
...fa.findindex(t => coll({ ...this.sn[0], h: this.h, w: this.w }, t)), this.sn.unshift(i), -1 != e) return console.log(e), fa[e].renew(), void (document.getelementbyid("score").innertext = number(document.getelementbyid("score").innertext) + 1); this.sn.pop(), console.log(6) } this.sn.foreach((t, e, i) => { if (0 == e || i.length - 1 == e) { var n = c.createlineargradient(t.x, t.y, t.x + this.w, t.y + this.h); i.length - 1 == e ?
..., c.linewidth = 10, c.stroke(), c.beginpath(), c.linewidth = 1 }) } function init() { cc.height = h, cc.width = w, c.fillrect(0, 0, w, innerheight); for (var t = 0; t < 10; t++) fa.push(new food); s = new snake(w / 2, h / 2, 400, 4, 4), anima() } function anima() { c.fillstyle = "rgba(0,0,0,0.11)", c.fillrect(0, 0, cc.width, cc.height), fa.foreach(t => t.put()), s.draw(), document.getelementbyid("time").innertext = tmz(), settimeout(() => { requestanimationframe(anima) }, fw) } function emit(t) { key.keydown(t) } function touch(t) { t.classlist.toggle("off"), document.getelementsbyclassname("keypress")[0].classlist.toggle("hide") } var t = new date + "", d = void 0, ...
Timing element visibility with the Intersection Observer API - Web APIs
function handlevisibilitychange() { if (document.hidden) { if (!previouslyvisibleads) { previouslyvisibleads = visibleads; visibleads = []; previouslyvisibleads.foreach(function(adbox) { updateadtimer(adbox); adbox.dataset.lastviewstarted = 0; }); } } else { previouslyvisibleads.foreach(function(adbox) { adbox.dataset.lastviewstarted = performance.now(); }); visibleads = previouslyvisibleads; previouslyvisibleads = null; } } since the event itself doesn't state whether the document has switched from visible to...
...our callback, intersectioncallback(), looks like this: function intersectioncallback(entries) { entries.foreach(function(entry) { let adbox = entry.target; if (entry.isintersecting) { if (entry.intersectionratio >= 0.75) { adbox.dataset.lastviewstarted = entry.time; visibleads.add(adbox); } } else { visibleads.delete(adbox); if ((entry.intersectionratio === 0.0) && (adbox.dataset.totalviewtime >= 60000)) { replacead(adbox); } } }); } ...
... function handlerefreshinterval() { let redrawlist = []; visibleads.foreach(function(adbox) { let previoustime = adbox.dataset.totalviewtime; updateadtimer(adbox); if (previoustime != adbox.dataset.totalviewtime) { redrawlist.push(adbox); } }); if (redrawlist.length) { window.requestanimationframe(function(time) { redrawlist.foreach(function(adbox) { drawadtimer(adbox); }); }); } } the array redrawlist will be us...
MediaDeviceInfo.groupId - Web APIs
const getdevicegroup = maindevinfo => { let devlist = []; navigator.mediadevices.enumeratedevices() .then(devices => { devices.foreach(device => { if (device.groupid === maindevinfo.groupid) { devlist.push(device); } }); }); return devlist; }; the getdevicegroup() function takes as input the mediadeviceinfo object describing the device for which a group list is to be built.
...once the promise resolves, we walk the list using foreach().
... this version of the example puts the passed-in device at the top of the result list, then adds any other members of the group that are found: const getdevicegroup = maindevinfo => { let devlist = [maindevinfo]; navigator.mediadevices.enumeratedevices() .then(devices => { devices.foreach(device => { if ((device.groupid === maindevinfo.groupid) && (device.deviceid !== maindevinfo.deviceid)) { devlist.push(device); } }); }); return devlist; }; ...
Map - JavaScript
map.prototype.foreach(callbackfn[, thisarg]) calls callbackfn once for each key-value pair present in the map object, in insertion order.
... if a thisarg parameter is provided to foreach, it will be used as the this value for each callback.
...ymap.set(0, 'zero') mymap.set(1, 'one') for (let [key, value] of mymap) { console.log(key + ' = ' + value) } // 0 = zero // 1 = one for (let key of mymap.keys()) { console.log(key) } // 0 // 1 for (let value of mymap.values()) { console.log(value) } // zero // one for (let [key, value] of mymap.entries()) { console.log(key + ' = ' + value) } // 0 = zero // 1 = one iterating map with foreach() maps can be iterated using the foreach() method: mymap.foreach(function(value, key) { console.log(key + ' = ' + value) }) // 0 = zero // 1 = one relation with array objects let kvarray = [['key1', 'value1'], ['key2', 'value2']] // use the regular map constructor to transform a 2d key-value array into a map let mymap = new map(kvarray) mymap.get('key1') // returns "value1" // use array...
Codecs used by WebRTC - Web media technologies
let codeclist = null; peerconnection.addeventlistener("icegatheringstatechange", (event) => { if (peerconnection.icegatheringstate === "complete") { const senders = peerconnection.getsenders(); senders.foreach((sender) => { if (sender.track.kind === "video") { codeclist = sender.getparameters().codecs; return; } }); } codeclist = null; }); the event handler for icegatheringstatechange is established; in it, we look to see if the ice gathering state is complete, indicating that no further candidates will be collected.
... function changevideocodec(mimetype) { const transceivers = peerconnection.gettransceivers(); transceivers.foreach(transceiver => { const kind = transceiver.sender.track.kind; let sendcodecs = rtcrtpsender.getcapabilities(kind).codecs; let recvcodecs = rtcrtpreceiver.getcapabilities(kind).codecs; if (kind === "video") { sendcodecs = prefercodec(mimetype); recvcodecs = prefercodec(mimetype); transceiver.setcodecpreferences([...sendcodecs, ...recvcodecs]); } }); peerc...
... the prefercodec() function called by the code above looks like this to move a specified codec to the top of the list (to be prioritized during negotiation): function prefercodec(codecs, mimetype) { let othercodecs = []; let sortedcodecs = []; let count = codecs.length; codecs.foreach(codec => { if (codec.mimetype === mimetype) { sortedcodecs.push(codec); } else { othercodecs.push(codec); } }); return sortedcodecs.concat(othercodecs); } this code is just splitting the codec list into two arrays: one containing codecs whose mime type matches the one specified by the mimetype parameter, and the other with all the other codecs.
Porting the Library Detector - Archive of obsolete content
to that worker using worker.tab, and adding the array of library names to that tab's libraries property: pagemod.pagemod({ include: "*", contentscriptwhen: 'end', contentscriptfile: (data.url('library-detector.js')), onattach: function(worker) { worker.on('message', function(librarylist) { if (!worker.tab.libraries) { worker.tab.libraries = []; } librarylist.foreach(function(library) { if (worker.tab.libraries.indexof(library) == -1) { worker.tab.libraries.push(library); } }); if (worker.tab == tabs.activetab) { updatewidgetview(worker.tab); } }); } }); the content script is executed once for every window.onload event, so it will run multiple times when a single page containing multiple iframes is l...
... main.js will create an array of icons corresponding to the array of library names, and use that to build the widget's html content dynamically: function buildwidgetviewcontent(librarylist) { widgetcontent = htmlcontentpreamble; librarylist.foreach(function(library) { widgetcontent += buildiconhtml(icons[library.name], library.name + "&lt;br&gt;version: " + library.version); }); widgetcontent += htmlcontentpostamble; return widgetcontent; } function updatewidgetview(tab) { var widgetview = widget.getview(tab.window); if (!tab.libraries) { tab.libraries = []; } widgetview.content = buildwidgetviewcontent(tab.
Displaying annotations - Archive of obsolete content
the complete content script is here: self.on('message', function onmessage(annotations) { annotations.foreach( function(annotation) { if(annotation.url == document.location.tostring()) { createanchor(annotation); } }); $('.annotated').css('border', 'solid 3px yellow'); $('.annotated').bind('mouseenter', function(event) { self.port.emit('show', $(this).attr('annotation')); event.stoppropagation(); event.preventdefault(); }); $('.annotated').bind('mouseleave...
... then in the module's scope implement a function to update the matcher's workers, and edit handlenewannotation to call this new function when the user enters a new annotation: function updatematchers() { matchers.foreach(function (matcher) { matcher.postmessage(simplestorage.storage.annotations); }); } function handlenewannotation(annotationtext, anchor) { var newannotation = new annotation(annotationtext, anchor); simplestorage.storage.annotations.push(newannotation); updatematchers(); } annotation panel the annotation panel just shows the content of an annotation.
How to convert an overlay extension to restartless - Archive of obsolete content
a basic bootstrap.js file: components.utils.import("resource://gre/modules/services.jsm"); function startup(data,reason) { components.utils.import("chrome://myaddon/content/mymodule.jsm"); mymodule.startup(); // do whatever initial startup stuff you need to do foreachopenwindow(loadintowindow); services.wm.addlistener(windowlistener); } function shutdown(data,reason) { if (reason == app_shutdown) return; foreachopenwindow(unloadfromwindow); services.wm.removelistener(windowlistener); mymodule.shutdown(); // do whatever shutdown stuff you need to do on addon disable components.utils.unload("chrome://myaddon/content/mymodule.j...
...in order to fully update images and locales, their caches need clearing here services.obs.notifyobservers(null, "chrome-flush-caches", null); } function install(data,reason) { } function uninstall(data,reason) { } function loadintowindow(window) { /* call/move your ui construction function here */ } function unloadfromwindow(window) { /* call/move your ui tear down function here */ } function foreachopenwindow(todo) // apply a function to all open browser windows { var windows = services.wm.getenumerator("navigator:browser"); while (windows.hasmoreelements()) todo(windows.getnext().queryinterface(components.interfaces.nsidomwindow)); } var windowlistener = { onopenwindow: function(xulwindow) { var window = xulwindow.queryinterface(components.interfaces.nsiinte...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
if (array.isarray(elemnameorarray)) { var frag = doc.createdocumentfragment(); array.foreach(arguments, function(thiselem) { frag.appendchild(tag.apply(null, thiselem)); }); return frag; } // single element?
...they're not in any namespace) elem.setattributens(attrns.namespace || "", attrns.shortname, val); } } // create and append this element's children var childelems = array.slice(arguments, 2); childelems.foreach(function(childelem) { if (childelem != null) { elem.appendchild( childelem instanceof doc.defaultview.node ?
jspage - Archive of obsolete content
rcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr","substring","tolowercase","touppercase","valueof"]}; for(var e in f){for(var b=f[e].length;b--;){native.genericize(a[e],f[e][b],true);}}})();var hash=new native({name:"hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getclean()); }for(var b in a){this[b]=a[b];}return this;}});hash.implement({foreach:function(b,c){for(var a in this){if(this.hasownproperty(a)){b.call(c,this[a],a,this); }}},getclean:function(){var b={};for(var a in this){if(this.hasownproperty(a)){b[a]=this[a];}}return b;},getlength:function(){var b=0;for(var a in this){if(this.hasownproperty(a)){b++; }}return b;}});hash.alias("foreach","each");array.implement({foreach:function(c,d){for(var b=0,a=this.length;b<a;b++){c.call(d,t...
...his[b],b,this);}}});array.alias("foreach","each"); function $a(b){if(b.item){var a=b.length,c=new array(a);while(a--){c[a]=b[a];}return c;}return array.prototype.slice.call(b);}function $arguments(a){return function(){return arguments[a]; };}function $chk(a){return !!(a||a===0);}function $clear(a){cleartimeout(a);clearinterval(a);return null;}function $defined(a){return(a!=undefined);}function $each(c,b,d){var a=$type(c); ((a=="arguments"||a=="collection"||a=="array")?array:hash).each(c,b,d);}function $empty(){}function $extend(c,a){for(var b in (a||{})){c[b]=a[b];}return c; }function $h(a){return new hash(a);}function $lambda(a){return($type(a)=="function")?a:function(){return a;};}function $merge(){var a=array.slice(arguments); a.unshift({});return $mixin.apply(null,a);}function $mixin(e){for(v...
Introducing asynchronous JavaScript - Learn web development
an example is when we use array.prototype.foreach() to loop through the items in an array (see it live, and the source): const gods = ['apollo', 'artemis', 'ares', 'zeus']; gods.foreach(function (eachname, index){ console.log(index + '.
...the expected parameter of foreach() is a callback function, which itself takes two parameters, a reference to the array name and index values.
Shell global objects
enableforeach() enables the deprecated, non-standard for-each.
... disableforeach() disables the deprecated, non-standard for-each.
AudioTrack.enabled - Web APIs
function swapcommentarymain() { var videoelem = document.getelementbyid("main-video"); var audiotrackmain; var audiotrackcommentary; videoelem.audiotracks.foreach(track) { if (track.kind === "main") { audiotrackmain = track; } else if (track.kind === "commentary") { audiotrackcommentary = track; } } if (audiotrackmain && audiotrackcommentary) { var commentaryenabled = audiotrackcommentary.enabled; audiotrackcommentary.enabled = audiotrackmain.enabled; audiotrackmain.enabled = commentaryenabled; } } the swapcomme...
... 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).
MediaDevices.ondevicechange - Web APIs
function updatedevicelist() { navigator.mediadevices.enumeratedevices() .then(function(devices) { audiolist.innerhtml = ""; videolist.innerhtml = ""; devices.foreach(function(device) { let elem = document.createelement("li"); let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i); elem.innerhtml = "<strong>" + device.label + "</strong> (" + direction + ")"; if (type === "audio") { audiolist.appendchild(elem); } else if (type === "video") { videolist.appendchild(elem); } }); }); } upd...
... a foreach() loop is used to scan through all the devices.
MediaStreamTrack.stop() - Web APIs
function stopstreamedvideo(videoelem) { const stream = videoelem.srcobject; const tracks = stream.gettracks(); tracks.foreach(function(track) { track.stop(); }); videoelem.srcobject = null; } this works by obtaining the video element's stream from its srcobject property.
...from there, all that remains to do is to iterate over the track list using foreach() and calling each track's stop() method.
PerformanceEventTiming - Web APIs
examples the following example shows how to use the api for all events: const observer = new performanceobserver(function(list) { const perfentries = list.getentries().foreach(entry => { // full duration const inputduration = entry.duration; // input delay (before processing event) const inputdelay = entry.processingstart - entry.starttime; // synchronous event processing time (between start and end dispatch).
... const po = new performanceobserver((entrylist) => { entrylist.getentries().foreach(onfirstinputentry); }); // observe entries of type `first-input`, including buffered entries, // i.e.
RTCIceCandidateStats.deleted - Web APIs
window.setinterval(function() { mypeerconnection.getstats(null).then(stats => { let statsoutput = ""; stats.foreach(report => { if ((stats.type === "local-candidate" || stats.type === "remote.candidate") && !stats.deleted) { statsoutput += `<h2>report: ${report.type}</h3>\n<strong>id:</strong> ${report.id}<br>\n` + `<strong>timestamp:</strong> ${report.timestamp}<br>\n`; // now the statistics for this report; we intentially drop the ones we // sorted to the...
... top above object.keys(report).foreach(statname => { if (statname !== "id" && statname !== "timestamp" && statname !== "type") { statsoutput += `<strong>${statname}:</strong> ${report[statname]}<br>\n`; } }); } }); document.queryselector(".stats-box").innerhtml = statsoutput; }); }, 1000); specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatestats.deleted' in that specification.
RTCIceCandidateStats.networkType - Web APIs
window.setinterval(function() { mypeerconnection.getstats(null).then(stats => { let statsoutput = ""; stats.foreach(report => { if ((stats.type === "local-candidate" || stats.type === "remote.candidate") && stats.networktype === "cellular") { statsoutput += `<h2>report: ${report.type}</h3>\n<strong>id:</strong> ${report.id}<br>\n` + `<strong>timestamp:</strong> ${report.timestamp}<br>\n`; // now the statistics for this report; we intentially drop the ones we ...
... // sorted to the top above object.keys(report).foreach(statname => { if (statname !== "id" && statname !== "timestamp" && statname !== "type") { statsoutput += `<strong>${statname}:</strong> ${report[statname]}<br>\n`; } }); } }); document.queryselector(".stats-box").innerhtml = statsoutput; }); }, 1000); ...
Using writable streams - Web APIs
o be written and the stream to write to: sendmessage("hello, world.", writablestream); the sendmessage() definition looks like so: function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
... with the chunks encoded, we then call array/foreach on the resulting array.
Using DTMF with WebRTC - Web APIs
function gotstream(stream) { log("got access to the microphone."); let audiotracks = stream.getaudiotracks(); if (hasaddtrack) { if (audiotracks.length > 0) { audiotracks.foreach(track => callerpc.addtrack(track, stream)); } } else { log("your browser doesn't support rtcpeerconnection.addtrack().
...disconnecting."); callerpc.getlocalstreams().foreach(function(stream) { stream.gettracks().foreach(function(track) { track.stop(); }); }); receiverpc.getlocalstreams().foreach(function(stream) { stream.gettracks().foreach(function(track) { track.stop(); }); }); audio.pause(); audio.srcobject = null; receiverpc.close(); callerpc.close(); } } the tonechange event is used both to...
Using the Web Speech API - Web APIs
the foreach() method is used to output colored indicators showing what colors to try saying.
... var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); var hints = document.queryselector('.hints'); var colorhtml= ''; colors.foreach(function(v, i, a){ console.log(v, i); colorhtml += '<span style="background-color:' + v + ';"> ' + v + ' </span>'; }); hints.innerhtml = 'tap/click then say a color to change the background color of the app.
WritableStream.WritableStream() - Web APIs
a foreach() call is used to write each chunk of the string to the stream.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
WritableStream.getWriter() - Web APIs
a foreach() call is used to write each chunk of the string to the stream.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
WritableStream - Web APIs
a foreach() call is used to write each chunk of the string to the stream.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
a foreach() call is used to write each chunk of the string to the stream.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
WritableStreamDefaultWriter.close() - Web APIs
a foreach() call is used to write each chunk of the string to the stream.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
WritableStreamDefaultWriter.write() - Web APIs
a foreach() call is used to write each chunk of the string to the stream.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
WritableStreamDefaultWriter - Web APIs
a foreach() call is used to write each chunk of the string to the stream.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
XRInputSourceArray - Web APIs
in addition to being able to access the input sources in the list using standard array notation (that is, with index numbers insize square brackets), methods are available to allow the use of iterators and the foreach() method is also available.
... foreach() iterates over each item in the list, in order from first to last.
ARIA: tab role - Accessibility
window.addeventlistener("domcontentloaded", () => { const tabs = document.queryselectorall('[role="tab"]'); const tablist = document.queryselector('[role="tablist"]'); // add a click event handler to each tab tabs.foreach(tab => { tab.addeventlistener("click", changetabs); }); // enable arrow navigation between tabs in the tab list let tabfocus = 0; tablist.addeventlistener("keydown", e => { // move right if (e.keycode === 39 || e.keycode === 37) { tabs[tabfocus].setattribute("tabindex", -1); if (e.keycode === 39) { tabfocus++; // if we're at the end, go to the sta...
...tabfocus < 0) { tabfocus = tabs.length - 1; } } tabs[tabfocus].setattribute("tabindex", 0); tabs[tabfocus].focus(); } }); }); function changetabs(e) { const target = e.target; const parent = target.parentnode; const grandparent = parent.parentnode; // remove all current selected tabs parent .queryselectorall('[aria-selected="true"]') .foreach(t => t.setattribute("aria-selected", false)); // set this tab as selected target.setattribute("aria-selected", true); // hide all tab panels grandparent .queryselectorall('[role="tabpanel"]') .foreach(p => p.setattribute("hidden", true)); // show the selected panel grandparent.parentnode .queryselector(`#${target.getattribute("aria-controls")}`) .removeattribute("hi...
<input type="color"> - HTML: Hypertext Markup Language
WebHTMLElementinputcolor
here's an example that watches changes over time to the color value: colorpicker.addeventlistener("input", updatefirst, false); colorpicker.addeventlistener("change", watchcolorpicker, false); function watchcolorpicker(event) { document.queryselectorall("p").foreach(function(p) { p.style.color = event.target.value; }); } selecting the value if the <input> element's implementation of the color type on the user's browser doesn't support a color well, but is instead a text field for entering the color string directly, you can use the select() method to select the text currently in the edit field.
...we handle that event using the updateall() function, using event.target.value to obtain the final selected color: function updateall(event) { document.queryselectorall("p").foreach(function(p) { p.style.color = event.target.value; }); } this sets the color of every <p> block so that its color attribute matches the current value of the color input, which is referred to using event.target.
Enumerability and ownership of properties - JavaScript
detection can occur by simplepropertyretriever.thegetmethodyouwant(obj).indexof(prop) > -1 iteration can occur by simplepropertyretriever.thegetmethodyouwant(obj).foreach(function (value, prop) {}); (or use filter(), map(), etc.) var simplepropertyretriever = { getownenumerables: function(obj) { return this._getpropertynames(obj, true, false, this._enumerable); // or could use for..in filtered with hasownproperty or just this: return object.keys(obj); }, getownnonenumerables: function(obj) { return this._getpropertynames(obj,...
...merable(prop); }, _enumerableandnotenumerable: function(obj, prop) { return true; }, // inspired by http://stackoverflow.com/a/8024294/271577 _getpropertynames: function getallpropertynames(obj, iterateselfbool, iterateprototypebool, includepropcb) { var props = []; do { if (iterateselfbool) { object.getownpropertynames(obj).foreach(function(prop) { if (props.indexof(prop) === -1 && includepropcb(obj, prop)) { props.push(prop); } }); } if (!iterateprototypebool) { break; } iterateselfbool = true; } while (obj = object.getprototypeof(obj)); return props; } }; det...
Inheritance and the prototype chain - JavaScript
// o ---> object.prototype ---> null var b = ['yo', 'whadup', '?']; // arrays inherit from array.prototype // (which has methods indexof, foreach, etc.) // the prototype chain looks like: // b ---> array.prototype ---> object.prototype ---> null function f() { return 2; } // functions inherit from function.prototype // (which has methods call, bind, etc.) // f ---> function.prototype ---> object.prototype ---> null with a constructor a "constructor" in javascript is "just" a function that happens to be called with the new operator.
... the only good reason for extending a built-in prototype is to backport the features of newer javascript engines, like array.foreach.
Array - JavaScript
common operations create an array let fruits = ['apple', 'banana'] console.log(fruits.length) // 2 access an array item using the index position let first = fruits[0] // apple let last = fruits[fruits.length - 1] // banana loop over an array fruits.foreach(function(item, index, array) { console.log(item, index) }) // apple 0 // banana 1 add an item to the end of an array let newlength = fruits.push('orange') // ["apple", "banana", "orange"] remove an item from the end of an array let last = fruits.pop() // remove orange (from the end) // ["apple", "banana"] remove an item from the beginning of an array let first = fruits.shift() // remov...
... array.prototype.foreach() calls a function for each element in the array.
BigInt64Array - JavaScript
bigint64array.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
BigUint64Array - JavaScript
biguint64array.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
Float32Array - JavaScript
float32array.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
Float64Array - JavaScript
float64array.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
Int16Array - JavaScript
int16array.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
Int32Array - JavaScript
int32array.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
Int8Array - JavaScript
int8array.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
Object.entries() - JavaScript
['0', 'f'], ['1', 'o'], ['2', 'o'] ] // returns an empty array for any primitive type, since primitives have no own properties console.log(object.entries(100)); // [ ] // iterate through key-value gracefully const obj = { a: 5, b: 7, c: 9 }; for (const [key, value] of object.entries(obj)) { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" } // or, using array extras object.entries(obj).foreach(([key, value]) => { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" }); converting an object to a map the new map() constructor accepts an iterable of entries.
... const obj = { foo: 'bar', baz: 42 }; object.entries(obj).foreach(([key, value]) => console.log(`${key}: ${value}`)); // "foo: bar", "baz: 42" specifications specification ecmascript (ecma-262)the definition of 'object.entries' in that specification.
Set - JavaScript
set.prototype.foreach(callbackfn[, thisarg]) calls callbackfn once for each value present in the set object, in insertion order.
...lector('body')) // true // converting between set and array myset2 = new set([1, 2, 3, 4]) myset2.size // 4 [...myset2] // [1, 2, 3, 4] // intersect can be simulated via let intersection = new set([...set1].filter(x => set2.has(x))) // difference can be simulated via let difference = new set([...set1].filter(x => !set2.has(x))) // iterate set entries with foreach() myset.foreach(function(value) { console.log(value) }) // 1 // 2 // 3 // 4 implementing basic set operations function issuperset(set, subset) { for (let elem of subset) { if (!set.has(elem)) { return false } } return true } function union(seta, setb) { let _union = new set(seta) for (let elem of setb) { _union.add(elem) } retu...
TypedArray - JavaScript
typedarray.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
Uint16Array - JavaScript
uint16array.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
Uint32Array - JavaScript
uint32array.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
Uint8Array - JavaScript
uint8array.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
Uint8ClampedArray - JavaScript
uint8clampedarray.prototype.foreach() calls a function for each element in the array.
... see also array.prototype.foreach().
for...in - JavaScript
therefore, it is better to use a for loop with a numeric index (or array.prototype.foreach() or the for...of loop) when iterating over arrays where the order of access is important.
... given that for...in is built for iterating object properties, not recommended for use with arrays, and options like array.prototype.foreach() and for...of exist, what might be the use of for...in at all?
Navigation and resource timings - Web Performance
you can also create marks: performance.getentriesbytype('navigation').foreach((navigation) => { console.dir(navigation); }); performance.getentriesbytype('resource').foreach((resource) => { console.dir(resource); }); performance.getentriesbytype('mark').foreach((mark) => { console.dir(mark); }); performance.getentriesbytype("measure").foreach((measure) => { console.dir(measure); }); performance.getentriesbytype('paint').foreach((paint) => { console.dir(paint)...
...; }); performance.getentriesbytype('frame').foreach((frame) => { console.dir(frame); }); in supporting browsers, you can use performance.getentriesbytype('paint') to query the measure for first-paint and first-contentful-paint.
Progressive loading - Progressive web apps (PWAs)
then we loop through each image and load it: imagestoload.foreach((img) => { loadimages(img); }); blur in css to make the whole process more visually appealing, the placeholder is blurred in css.
... here's what the relevant code looks like: if('intersectionobserver' in window) { const observer = new intersectionobserver((items, observer) => { items.foreach((item) => { if(item.isintersecting) { loadimages(item.target); observer.unobserve(item.target); } }); }); imagestoload.foreach((img) => { observer.observe(img); }); } else { imagestoload.foreach((img) => { loadimages(img); }); } if the intersectionobserver object is supported, the app creates a new instance of it.
core/promise - Archive of obsolete content
in the following example we implement functions that take multiple promises and return one that resolves to first one being fulfilled: function race() { let { promise, resolve } = defer(); array.slice(arguments).foreach(function(promise) { promise.then(resolve); }); return promise; } var asyncaorb = race(readasync(urla), readasync(urlb)); note: that this implementation forgives failures and would fail if all promises fail to resolve.
util/list - Archive of obsolete content
examples: var { list } = require("sdk/util/list"); var mylist = list.compose({ add: function add(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._add.bind(this)); }, remove: function remove(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._remove.bind(this)); } }); mylist('foo', 'bar', 'baz').length == 3; // true new mylist('new', 'keyword').length == 2; // true mylist.apply(null, [1, 2, 3]).length == 3; // true let list = mylist(); list.length == 0; // true l...
Creating annotations - Archive of obsolete content
module and declare an array for the workers: var pagemod = require('sdk/page-mod'); var selectors = []; add detachworker(): function detachworker(worker, workerarray) { var index = workerarray.indexof(worker); if(index != -1) { workerarray.splice(index, 1); } } edit toggleactivation() to notify the workers of a change in activation state: function activateselectors() { selectors.foreach( function (selector) { selector.postmessage(annotatorison); }); } function toggleactivation() { annotatorison = !annotatorison; activateselectors(); return annotatorison; } we'll be using this url in all our screenshots.
Storing annotations - Archive of obsolete content
annotation list content script here's the annotation list's content script: self.on("message", function onmessage(storedannotations) { var annotationlist = $('#annotation-list'); annotationlist.empty(); storedannotations.foreach( function(storedannotation) { var annotationhtml = $('#template .annotation-details').clone(); annotationhtml.find('.url').text(storedannotation.url) .attr('href', storedannotation.url); annotationhtml.find('.url').bind('click', function(event) { event.stoppropagation(); event.preventdefault(); self.postmessage(storeda...
Getting started (cfx) - Archive of obsolete content
another example using grunt and grunt-shell: module.exports = function(grunt) { 'use strict'; require('matchdep').filterdev('grunt-!(cli)').foreach(grunt.loadnpmtasks); grunt.initconfig({ shell: { xpi: { command: [ 'cd pluginpath', 'cfx xpi', 'wget --post-file=pluginname.xpi http://localhost:8888/ || echo>/dev/null' ].join('&&') } }, watch: { xpi: { files: ['pluginpath/**'], tasks: ['shell:xpi'] } } }); grunt.loadnpmtasks('grunt-contr...
Preferences - Archive of obsolete content
foreach(function (pref_leaf_name) { that._callback(that._branch, pref_leaf_name); }); } }; preflistener.prototype.unregister = function() { if (this._branch) this._branch.removeobserver('', this); }; var mylistener = new preflistener( "extensions.myextension.", function(branch, name) { switch (name) { case "pref1": // extensions.myextension.pref1 was changed ...
Intercepting Page Loads - Archive of obsolete content
here's a code sample that keeps track of your progress listeners for all tabs: init : function() { gbrowser.browsers.foreach(function (browser) { this._toggleprogresslistener(browser.webprogress, true); }, this); gbrowser.tabcontainer.addeventlistener("tabopen", this, false); gbrowser.tabcontainer.addeventlistener("tabclose", this, false); }, uninit : function() { gbrowser.browsers.foreach(function (browser) { this ._toggleprogresslistener(browser.webprogress, false); }, this); gbrowser.tabcontai...
Promises - Archive of obsolete content
let iter = new os.file.directoryiterator(dir); yield iter.foreach(entry => { if (!entry.isdir) files.push(entry.path); }); iter.close(); } // read the files as binary blobs and process them.
Index - Archive of obsolete content
znerd 04 august 2009 2249 foreach ok, in the end i didn't remove the old code as it isn't hosted anywhere (i thought the github reference contained the code) but inserted a faster implementation above while retaining the rest of the document.
Index of archived content - Archive of obsolete content
e custom controls interfaces rfe to the xforms api troubleshooting xforms forms using xforms and php xforms api reference xforms config variables xforms custom controls xforms custom controls examples xforms styling background-size foreach beginner tutorials creating reusable content with css and xbl underscores in class and id names xml data xul user interfaces case sensitivity in class and id names creating a dynamic status bar extension creating a status bar extension element ...
Simple Storage - Archive of obsolete content
examples this code persistently stores some data: jetpack.future.import("storage.simple");var mystorage = jetpack.storage.simple;mystorage.fribblefrops = [1, 3, 3, 7];mystorage.heimelfarbs = { bar: "baz" }; and this code -- pretend it's in the same jetpack as the code above -- simply uses that data: mystorage.fribblefrops.foreach(function (elt) console.log(elt));var bar = mystorage.heimelfarbs.bar;jetpack.notifications.show(bar.baz); that's all there is to it!
Simple Storage - Archive of obsolete content
examples this code persistently stores some data: jetpack.future.import("storage.simple"); var mystorage = jetpack.storage.simple; mystorage.fribblefrops = [1, 3, 3, 7]; mystorage.heimelfarbs = { bar: "baz" }; and this code -- pretend it's in the same jetpack as the code above -- simply uses that data: mystorage.fribblefrops.foreach(function (elt) console.log(elt)); var bar = mystorage.heimelfarbs.bar; jetpack.notifications.show(bar.baz); that's all there is to it!
Sorting and filtering a custom tree view - Archive of obsolete content
ck"}); data.push({name: "shredder", description: "armored man", weapon: "blades"}); data.push({name: "casey jones", description: "goalie masked man", weapon: "hockey stick"}); data.push({name: "april o'neil", description: "journalist", weapon: "none"}); } if (filtertext == "") { //show all of them table = data; } else { //filter out the ones we want to display table = []; data.foreach(function(element) { //we'll match on every property for (var i in element) { if (prepareforcomparison(element[i]).indexof(filtertext) != -1) { table.push(element); break; } } }); } sort(); //restore scroll position if (topvisiblerow) { settopvisiblerow(topvisiblerow); } } //generic custom tree view stuff function treeview(table) { this.rowcount = table.leng...
Processing XML with E4X - Archive of obsolete content
despite these similarities to regular arrays, xmllist does not support array methods such as foreach, and array generics such as array.foreach() are not compatible with xmllist objects.
New in JavaScript 1.6 - Archive of obsolete content
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.
ECMAScript 2015 support in Mozilla - Archive of obsolete content
e.fill() (firefox 31) array.prototype.find(), array.prototype.findindex() (firefox 25) array.prototype.entries(), array.prototype.keys() (firefox 28), array.prototype.values() array.prototype.copywithin() (firefox 32) get array[@@species] (firefox 48) new map and set objects, and their weak counterparts map (firefox 13) map iteration with for...of (firefox 17) map.prototype.foreach() (firefox 25) map.prototype.entries() (firefox 20) map.prototype.keys() (firefox 20) map.prototype.values() constructor argument: new map(null) (firefox 37) monkey-patched set() in constructor (firefox 37) get map[@@species] (firefox 41) set (firefox 13) set iteration with for...of (firefox 17) set.prototype.foreach() (firefox 25) set.prototype.entries(), ...
Object.observe() - Archive of obsolete content
name: 'bar', object: <obj>, type: 'reconfigure'}, // {object: <obj>, type: 'preventextensions'} // ] data binding // a user model var user = { id: 0, name: 'brendan eich', title: 'mr.' }; // create a greeting for the user function updategreeting() { user.greeting = 'hello, ' + user.title + ' ' + user.name + '!'; } updategreeting(); object.observe(user, function(changes) { changes.foreach(function(change) { // any time name or title change, update the greeting if (change.name === 'name' || change.name === 'title') { updategreeting(); } }); }); custom change type // a point on a 2d plane var point = {x: 0, y: 0, distance: 0}; function setposition(pt, x, y) { // performing a custom change object.getnotifier(pt).performchange('reposition', function() { ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
listing 10 - creating a simple xml service <script runat="server"> var rs_comments = jaxer.db.execute("select * from comments"); var doc = document.implementation.createdocument('', 'comments', null); var root = doc.documentelement; rs_comments.rows.foreach(function(row, index) { if (true || index < 10) { var node = doc.createelement('comment'); node.setattribute('id', row.id); node.setattribute('name', row.name); node.setattribute('message', row.message); root.appendchild(node); } }); jaxer.response.exit(200, doc); </script> the data from the database is represented in xml format as follows: <comments> <comment message="”jaxer" name="”nigel"...
Archived open Web documentation - Archive of obsolete content
talk:array.foreach() ok, in the end i didn't remove the old code as it isn't hosted anywhere (i thought the github reference contained the code) but inserted a faster implementation above while retaining the rest of the document.
Audio for Web games - Game development
tracksource.connect(audioctx.destination) if (offset == 0) { tracksource.start(); offset = audioctx.currenttime; } else { tracksource.start(0, audioctx.currenttime - offset); } return tracksource; } finally, let's loop over our <li> elements, grab the correct file for each one and then allow playback by hiding the "loading" text and displaying the play button: trackels.foreach((el, i) => { // get children const anchor = el.queryselector('a'); const loadtext = el.queryselector('p'); const playbutton = el.queryselector('button'); // load file loadfile(anchor.href).then((track) => { // set loading to false el.dataset.loading = 'false'; // hide loading text loadtext.style.display = 'none'; // show button playbutton.style.display = '...
Choosing the right approach - Learn web development
for example: remotedb.alldocs({ include_docs: true, attachments: true }).then(function (result) { let docs = result.rows; docs.foreach(function(element) { localdb.put(element.doc).then(function(response) { alert("pulled doc with id " + element.doc._id + " and added to local db."); }).catch(function (err) { if (err.name == 'conflict') { localdb.get(element.doc._id).then(function (resp) { localdb.remove(resp._id, resp._rev).then(function (resp) { // et cetera...
Graceful asynchronous programming with Promises - Learn web development
the code that the video chat application would use might look something like this: function handlecallbutton(evt) { setstatusmessage("calling..."); navigator.mediadevices.getusermedia({video: true, audio: true}) .then(chatstream => { selfviewelem.srcobject = chatstream; chatstream.gettracks().foreach(track => mypeerconnection.addtrack(track, chatstream)); setstatusmessage("connected"); }).catch(err => { setstatusmessage("failed to connect"); }); } this function starts by using a function called setstatusmessage() to update a status display with the message "calling...", indicating that a call is being attempted.
Introduction to events - Learn web development
with javascript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this: const buttons = document.queryselectorall('button'); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = bgchange; } note that another option here would be to use the foreach() built-in method available on nodelist objects: buttons.foreach(function(button) { button.onclick = bgchange; }); note: separating your programming logic from your content also makes your site more friendly to search engines.
Ember interactivity: Events, classes and state - Learn web development
to put this in action, go to your todo-list.hbs component, and replace the static component calls: <todo /> <todo /> with a dynamic #each block (which is basically syntactic sugar over the top of javascript's foreach()) that creates a <todo /> component for each todo available in the list of todos returned by the service’s all() getter: {{#each this.todos.all as |todo|}} <todo @todo={{todo}} /> {{/each}} another way to look at this: this — the rendering context / component instance.
Introduction to client-side frameworks - Learn web development
the code that will render our items on the page might read something like this: function rendertodolist() { const frag = document.createdocumentfragment(); state.tasks.foreach(task => { const item = buildtodoitemel(task.id, task.name); frag.appendchild(item); }); while (todolistel.firstchild) { todolistel.removechild(todolistel.firstchild); } todolistel.appendchild(frag); } we've now got well over thirty lines of code dedicated just to the ui – just to the step of rendering something in the dom – and at no point do we add classes that we could...
Working with Svelte stores - Learn web development
add handler to the array of subscribers handler(value) // call handler with current value return () => subs = subs.filter(sub => sub !== handler) // return unsubscribe function } const set = (new_value) => { if (value === new_value) return // same value, exit value = new_value // update value subs.foreach(sub => sub(value)) // update subscribers } const update = (update_fn) => set(update_fn(value)) // update function return { subscribe, set, update } // store contract } here we declare subs, which is an array of subscribers.
Examples
cesful and reason was = "' + asuccessreason + '"'); }, function(arejectreason) { alert('mypromise failed for reason = "' + uneval(arejectreason) + '"'); } ); function myuserdefinedpromise() { try { var mysubpromises = []; var imagepaths = ['http://www.mozilla.org/media/img/firefox/favicon.png', 'https://developer.cdn.mozilla.net/media/redesign/img/favicon32.png']; [].foreach.call(imagepaths, function(path) { let myimage = new image(); let loadthisimagepromise = promise.defer(); mysubpromises.push(loadthisimagepromise.promise); myimage.onload = function() { loadthisimagepromise.resolve('succesfully loaded image at path = "' + path + '" the width of this image is = "' + this.naturalwidth + '".'); if (!this.naturalwidth) { ...
Self-hosted builtins in SpiderMonkey
example: js_self_hosted_fn("foreach", "arrayforeach", 1,0) this causes the self-hosted function arrayforeach to be installed as the host object's method foreach.
SpiderMonkey 45
::objecttocompletepropertydescriptor (bug 1144366) js_setimmutableprototype (bug 1211607) js_getownucpropertydescriptor (bug 1211607) js_hasownpropertybyid (bug 1211607) js_hasownproperty (bug 1211607) js_deleteucproperty (bug 1211607) js::newfunctionfromspec (bug 1054756) js::compilefornonsyntacticscope (bug 1165486) js_checkforinterrupt (bug 1058695) js::mapdelete (bug 1159469) js::mapforeach (bug 1159469) js::newsetobject (bug 1159469) js::setsize (bug 1159469) js::sethas (bug 1159469) js::setdelete (bug 1159469) js::setadd (bug 1159469) js::setclear (bug 1159469) js::setkeys (bug 1159469) js::setvalues (bug 1159469) js::setentries (bug 1159469) js::setforeach (bug 1159469) js::exceptionstackornull (bug 814497) js::copyasyncstack (bug 1160307) js::getsavedframesource (bu...
mozIStorageAggregateFunction
var standarddeviationfunc = { _numbers: [], onstep: function(aarguments) { this._numbers.push(aarguments.getint32(0)); }, onfinal: function() { let total = 0; let ilength = this._numbers.length; this._numbers.foreach(function(elt) { total += elt }); let mean = total / this._numbers.length; let data = this._numbers.map(function(elt) { let value = elt - mean; return value * value; }); total = 0; data.foreach(function(elt) { total += elt }); this._numbers = []; return math.sqrt(total / ilength); } }; // now, register our function with the database connection.
ExtensionManager (Toolkit)
examples here is how to retrive all the extensions installed: var em = cc['@mozilla.org/extensions/manager;1'] .getservice(ci.nsiextensionmanager); const nsiupdateitem = ci.nsiupdateitem; var extension_type = nsiupdateitem.type_extension; items = em.getitemlist(extension_type, {}); items.foreach(function(item, index, array) { alert(item.name + " / " + item.id + " version: " + item.version); }); ...
nsIXMLHttpRequest
case 'load': if (xhr.status == 200) { cb(xhr.response); break; } default: services.prompt.alert(null, 'xhr error', 'error fetching package: ' + xhr.statustext + ' [' + ev.type + ':' + xhr.status + ']'); break; } }; let evf = f => ['load', 'error', 'abort'].foreach(f); evf(m => xhr.addeventlistener(m, handler, false)); xhr.mozbackgroundrequest = true; xhr.open('get', url, true); xhr.channel.loadflags |= ci.nsirequest.load_anonymous | ci.nsirequest.load_bypass_cache | ci.nsirequest.inhibit_persistent_caching; xhr.responsetype = "arraybuffer"; //dont set it, so it returns string, you dont want arraybuffer.
Animation.finish() - Web APIs
WebAPIAnimationfinish
elem.getanimations().foreach( function(animation){ return animation.finish(); } ); specifications specification status comment web animationsthe definition of 'finish()' in that specification.
AudioParamDescriptor - Web APIs
// white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { static get parameterdescriptors () { return [{ name: 'customgain', defaultvalue: 1, minvalue: 0, maxvalue: 1, automationrate: 'a-rate' }] } process (inputs, outputs, parameters) { const output = outputs[0] output.foreach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = (math.random() * 2 - 1) * (parameters['customgain'].length > 1 ?
AudioParamMap - Web APIs
foreach() ?
AudioTrack.label - Web APIs
WebAPIAudioTracklabel
function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "main-desc", "translation", "commentary" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return tracklist; } the resulting tracklist contains an array of audio tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label.
AudioTrack.language - Web APIs
function getavailablelanguages(el) { var tracklist = []; const wantedkinds = [ "main", "translation" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, language: track.language }); } }); return tracklist; } specifications specification status comment html living standardthe definition of 'audiotrack.language' in that specification.
AudioTrackList.onchange - Web APIs
var tracklist = document.queryselector("video").audiotracks; tracklist.onchange = function(event) { tracklist.foreach(function(track) { updatetrackenabledbutton(track.id, track.enabled); }); }; the updatetrackenabledbutton(), in this example, should be a function that finds a user interface control using the track's id (perhaps the app uses the track id as the control element's id) and the track's enabled flag to determine which state the control should be in now.
AudioWorkletNode.parameters - Web APIs
// white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { static get parameterdescriptors () { return [{ name: 'customgain', defaultvalue: 1, minvalue: 0, maxvalue: 1, automationrate: 'a-rate' }] } process (inputs, outputs, parameters) { const output = outputs[0] output.foreach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = (math.random() * 2 - 1) * (parameters['customgain'].length > 1 ?
AudioWorkletNode - Web APIs
// white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { const output = outputs[0] output.foreach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = math.random() * 2 - 1 } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode passing it the name of the processor, and connect the node to an audio graph.
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
// white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { static get parameterdescriptors () { return [{ name: 'customgain', defaultvalue: 1, minvalue: 0, maxvalue: 1, automationrate: 'a-rate' }] } process (inputs, outputs, parameters) { const output = outputs[0] output.foreach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = (math.random() * 2 - 1) * (parameters['customgain'].length > 1 ?
AudioWorkletProcessor.process - Web APIs
class whitenoiseprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { // take the first output const output = outputs[0] // fill each channel with random values multiplied by gain output.foreach(channel => { for (let i = 0; i < channel.length; i++) { // generate random value for each sample // math.random range is [0; 1); we need [-1; 1] // this won't include exact 1 but is fine for now for simplicity channel[i] = (math.random() * 2 - 1) * // the array can contain 1 or 128 values // depending on if the automation is present ...
AudioWorkletProcessor - Web APIs
// white-noise-processor.js class whitenoiseprocessor extends audioworkletprocessor { process (inputs, outputs, parameters) { const output = outputs[0] output.foreach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = math.random() * 2 - 1 } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode, passing it the name of the processor, then connect the node to an audio graph.
CSSStyleSheet.cssRules - Web APIs
idual rules within the stylesheet can then be accessed by index: let rulelist = document.stylesheets[0].cssrules; for (let i=0; i < rulelist.length; i++) { processrule(rulelist[i]); } rules can also be accessed using for...of: let rulelist = document.stylesheets[0].cssrules; for (let rule of rulelist) { processrule(rule); } however, because cssrule is not a proper array, you can't use foreach().
CSSUnparsedValue - Web APIs
cssunparsedvalue.foreach() executes a provided function once for each element of the cssunparsedvalue object.
CSS Typed Object Model API - Web APIs
cssunparsedvalue.foreach() method executing a provided function once for each element of the cssunparsedvalue.
Cache.keys() - Web APIs
WebAPICachekeys
examples caches.open('v1').then(function(cache) { cache.keys().then(function(keys) { keys.foreach(function(request, index, array) { cache.delete(request); }); }); }) specifications specification status comment service workersthe definition of 'cache: keys' in that specification.
Cache.matchAll() - Web APIs
WebAPICachematchAll
examples caches.open('v1').then(function(cache) { cache.matchall('/images/').then(function(response) { response.foreach(function(element, index, array) { cache.delete(element); }); }); }) specifications specification status comment service workersthe definition of 'cache: matchall' in that specification.
CanvasRenderingContext2D.textBaseline - Web APIs
html <canvas id="canvas" width="550" height="500"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const baselines = ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom']; ctx.font = '36px serif'; ctx.strokestyle = 'red'; baselines.foreach(function (baseline, index) { ctx.textbaseline = baseline; const y = 75 + index * 75; ctx.beginpath(); ctx.moveto(0, y + 0.5); ctx.lineto(550, y + 0.5); ctx.stroke(); ctx.filltext('abcdefghijklmnop (' + baseline + ')', 0, y); }); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.textbaselin...
ChildNode.after() - Web APIs
WebAPIChildNodeafter
with(node) { after("foo"); } // referenceerror: after is not defined polyfill you can polyfill the after() method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/after()/after().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('after')) { return; } object.defineproperty(item, 'after', { configurable: true, enumerable: true, writable: true, value: function after() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var ...
ChildNode.before() - Web APIs
WebAPIChildNodebefore
with(node) { before("foo"); } // referenceerror: before is not defined polyfill you can polyfill the before() method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/before()/before().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('before')) { return; } object.defineproperty(item, 'before', { configurable: true, enumerable: true, writable: true, value: function before() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { v...
ChildNode.remove() - Web APIs
WebAPIChildNoderemove
with(node) { remove(); } // referenceerror: remove is not defined polyfill you can polyfill the remove() method in internet explorer 9 and higher with the following code: // from:https://github.com/jserz/js_piece/blob/master/dom/childnode/remove()/remove().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('remove')) { return; } object.defineproperty(item, 'remove', { configurable: true, enumerable: true, writable: true, value: function remove() { this.parentnode.removechild(this); } }); }); })([element.prototype, characterdata.prototype, documenttype.prototype]); specifications specif...
DOMTokenList - Web APIs
domtokenlist.foreach(callback [, thisarg]) executes a provided callback function once per domtokenlist element.
DataTransferItem.webkitGetAsEntry() - Web APIs
isting"); function scanfiles(item, container) { let elem = document.createelement("li"); elem.innerhtml = item.name; container.appendchild(elem); if (item.isdirectory) { let directoryreader = item.createreader(); let directorycontainer = document.createelement("ul"); container.appendchild(directorycontainer); directoryreader.readentries(function(entries) { entries.foreach(function(entry) { scanfiles(entry, directorycontainer); }); }); } } scanfiles() begins by creating a new <li> element to represent the item being scanned, inserts the name of the item into it as its text content, and then appends it to the container.
DirectoryReaderSync - Web APIs
window.resolvelocalfilesystemurl = window.resolvelocalfilesystemurl || window.webkitresolvelocalfilesystemurl; // create web workers var worker = new worker('worker.js'); worker.onmessage = function(e) { var urls = e.data.entries; urls.foreach(function(url, i) { window.resolvelocalfilesystemurl(url, function(fileentry) { // print out file's name.
Document.adoptNode() - Web APIs
example const iframe = document.queryselector('iframe'); const iframeimages = iframe.contentdocument.queryselectorall('img'); const newparent = document.getelementbyid('images'); iframeimages.foreach(function(imgel) { newparent.appendchild(document.adoptnode(imgel)); }); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode().
Document.createDocumentFragment() - Web APIs
html <ul id="ul"> </ul> javascript var element = document.getelementbyid('ul'); // assuming ul exists var fragment = document.createdocumentfragment(); var browsers = ['firefox', 'chrome', 'opera', 'safari', 'internet explorer']; browsers.foreach(function(browser) { var li = document.createelement('li'); li.textcontent = browser; fragment.appendchild(li); }); element.appendchild(fragment); result specifications specification status comment domthe definition of 'document.createdocumentfragment()' in that specification.
Document.getAnimations() - Web APIs
document.getanimations().foreach( function (animation) { animation.playbackrate *= .5; } ); specifications specification status comment web animationsthe definition of 'document.getanimations()' in that specification.
Document.querySelectorAll() - Web APIs
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.
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 'documentfragment' in that specification.
DocumentTimeline.DocumentTimeline() - Web APIs
this bit of code would start all the cats animating 500 milliseconds into their animations: var cats = document.queryselectorall('.sharedtimelinecat'); cats = array.prototype.slice.call(cats); var sharedtimeline = new documenttimeline({ origintime: 500 }); cats.foreach(function(cat) { var catkeyframes = new keyframeeffect(cat, keyframes, timing); var catanimation = new animation(catkeyframes, sharedtimeline); catanimation.play(); }); specifications specification status comment web animationsthe definition of 'documenttimeline()' in that specification.
EffectTiming.delay - Web APIs
examples in the pool of tears example, each tear is passed a random delay via its timing object: // randomizer function var getrandommsrange = function(min, max) { return math.random() * (max - min) + min; } // loop through each tear tears.foreach(function(el) { // animate each tear el.animate( tearsfalling, { delay: getrandommsrange(-1000, 1000), // randomized for each tear duration: getrandommsrange(2000, 6000), // randomized for each tear iterations: infinity, easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)" }); }); specifications specification status comment web animat...
EffectTiming.duration - Web APIs
examples in the pool of tears example, each tear is passed a random duration via its timing object: // randomizer function var getrandommsrange = function(min, max) { return math.random() * (max - min) + min; } // loop through each tear tears.foreach(function(el) { // animate each tear el.animate( tearsfalling, { delay: getrandommsrange(-1000, 1000), // randomized for each tear duration: getrandommsrange(2000, 6000), // randomized for each tear iterations: infinity, easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)" }); }); specifications specification status comment web anim...
Element.classList - Web APIs
WebAPIElementclassList
"replace", newtoken); var oldvalue = this.value; return (this.remove(oldtoken), this.value !== oldvalue && (this.add(newtoken), true)); }; if (!domtokenlistproto.contains) domtokenlistproto.contains = function(value){ for (var i=0,len=this.length; i !== len; ++i) if (this[i] === value) return true; return false; }; if (!domtokenlistproto.foreach) domtokenlistproto.foreach = function(f){ if (arguments.length === 1) for (var i = 0, len = this.length; i !== len; ++i) f( this[i], i, this); else for (var i=0,len=this.length,targ=arguments[1]; i !== len; ++i) f.call(targ, this[i], i, this); }; if (!domtokenlistproto.entries) domtokenlistproto.entries = function(){ var nextindex = 0, that = this; return {...
Element.part - Web APIs
WebAPIElementpart
let tabs = []; let children = this.shadowroot.children; for(let elem of children) { if(elem.getattribute('part')) { tabs.push(elem); } } tabs.foreach((tab) => { tab.addeventlistener('click', (e) => { tabs.foreach((tab) => { tab.part = 'tab'; }) e.target.part = 'tab active'; }) console.log(tab.part); }) specifications specification status comment shadow partsthe definition of 'element.part' in that specification.
Element.querySelectorAll() - Web APIs
you can use any common looping statement, such as: var highlighteditems = userlist.queryselectorall(".highlighted"); highlighteditems.foreach(function(useritem) { deleteuser(useritem); }); note: nodelist is not a genuine array, that is to say it doesn't have the array methods like slice, some, map etc.
Element.shadowRoot - Web APIs
from here we use standard dom traversal techniques to find the <style> element inside the shadow dom and then update the css found inside it: function updatestyle(elem) { const shadow = elem.shadowroot; const childnodes = array.from(shadow.childnodes); childnodes.foreach(childnode => { if (childnode.nodename === 'style') { childnode.textcontent = ` div { width: ${elem.getattribute('l')}px; height: ${elem.getattribute('l')}px; background-color: ${elem.getattribute('c')}; } `; } }); } specifications specification status comment domthe definition of 'shadowroot' in that spe...
FileReader.readAsDataURL() - Web APIs
riteria 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); } } note: the filereader() constructor was not supported by internet explorer for versions before 10.
FileSystemDirectoryReader.readEntries() - Web APIs
isting"); function scanfiles(item, container) { let elem = document.createelement("li"); elem.innerhtml = item.name; container.appendchild(elem); if (item.isdirectory) { let directoryreader = item.createreader(); let directorycontainer = document.createelement("ul"); container.appendchild(directorycontainer); directoryreader.readentries(function(entries) { entries.foreach(function(entry) { scanfiles(entry, directorycontainer); }); }); } } scanfiles() begins by creating a new <li> element to represent the item being scanned, inserts the name of the item into it as its text content, and then appends it to the container.
GlobalEventHandlers.onmousemove - Web APIs
ode); 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.tooltip; node.removeattribute('hidden'); }; this.hide = function() { node.setattribute('hidden', ''); }; })(); const links = document.queryselectorall('a'); links.foreach(link => { link.onmouseover = tooltip.show; link.onmousemove = tooltip.follow; link.onmouseout = tooltip.hide; }); result draggable elements we also have an example available showing the use of the onmousemove event handler with draggable objects — view the example in action.
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 event' in that specification.
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.
Option() - Web APIs
examples just add new options /* assuming we have the following html <select id='s'> </select> */ var s = document.getelementbyid('s'); var options = [four, five, six]; options.foreach(function(element,key) { s[key] = new option(element,key); }); append options with different parameters /* assuming we have the following html <select id="s"> <option>first</option> <option>second</option> <option>third</option> </select> */ var s = document.getelementbyid('s'); var options = [ 'zero', 'one', 'two' ]; options.foreach(function(element, key) { if (element == '...
HTMLTableRowElement.rowIndex - Web APIs
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 ...
Drag Operations - Web APIs
function dodrop(event) { const lines = event.datatransfer.getdata("text/uri-list").split("\n"); lines.filter(line => !line.startswith("#")) .foreach(line => { const link = document.createelement("a"); link.href = line; link.textcontent = line; event.target.appendchild(link); }) event.preventdefault(); } this example inserts a link from the dragged data.
Headers - Web APIs
WebAPIHeaders
headers.foreach() executes a provided function once for each array element.
IntersectionObserverEntry.intersectionRatio - Web APIs
function intersectioncallback(entries) { entries.foreach(function(entry) { entry.target.style.opacity = entry.intersectionratio; }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api.
IntersectionObserverEntry.intersectionRect - Web APIs
function intersectioncallback(entries) { entries.foreach(function(entry) { refreshzones.push({ element: entry.target, rect: entry.intersectionrect }); }); } specifications specification status comment intersection observerthe definition of 'intersectionobserverentry.intersectionrect' in that specification.
IntersectionObserverEntry.isIntersecting - Web APIs
function intersectioncallback(entries) { entries.foreach(function(entry) { if (entry.isintersecting) { intersectingcount += 1; } else { intersectingcount -= 1; } }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api.
IntersectionObserverEntry.target - Web APIs
function intersectioncallback(entries) { entries.foreach(function(entry) { entry.target.opacity = entry.intersectionratio; }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api.
KeyboardLayoutMap - Web APIs
methods keyboardlayoutmap.foreach() read only executes a provided function once for each element of keyboardlayoutmap.
Location - Web APIs
WebAPILocation
e; 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.stoppropagation(); win...
MIDIMessageEvent - Web APIs
examples // printing all messages to console navigator.requestmidiaccess().then(midiaccess => { array.from(midiaccess.inputs).foreach(input => { input[1].onmidimessage = console.log; }) }); specifications specification status comment web midi apithe definition of 'midimessageevent' in that specification.
MediaDeviceInfo - Web APIs
navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { console.log(device.kind + ": " + device.label + " id = " + device.deviceid); }); }) .catch(function(err) { console.log(err.name + ": " + err.message); }); this might produce: videoinput: id = cso9c0ypaf274oucpua53cne0yhlir2yxci+sqfbzz8= audioinput: id = rkxxbyjnabbadgqnnzqlvldmxls0yketycibg+xxnvm= audioinput: id = r2/xw1xupiyzunfv1lgrkoma5wtovckwfz368...
MediaDevices.enumerateDevices() - Web APIs
navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { console.log(device.kind + ": " + device.label + " id = " + device.deviceid); }); }) .catch(function(err) { console.log(err.name + ": " + err.message); }); this might produce: videoinput: id = cso9c0ypaf274oucpua53cne0yhlir2yxci+sqfbzz8= audioinput: id = rkxxbyjnabbadgqnnzqlvldmxls0yketycibg+xxnvm= audioinput: id = r2/xw1xupiyzunfv1lgrkoma5wtovckwfz368...
MediaKeyStatusMap - Web APIs
mediakeystatusmap.foreach(callback[, argument]) read only calls callback once for each key-value pair in the status map, in insertion order.
MediaStreamTrack.muted - Web APIs
let mutedcount = 0; tracklist.foreach((track) => { if (track.muted) { mutedcount += 1; } }); specifications specification status comment media capture and streamsthe definition of 'muted' in that specification.
Recording a media element - Web APIs
stopping the input stream the stop() function simply stops the input media: function stop(stream) { stream.gettracks().foreach(track => track.stop()); } this works by calling mediastream.gettracks(), using foreach() to call mediastreamtrack.stop() on each track in the stream.
MediaStream Recording API - Web APIs
navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { let menu = document.getelementbyid("inputdevices"); if (device.kind == "audioinput") { let item = document.createelement("option"); item.innerhtml = device.label; item.value = device.deviceid; menu.appendchild(item); } }); }); code similar to this can be used to let the user restrict the set of devices they wish to use.
MutationObserver.MutationObserver() - Web APIs
the callback function function callback(mutationlist, observer) { mutationlist.foreach( (mutation) => { switch(mutation.type) { case 'childlist': /* one or more children have been added to and/or removed from the tree.
MutationObserverInit.attributeFilter - Web APIs
function callback(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": switch(mutation.attributename) { case "status": userstatuschanged(mutation.target.username, mutation.target.status); break; case "username": usernamechanged(mutation.oldvalue, mutation.target.username); break; } break; } }); } ...
MutationObserverInit.attributeOldValue - Web APIs
function callback(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": notifyuser("attribute name " + mutation.attributename + " changed to " + mutation.target[mutation.attributename] + " (was " + mutation.oldvalue + ")"); break; } }); } var targetnode = document.queryselector("#target"); var observer = new mutationobserver(callback); observer.ob...
MutationObserverInit.attributes - Web APIs
function callback(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": notifyuser("attribute name " + mutation.attributename + " changed to " + mutation.target[mutation.attributename] + " (was " + mutation.oldvalue + ")"); break; } }); } var targetnode = document.queryselector("#target"); var observer = new mutationobserver(callback); observer.ob...
NonDocumentTypeChildNode.nextElementSibling - Web APIs
xtelementsibling", { get: function(){ var e = this.nextsibling; while(e && 1 !== e.nodetype) e = e.nextsibling; return e; } }); } polyfill for internet explorer 9+ and safari // source: https://github.com/jserz/js_piece/blob/master/dom/nondocumenttypechildnode/nextelementsibling/nextelementsibling.md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('nextelementsibling')) { return; } object.defineproperty(item, 'nextelementsibling', { configurable: true, enumerable: true, get: function () { var el = this; while (el = el.nextsibling) { if (el.nodetype === 1) { return el; } } return null; }, ...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
t.prototype, "previouselementsibling", { get: function(){ var e = this.previoussibling; while(e && 1 !== e.nodetype) e = e.previoussibling; return e; } }); } polyfill for internet explorer 9+ and safari // source: https://github.com/jserz/js_piece/blob/master/dom/nondocumenttypechildnode/previouselementsibling/previouselementsibling.md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('previouselementsibling')) { return; } object.defineproperty(item, 'previouselementsibling', { configurable: true, enumerable: true, get: function () { let el = this; while (el = el.previoussibling) { if (el.nodetype === 1) { return el; } } return null; ...
ParentNode.append() - Web APIs
WebAPIParentNodeappend
let parent = document.createelement("div") with(parent) { append("foo") } // referenceerror: append is not defined polyfill you can polyfill the append() method in internet explorer 9 and higher with the following code: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/append()/append().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('append')) { return; } object.defineproperty(item, 'append', { configurable: true, enumerable: true, writable: true, value: function append() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { v...
ParentNode.prepend() - Web APIs
var parent = document.createelement("div"); with(parent) { prepend("foo"); } // referenceerror: prepend is not defined polyfill you can polyfill the prepend() method if it's not available: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/prepend()/prepend().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('prepend')) { return; } object.defineproperty(item, 'prepend', { configurable: true, enumerable: true, writable: true, value: function prepend() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { ...
PerformancePaintTiming - Web APIs
example function showpainttimings() { if (window.performance) { let performance = window.performance; let performanceentries = performance.getentriesbytype('paint'); performanceentries.foreach( (performanceentry, i, entries) => { console.log("the time to " + performanceentry.name + " was " + performanceentry.starttime + " milliseconds."); }); } else { console.log('performance timing isn\'t supported.'); } } the code above produces console output something like the following: the time to first-paint was 2785.915 milliseconds.
RTCDataChannel.binaryType - Web APIs
var dc = peerconnection.createdatachannel("binary"); dc.binarytype = "arraybuffer"; dc.onmessage = function(event) { let bytearray = new uint8array(event.data); let hexstring = ""; bytearray.foreach(function(byte) { hexstring += byte.tostring(16) + " "; }); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.binarytype' in that specification.
RTCDataChannel.readyState - Web APIs
example var datachannel = peerconnection.createdatachannel("file transfer"); var sendqueue = []; function sendmessage(msg) { switch(datachannel.readystate) { case "connecting": console.log("connection not open; queueing: " + msg); sendqueue.push(msg); break; case "open": sendqueue.foreach((msg) => datachannel.send(msg)); break; case "closing": console.log("attempted to send message while closing: " + msg); break; case "closed": console.log("error!
RTCDtlsTransport.state - Web APIs
*/ function tallysenders(pc) { let results = { transportmissing: 0, connectionpending: 0, connected: 0, closed: 0, failed: 0, unknown: 0 }; let senderlist = pc.getsenders(); senderlist.foreach(sender => { let transport = sender.transport; if (!transport) { results.transportmissing++; } else { switch(transport.state) { case "new": case "connecting": results.connectionpending++; break; case "connected": results.connected++; break; case "closed": results.closed++; break; ...
RTCDtlsTransport - Web APIs
*/ function tallysenders(pc) { let results = { transportmissing: 0, connectionpending: 0, connected: 0, closed: 0, failed: 0, unknown: 0 }; let senderlist = pc.getsenders(); senderlist.foreach(sender => { let transport = sender.transport; if (!transport) { results.transportmissing++; } else { switch(transport.state) { case "new": case "connecting": results.connectionpending++; break; case "connected": results.connected++; break; case "closed": results.closed++; break; ...
RTCIceCandidate.usernameFragment - Web APIs
to avoid including candidates obsoleted by an ice restart, we can use code like this: const ssnewcandidate = signalmsg => { let candidate = new rtcicecandidate(signalmsg.candidate); let receivers = pc.getreceivers(); receivers.foreach(receiver => { let parameters = receiver.transport.getparameters(); if (parameters.usernamefragment === candidate.usernamefragment) { return; } }); pc.addicecandidate(candidate) .catch(reporterror); } this walks through the list of the rtcrtpreceiver objects being used to receive ice data, and looks to see if the usernamefragment indicated in the candidate matches any...
RTCIceCandidatePairStats.selected - Web APIs
function getcurrentcandidatepair(statsresults) { statsresults.foreach(report => { if (report.type === "transport") { currentpair = statsresults.get(report.selectedcandidatepairid); } }); if (!currentpair) { statsresults.foreach(report => { if (report.type === "candidate-pair" && report.selected) { currentpair = report; } }); } return currentpair; } specifications not part of any specification.
RTCIceTransport: gatheringstatechange event - Web APIs
here, the addeventlistener() method is called to add a listener for gatheringstatechange events: pc.getsenders().foreach(sender => { sender.transport.icetransport.addeventlistener("gatheringstatechange", ev => { let transport = ev.target; if (transport.gatheringstate === "complete") { /* this transport has finished gathering candidates, but others may still be working on it */ } }, false); likewise, you can use the ongatheringstatechange event handler property: pc.getsenders().foreach(sender =...
RTCIceTransport.getLocalCandidates() - Web APIs
var localcandidates = pc.getsenders()[0].transport.transport.getlocalcandidates(); localcandidates.foreach(function(candidate, index)) { console.log("candidate " + index + ": " + candidate.candidate); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.getlocalcandidates()' in that specification.
RTCIceTransport.getRemoteCandidates() - Web APIs
var remotecandidates = pc.getsenders()[0].transport.transport.getremotecandidates(); remotecandidates.foreach(function(candidate, index)) { console.log("candidate " + index + ": " + candidate.candidate); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.getremotecandidates()' in that specification.
RTCPeerConnection.addStream() - Web APIs
navigator.mediadevices.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); pc.addstream(stream); }); migrating to addtrack() compatibility allowing, you should update your code to instead use the addtrack() method: navigator.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); stream.gettracks().foreach(function(track) { pc.addtrack(track, stream); }); }); the newer addtrack() api avoids confusion over whether later changes to the track-makeup of a stream affects a peer connection (they do not).
RTCPeerConnection.addTrack() - Web APIs
var mediaconstraints = { audio: true, // we want an audio track video: true // ...and we want a video track }; var desc = new rtcsessiondescription(sdp); pc.setremotedescription(desc).then(function () { return navigator.mediadevices.getusermedia(mediaconstraints); }) .then(function(stream) { previewelement.srcobject = stream; stream.gettracks().foreach(track => pc.addtrack(track, stream)); }) this code takes sdp which has been received from the remote peer and constructs a new rtcsessiondescription to pass into setremotedescription().
RTCPeerConnection: addstream event - Web APIs
if (pc.addtrack !== undefined) { pc.ontrack = ev => { ev.streams.foreach(stream => doaddstream(stream)); } } else { pc.onaddstream = ev => { doaddstream(ev.stream); } } this calls a function doaddstream() once for each stream being added to the rtcpeerconnection, regardless of whether the browser sends addstream or track.
RTCPeerConnection.getSenders() - Web APIs
function setmuting(pc, muting) { let senderlist = pc.getsenders(); senderlist.foreach(sender) { sender.track.enabled = !muting; } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.getsenders()' in that specification.
RTCPeerConnection.getStats() - Web APIs
window.setinterval(function() { mypeerconnection.getstats(null).then(stats => { let statsoutput = ""; stats.foreach(report => { statsoutput += `<h2>report: ${report.type}</h3>\n<strong>id:</strong> ${report.id}<br>\n` + `<strong>timestamp:</strong> ${report.timestamp}<br>\n`; // now the statistics for this report; we intentially drop the ones we // sorted to the top above object.keys(report).foreach(statname => { if (statname !== "id" && statname !== "time...
RTCPeerConnection.getTransceivers() - Web APIs
pc.gettransceivers().foreach(transceiver => { transceiver.stop(); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.gettransceivers()' in that specification.
RTCRtpReceiver.getCapabilities() static function - Web APIs
function canreceiveh264() { let capabilities = rtcrtpreceiver.getcapabilities("video"); capabilities.codecs.foreach((codec) => { if (codec.mimetype === "video/h264") { return true; } }); return false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiver.getcapabilities()' in that specification.
RTCRtpSender.getCapabilities() static function - Web APIs
function cansendh264() { let capabilities = rtcrtpsender.getcapabilities("video"); capabilities.codecs.foreach((codec) => { if (codec.mimetype === "video/h264") { return true; } }); return false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.getcapabilities()' in that specification.
RTCRtpSender.replaceTrack() - Web APIs
examples switching video cameras // example to change video camera, suppose selected value saved into window.selectedcamera navigator.mediadevices .getusermedia({ video: { deviceid: { exact: window.selectedcamera } } }) .then(function(stream) { let videotrack = stream.getvideotracks()[0]; pcs.foreach(function(pc) { var sender = pc.getsenders().find(function(s) { return s.track.kind == videotrack.kind; }); console.log('found sender:', sender); sender.replacetrack(videotrack); }); }) .catch(function(err) { console.error('error happens:', err); }); specifications specification status comment webrtc 1.0: real-time communicat...
RTCRtpSender.setStreams() - Web APIs
function addtrackstostream(stream) { let senders = pc.getsenders(); senders.foreach((sender) => { if (sender.track && (sender.transport.state === connected)) { sender.setstreams(stream); } }); } after calling the rtcpeerconnection method getsenders() to get the list of the connection's senders, the addtrackstostream() function iterates over the list.
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.
Using the Screen Capture API - Web APIs
function stopcapture(evt) { let tracks = videoelem.srcobject.gettracks(); tracks.foreach(track => track.stop()); videoelem.srcobject = null; } dumping configuration information for informational purposes, the startcapture() method shown above calls a method named dumpoptions(), which outputs the current track settings as well as the constraints that were placed upon the stream when it was created.
ServiceWorkerGlobalScope: activate event - Web APIs
globalscope.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { return caches.delete(cachename); } }) ); }); you can also set up the event handler using the serviceworkerglobalscope.onactivate property: globalscope.onactivate = function(event) { ...
ServiceWorkerGlobalScope.onactivate - Web APIs
then.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { return caches.delete(cachename); } }) ); }); specifications specification status comment service workersthe definition of 'event handlers' in that specification.
SourceBufferList - Web APIs
[]) or functions such as foreach() for example.
Storage.key() - Web APIs
WebAPIStoragekey
examples the following function iterates over the local storage keys: function foreachkey(callback) { for (var i = 0; i < localstorage.length; i++) { callback(localstorage.key(i)); } } the following function iterates over the local storage keys and gets the value set for each key: for(var i =0; i < localstorage.length; i++){ console.log(localstorage.getitem(localstorage.key(i))); } note: for a real world example, see our web storage demo.
StylePropertyMapReadOnly - Web APIs
stylepropertymapreadonly.foreach() executes a provided function once for each element of stylepropertymapreadonly.
TextMetrics - Web APIs
['fontboundingboxascent', 'actualboundingboxascent', 'emheightascent', 'hangingbaseline']; const baselinesbelowalphabetic = ['ideographicbaseline', 'emheightdescent', 'actualboundingboxdescent', 'fontboundingboxdescent']; const baselines = [...baselinesabovealphabetic, ...baselinesbelowalphabetic]; ctx.font = '25px serif'; ctx.strokestyle = 'red'; baselines.foreach(function (baseline, index) { let text = 'abcdefghijklmnop (' + baseline + ')'; let textmetrics = ctx.measuretext(text); let y = 50 + index * 50; ctx.beginpath(); ctx.filltext(text, 0, y); let liney = y - math.abs(textmetrics[baseline]); if (baselinesbelowalphabetic.includes(baseline)) { liney = y + math.abs(textmetrics[baseline]); } ctx.moveto(0, liney); ctx.lineto(550, li...
TextTrackList - Web APIs
the individual tracks can be accessed using array syntax or functions such as foreach() for example.
URLSearchParams - Web APIs
urlsearchparams.foreach() allows iteration through all values contained in this object via a callback function.
USB.getDevices() - Web APIs
WebAPIUSBgetDevices
navigator.usb.getdevices() .then(devices => { console.log("total devices: " + devices.length); devices.foreach(device => { console.log("product name: " + device.productname + ", serial number " + device.serialnumber); }); }); specifications specification status comment webusbthe definition of 'getdevices' in that specification.
VideoTrack.label - Web APIs
WebAPIVideoTracklabel
function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "commentary" ]; el.videotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return tracklist; } the resulting tracklist contains an array of video tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label.
VideoTrack - Web APIs
usage notes to get a videotrack for a given media element, use the element's videotracks property, which returns a videotracklist object from which you can get the individual tracks contained in the media: var el = document.queryselector("video"); var tracks = el.videotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach().
VideoTrackList.onchange - Web APIs
var tracklist = document.queryselector("video").videotracks; tracklist.onchange = function(event) { tracklist.foreach(function(track) { updatetrackselectedbutton(track.id, track.selected); }); }; the updatetrackselectedbutton(), in this example, should be a function that finds a user interface control using the track's id (perhaps the app uses the track id as the control element's id) and the track's selected flag to determine which state the control should be in now.
VideoTrackList - Web APIs
the individual tracks can be accessed using array syntax or functions such as foreach() for example.
WebGLRenderingContext - Web APIs
80px; margin : auto; padding : 0; border : none; background-color : black; } window.addeventlistener("load", function() { "use strict" var firstcanvas = document.getelementsbytagname("canvas")[0], secondcanvas = document.getelementsbytagname("canvas")[1]; firstcanvas.width = firstcanvas.clientwidth; firstcanvas.height = firstcanvas.clientheight; [firstcanvas, secondcanvas].foreach(function(canvas) { var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { document.queryselector("p").innerhtml = "failed to get webgl context.
A basic 2D WebGL animation example - Web APIs
function buildshaderprogram(shaderinfo) { let program = gl.createprogram(); shaderinfo.foreach(function(desc) { let shader = compileshader(desc.id, desc.type); if (shader) { gl.attachshader(program, shader); } }); gl.linkprogram(program) if (!gl.getprogramparameter(program, gl.link_status)) { console.log("error linking shader program:"); console.log(gl.getprograminfolog(program)); } return program; } first, gl.createprogram() is called to create a n...
Canvas size and WebGL - Web APIs
80px; margin : auto; padding : 0; border : none; background-color : black; } window.addeventlistener("load", function() { "use strict" var firstcanvas = document.getelementsbytagname("canvas")[0], secondcanvas = document.getelementsbytagname("canvas")[1]; firstcanvas.width = firstcanvas.clientwidth; firstcanvas.height = firstcanvas.clientheight; [firstcanvas, secondcanvas].foreach(function(canvas) { var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { document.queryselector("p").innerhtml = "failed to get webgl context.
WebRTC Statistics API - Web APIs
try { mypeerconnection = new rtcpeerconnection(pcoptions); statsinterval = window.setinterval(getconnectionstats, 1000); /* add event handlers, etc */ } catch(err) { console.error("error creating rtcpeerconnection: " + err); } function getconnectionstats() { mypeerconnection.getstats(null).then(stats => { var statsoutput = ""; stats.foreach(report => { if (report.type === "inbound-rtp" && report.kind === "video") { object.keys(report).foreach(statname => { statsoutput += `<strong>${statname}:</strong> ${report[statname]}<br>\n`; }); } }); document.queryselector(".stats-box").innerhtml = statsoutput; }); } when the promise returned by getstats() is fulfilled, the resolution handler re...
Inputs and input sources - Web APIs
for example, if you need to keep up with which controller is held in each of the player's hands, you might do something like this: let inputsourcelist = null; let lefthandsource = null; let righthandsource = null; xrsession.addeventlistener("inputsourceschange", event => { inputsourcelist = event.session.inputsources; inputsourcelist.foreach(source => { switch(source) { case "left": lefthandsource = source; break; case "right": righthandsource = source; break; } }); }); the inputsourceschange event is also fired once when the session's creation callback first completes execution, so you can use it to fetch the input source list as soon as it's available at startup time.
Using the Web Animations API - Web APIs
that’s impossible to do with css without recalculating durations in every css rule, but with the web animations api, we could use the document.getanimations() method to loop over each animation on the page and halve their playbackrates, like so: document.getanimations().foreach( function (animation) { animation.updateplaybackrate(animation.playbackrate * .5); } ); with the web animations api, all you need to change is just one little property!
Advanced techniques: Creating and sequencing audio - Web APIs
if (lastnotedrawn != drawnote) { pads.foreach(function(el, i) { el.children[lastnotedrawn].style.bordercolor = 'hsla(0, 0%, 10%, 1)'; el.children[drawnote].style.bordercolor = 'hsla(49, 99%, 50%, 1)'; }); lastnotedrawn = drawnote; } // set up to draw again requestanimationframe(draw); } putting it all together now all that's left to do is make sure we've loaded the sample before we are a...
Example and tutorial: Simple synth keyboard - Web APIs
notefreq.foreach(function(keys, idx) { let keylist = object.entries(keys); let octaveelem = document.createelement("div"); octaveelem.classname = "octave"; keylist.foreach(function(key) { if (key[0].length == 1) { octaveelem.appendchild(createkey(key[0], idx, key[1])); } }); keyboard.appendchild(octaveelem); }); document.queryselector("div[data-note='b'][data-oct...
Web audio spatialization basics - Web APIs
|| {}; move.frameid = requestanimationframe(() => moveboombox(direction, move)); return move; } wiring up our controls wiring up out control buttons is comparatively simple — now we can listen for a mouse event on our controls and run this function, as well as stop it when the mouse is released: // for each of our controls, move the boombox and change the position values movecontrols.foreach(function(el) { let moving; el.addeventlistener('mousedown', function() { let direction = this.dataset.control; if (moving && moving.frameid) { window.cancelanimationframe(moving.frameid); } moving = moveboombox(direction); }, false); window.addeventlistener('mouseup', function() { if (moving && moving.frameid) { w...
Web Audio API - Web APIs
audioparammap provides a maplike interface to a group of audioparam interfaces, which means it provides the methods foreach(), get(), has(), keys(), and values(), as well as a size property.
Window: pageshow event - Web APIs
"persisted" : "not persisted"; console.log('event:', event.type, '-', ispersisted); break; default: console.log('event:', event.type); break; } }; events.foreach(eventname => window.addeventlistener(eventname, eventlogger) ); html <p>open the console and watch the output as you navigate to and from this page.
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
there's also no option to pass a thisarg to settimeout as there is in array methods like foreach, reduce, etc.
WritableStreamDefaultWriter.ready - Web APIs
function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter var defaultwriter = writablestream.getwriter(); var encoder = new textencoder(); var encoded = encoder.encode(message, {stream: true}); encoded.foreach(function(chunk) { // make sure the stream and its writer are able to // receive data.
XMLHttpRequest.getAllResponseHeaders() - Web APIs
e); request.send(); request.onreadystatechange = function() { if(this.readystate == this.headers_received) { // get the raw header string var headers = request.getallresponseheaders(); // convert the header string into an array // of individual headers var arr = headers.trim().split(/[\r\n]+/); // create a map of header names to values var headermap = {}; arr.foreach(function (line) { var parts = line.split(': '); var header = parts.shift(); var value = parts.join(': '); headermap[header] = value; }); } } once this is done, you can, for example: var contenttype = headermap["content-type"]; this obtains the value of the content-type header into the variable contenttype.
XRInputSourceArray.entries() - Web APIs
specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like methods in information contained in a webidl file for information on how an iterable declaration in an interface definition causes entries(), foreach(), keys(), and values() methods to be exposed from objects that implement the interface.
XRInputSourceArray.keys() - Web APIs
specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like methods in information contained in a webidl file for information on how an iterable declaration in an interface definition causes entries(), foreach(), keys(), and values() methods to be exposed from objects that implement the interface.
XRInputSourceArray.values() - Web APIs
specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like methods in information contained in a webidl file for information on how an iterable declaration in an interface definition causes entries(), foreach(), keys(), and values() methods to be exposed from objects that implement the interface.
ARIA: switch role - Accessibility
document.queryselectorall(".switch").foreach(function(theswitch) { theswitch.addeventlistener("click", handleclickevent, false); }); function handleclickevent(evt) { let el = evt.target; if (el.getattribute("aria-checked") == "true") { el.setattribute("aria-checked", "false"); } else { el.setattribute("aria-checked", "true"); } } css the purpose of the css is to establish a look and feel for the switch that's remin...
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
WebCSS:is
matches(header, main, footer) p'); } catch(e) { try { matcheditems = document.queryselectorall(':-webkit-any(header, main, footer) p'); } catch(e) { try { matcheditems = document.queryselectorall(':-moz-any(header, main, footer) p'); } catch(e) { console.log('your browser doesn\'t support :is(), :matches(), or :any()'); } } } } matcheditems.foreach(applyhandler); function applyhandler(elem) { elem.addeventlistener('click', function(e) { alert('this paragraph is inside a ' + e.target.parentnode.nodename); }); } simplifying list selectors the :is() pseudo-class can greatly simplify your css selectors.
animation - CSS: Cascading Style Sheets
WebCSSanimation
'play' : 'pause'); anim.style.animationplaystate = ''; anim.classlist.add('a' + (i + 1)); }, 100) } } animation.foreach(function (node, index) { node.addeventlistener('animationstart', function () { togglebutton(button[index], 'pause'); }); node.addeventlistener('animationend', function () { togglebutton(button[index], 'restart'); }); }); button.foreach(function (btn, index) { btn.addeventlistener('click', function () { playpause(index); }); }); }) a description of which properties are a...
display - CSS: Cascading Style Sheets
WebCSSdisplay
acing: 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.
Mutation events - Developer guides
insertedintodocument domnoderemoved domnoderemovedfromdocument domsubtreemodified mutation observers alternatives examples domnoderemovedfromdocument var isdescendant = function (desc, root) { return !!desc && (desc === root || isdescendant(desc.parentnode, root)); }; var onremove = function (element, callback) { var observer = new mutationobserver(function (mutations) { _.foreach(mutations, function (mutation) { _.foreach(mutation.removednodes, function (removed) { if (isdescendant(element, removed)) { callback(); // allow garbage collection observer.disconnect(); observer = undefined; } }); }); }); observer.observe(docum...
<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 accessibility concerns breaking up content into paragraphs helps make a page more accessible.
A re-introduction to JavaScript (JS tutorial) - JavaScript
another way of iterating over an array that was added with ecmascript 5 is foreach(): ['dog', 'cat', 'hen'].foreach(function(currentvalue, index, array) { // do something with currentvalue or array[index] }); if you want to append an item to an array simply do it like this: a.push(item); arrays come with a number of methods.
Closures - JavaScript
another alternative could be to use foreach() to iterate over the helptext array and attach a listener to each <p>, as shown: function showhelp(help) { document.getelementbyid('help').innerhtml = help; } function setuphelp() { var helptext = [ {'id': 'email', 'help': 'your e-mail address'}, {'id': 'name', 'help': 'your full name'}, {'id': 'age', 'help': 'your age (you must be over 16)'} ]; helptext.foreach(fu...
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var dateformatter = new intl.datetimeformat('de-de', options) var dates = [date.utc(2012, 11, 20, 3, 0, 0), date.utc(2014, 04, 12, 8, 0, 0)]; dates.foreach(date => console.log(dateformatter.format(date))); // "donnerstag, 20.
TypeError: "x" is not a function - JavaScript
you will have to provide a function in order to have these methods working properly: when working with array or typedarray objects: array.prototype.every(), array.prototype.some(), array.prototype.foreach(), array.prototype.map(), array.prototype.filter(), array.prototype.reduce(), array.prototype.reduceright(), array.prototype.find() when working with map and set objects: map.prototype.foreach() and set.prototype.foreach() examples a typo in the function name in this case, which happens way too often, there is a typo in the method name: let x = document.getelementbyid('foo'...
The arguments object - JavaScript
note: “array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have array's built-in methods like foreach() or map().
Rest parameters - JavaScript
formally defined in function expression), while the arguments object contains all arguments passed to the function; the arguments object is not a real array, while rest parameters are array instances, meaning methods like sort, map, foreach or pop can be applied on it directly; the arguments object has additional functionality specific to itself (like the callee property).
Array.prototype.reduce() - JavaScript
(if you like for loops, you can filter and map while traversing once with array.foreach()).
Array.prototype.length - JavaScript
console.log(arr); // [ 1, 2, <3 empty items> ] arr.foreach(element => console.log(element)); // 1 // 2 as you can see, the length property does not necessarily indicate the number of defined values in the array.
Array.prototype.map() - JavaScript
when not to use map() since map builds a new array, using it when you aren't using the returned array is an anti-pattern; use foreach or for-of instead.
Object.assign() - JavaScript
// this is an assign function that copies full descriptors function completeassign(target, ...sources) { sources.foreach(source => { let descriptors = object.keys(source).reduce((descriptors, key) => { descriptors[key] = object.getownpropertydescriptor(source, key); return descriptors; }, {}); // by default, object.assign copies enumerable symbols, too object.getownpropertysymbols(source).foreach(sym => { let descriptor = object.getownpropertydescriptor(source, sym); if (des...
Object.getOwnPropertyNames() - JavaScript
// logs ["0", "1", "2"] // logging property names and values using array.foreach object.getownpropertynames(obj).foreach( function (val, idx, array) { console.log(val + ' -> ' + obj[val]); } ); // logs // 0 -> a // 1 -> b // 2 -> c // non-enumerable property var my_obj = object.create({}, { getfoo: { value: function() { return this.foo; }, enumerable: false } }); my_obj.foo = 1; console.log(object.getownpropertynames(my_obj).sort()); // logs ["foo", "get...
Set.prototype.delete() - JavaScript
setobj.foreach(function(point){ if (point.x > 10){ setobj.delete(point) } }) specifications specification ecmascript (ecma-262)the definition of 'set.prototype.delete' in that specification.
Template literals (Template strings) - JavaScript
function template(strings, ...keys) { return (function(...values) { let dict = values[values.length - 1] || {}; let result = [strings[0]]; keys.foreach(function(key, i) { let value = number.isinteger(key) ?
Trailing commas - JavaScript
when iterating arrays for example with array.prototype.foreach() or array.prototype.map(), array holes are skipped.
restart - SVG: Scalable Vector Graphics
WebSVGAttributerestart
="1" restart="always" /> </rect> <rect x="120" y="30" width="100" height="100"> <animate attributetype="xml" attributename="y" from="30" to="100" dur="5s" repeatcount="1" restart="whennotactive"/> </rect> <a id="restart"><text y="20">restart animation</text></a> </svg> document.getelementbyid("restart").addeventlistener("click", evt => { document.queryselectorall("animate").foreach(element => { element.beginelement(); }); }); usage notes value always | whennotactive | never default value always animatable no always this value indicates that the animation can be restarted at any time.