Search completed in 1.22 seconds.
EventTarget.addEventListener() - Web APIs
The EventTarget method
addEventListener() sets up a function that will be called whenever the specified event is delivered to the target. Common targets are Element, Document, and Window, but the target may be any object that supports events (such as XMLHttpRequest).
addEventListener() works by adding a function or an object that implements EventListener to the list of event listeners for the specified event type on the EventTarget on which it's called. Syntax target.
addEventListener(type, listener [, options]); target.
addEventListener(type, listener [, useCapture]); target.
addEventListener(type, listener [, useCapture, wantsUntrusted ]); // Gecko/Mozilla only Parameters type A case-sensitive string representing the event type to listen for. listener The object that receives a notification (an...
...Over time, it became clear that more options were needed. Rather than adding more parameters to the function (complicating things enormously when dealing with optional values), the third parameter was changed to an object that can contain various properties defining the values of options to configure the process of removing the event...
...is by using feature detection for each of the options you're interested in. For example, if you want to check for the passive option: let passiveSupported = false; try { const options = { get passive() { // This function will be called when the browser // attempts to access the passive property. passiveSupported = true; return false; } }; window.
addEventListener("test", null, options); window.removeEventListener("test", null, options); } catch(err) { passiveSupported = false; } This creates an options object with a getter function for the passive property; the getter sets a flag, passiveSupported, to true if it gets called. That means that if the browser checks the value of the passive property on the options object, passiveSupported will be set to...
...And 33 more matches
Color picker tool - CSS: Cascading Style Sheets
otype.getColor = function getColor() { if (this.a | 0 === 1) return this.getHexa(); return this.getRGBA(); }; /*=======================================================================*/ /*=======================================================================*/ /*========== Capture Mouse Movement ==========*/ var setMouseTracking = function setMouseTracking(elem, callback) { elem.
addEventListener('mousedown', function(e) { callback(e); document.
addEventListener('mousemove', callback); }); document.
addEventListener('mouseup', function(e) { document.removeEventListener('mousemove', callback); }); }; /*====================*/ // Color Picker Class /*====================*/ function ColorPicker(node) { this.color = new Color(); this.node = node; this.subscribers = [...
...r = document.createElement('div'); var input = document.createElement('input'); var info = document.createElement('span'); wrapper.className = 'input'; wrapper.setAttribute('data-topic', topic); info.textContent = title; info.className = 'name'; input.setAttribute('type', 'text'); wrapper.appendChild(info); wrapper.appendChild(input); this.node.appendChild(wrapper); input.
addEventListener('change', onChangeFunc); input.
addEventListener('click', function() { this.select(); }); this.subscribe(topic, function(value) { input.value = value; }); }; ColorPicker.prototype.createChangeModeButton = function createChangeModeButton() { var button = document.createElement('div'); button.className = 'switch_mode'; button.
addEventListener('click', function() { if (thi...
...cribe : unsubscribe, setPickerMode : setPickerMode }; })(); /** * UI-SlidersManager */ var InputSliderManager = (function InputSliderManager() { var subscribers = {}; var sliders = []; var InputComponent = function InputComponent(obj) { var input = document.createElement('input'); input.setAttribute('type', 'text'); input.style.width = 50 + obj.precision * 10 + 'px'; input.
addEventListener('click', function(e) { this.select(); }); input.
addEventListener('change', function(e) { var value = parseFloat(e.target.value); if (isNaN(value) === true) setValue(obj.topic, obj.value); else setValue(obj.topic, value); }); return input; }; var SliderComponent = function SliderComponent(obj, sign) { var slider = document.createElement('div'); var startX = nu...
...And 17 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
otype.getColor = function getColor() { if (this.a | 0 === 1) return this.getHexa(); return this.getRGBA(); }; /*=======================================================================*/ /*=======================================================================*/ /*========== Capture Mouse Movement ==========*/ var setMouseTracking = function setMouseTracking(elem, callback) { elem.
addEventListener('mousedown', function(e) { callback(e); document.
addEventListener('mousemove', callback); }); document.
addEventListener('mouseup', function(e) { document.removeEventListener('mousemove', callback); }); }; /*====================*/ // Color Picker Class /*====================*/ function ColorPicker(node) { this.color = new Color(); this.node = node; this.subscribers = [...
...r = document.createElement('div'); var input = document.createElement('input'); var info = document.createElement('span'); wrapper.className = 'input'; wrapper.setAttribute('data-topic', topic); info.textContent = title; info.className = 'name'; input.setAttribute('type', 'text'); wrapper.appendChild(info); wrapper.appendChild(input); this.node.appendChild(wrapper); input.
addEventListener('change', onChangeFunc); input.
addEventListener('click', function() { this.select(); }); this.subscribe(topic, function(value) { input.value = value; }); }; ColorPicker.prototype.createChangeModeButton = function createChangeModeButton() { var button = document.createElement('div'); button.className = 'switch_mode'; button.
addEventListener('click', function() { if (thi...
...Child !== null) { option = node.firstElementChild; option_value = option.getAttribute('data-value'); if (option_value === null) option.setAttribute('data-value', uval); list.appendChild(node.firstElementChild); uval++; } node.appendChild(select); node.appendChild(list); select.onclick = this.toggle.bind(this); list.onclick = this.updateValue.bind(this); document.
addEventListener('click', clickOut); this.state = 0; this.time = 0; this.dropmenu = list; this.select = select; this.toggle(false); this.value = {}; this.topic = topic; if (label) select.textContent = label; else this.setNodeValue(list.children[selected]); dropdowns[topic] = this; }; DropDown.prototype.toggle = function toggle(state) { if (typeof(state) === 'boolean') this.st...
...And 16 more matches
Index - Web APIs
source is opened. 1273 EventTarget API, DOM, DOM Events, EventTarget, Interface EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. 1274 EventTarget() API, Constructor, DOM, DOM Events, EventTarget The EventTarget() constructor creates a new EventTarget object instance. 1275 EventTarget.
addEventListener() API, AccessOuterData, DOM, Detecting Events, Event Handlers, Event Listener, EventTarget, JavaScript, Method, PassingData, Receiving Events, Reference,
addEventListener, attachEvent, events, mselementresize The EventTarget method
addEventListener() sets up a function that will be called whenever the specified event is delivered to the target. 1276 EventTarget.attachEvent() ...
...ing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent(). 1278 EventTarget.removeEventListener() API, DOM, DOM Element Methods, EventTarget, Gecko, Method, Reference, browser compatibility, removeEventListener The EventTarget.removeEventListener() method removes from the EventTarget an event listener previously registered with EventTarget.
addEventListener(). The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal 1279 ExtendableEvent API, Experimental, ExtendableEvent, Interface, Offline, Reference, Service Workers, ServiceWorker, Workers The ExtendableEve...
... method of the MessagePort interface sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts. 2565 MessagePort.start() API, Channel messaging, MessagePort, Method, Reference, start The start() method of the MessagePort interface starts the sending of messages queued on the port. This method is only needed when using EventTarget.
addEventListener; it is implied when using MessageChannel.onmessage. 2566 MessagePort: message event Event The message event is fired on a MessagePort object when a message arrives on that channel. 2567 MessagePort: messageerror event Event The messageerror event is fired on a MessagePort object when it receives a message that can't be deserialized. 2568 Metada...
...And 13 more matches
Sending forms through JavaScript - Learn web development
{ urlEncodedDataPairs.push( encodeURIComponent( name ) + '=' + encodeURIComponent( data[name] ) ); } // Combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behaviour of browser form submissions. ...
...nd replace all %-encoded spaces to // the '+' character; matches the behaviour of browser form submissions. ...
...For cross-origin requests, you'll need CORS and HTTP access control. Using XMLHttpRequest and the FormData object Building an HTTP request by hand can be overwhelming. ...
...And 11 more matches
Border-image generator - CSS: Cascading Style Sheets
: break-all; float: left; } JavaScript Content 'use strict'; /** * UI-SlidersManager */ var InputSliderManager = (function InputSliderManager() { var subscribers = {}; var sliders = []; var InputComponent = function InputComponent(obj) { var input = document.createElement('input'); input.setAttribute('type', 'text'); input.style.width = 50 + obj.precision * 10 + 'px'; input.
addEventListener('click', function(e) { this.select(); }); input.
addEventListener('change', function(e) { var value = parseFloat(e.target.value); if (isNaN(value) === true) setValue(obj.topic, obj.value); else setValue(obj.topic, value); }); return input; }; var SliderComponent = function SliderComponent(obj, sign) { var slider = document.createElement('div'); var startX = nu...
...t(); }); input.
addEventListener('change', function(e) { var value = parseFloat(e.target.value); if (isNaN(value) === true) setValue(obj.topic, obj.value); else setValue(obj.topic, value); }); return input; }; var SliderComponent = function SliderComponent(obj, sign) { var slider = document.createElement('div'); var startX = null; var start_value = 0; slider.
addEventListener("click", function(e) { document.removeEventListener("mousemove", sliderMotion); setValue(obj.topic, obj.value + obj.step * sign); }); slider.
addEventListener("mousedown", function(e) { startX = e.clientX; start_value = obj.value; document.body.style.cursor = "e-resize"; document.
addEventListener("mouseup", slideEnd); document.
addEventListener("mousemove", sliderMotion);...
...Child !== null) { option = node.firstElementChild; option_value = option.getAttribute('data-value'); if (option_value === null) option.setAttribute('data-value', uval); list.appendChild(node.firstElementChild); uval++; } node.appendChild(select); node.appendChild(list); select.onclick = this.toggle.bind(this); list.onclick = this.updateValue.bind(this); document.
addEventListener('click', clickOut); this.state = 0; this.time = 0; this.dropmenu = list; this.select = select; this.toggle(false); this.value = {}; this.topic = topic; if (label) select.textContent = label; else this.setNodeValue(list.children[selected]); dropdowns[topic] = this; }; DropDown.prototype.toggle = function toggle(state) { if (typeof(state) === 'boolean') this.st...
...And 11 more matches
Interacting with page scripts - Archive of obsolete content
future version of the SDK. Expose objects to page scripts Until Firefox 30, you could use unsafeWindow to perform the reverse procedure, and make objects defined in content scripts available to page scripts: // content-script.js unsafeWindow.contentScriptObject = {"greeting" : "hello from add-on"}; // page-script.js var button = document.getElementById("show-content-script-var"); button.
addEventListener("click", function() { // access object defined by content script console.log(window.contentScriptObject.greeting); // "hello from add-on" }, false); After Firefox 30, you can still do this for primitive values, but can no longer do it for objects. Instead, you need to use the global cloneInto() function to clone the object into the page script's scope. cloneInto() creates a structured cl...
...Clicking...
...Clicking "I will not work" fails, and the following message is logged: Permission denied to access property 'greeting' Expose functions to page scripts The structured clone algo...
...And 10 more matches
Using the Browser API
You can see the full HTML listing here. The JavaScript implementation To wire up the functionality required by our simple browser, we've written some basic JavaScript (see the full JavaScript listing.) Wiring up the back and forward buttons Early on in the code we implement two simple event listeners to move the browser back and forward in history when the relevant buttons are pressed: back.
addEventListener('touchend',function() { browser.goBack(); }); fwd.
addEventListener('touchend',function() { browser.goForward(); }); The functions can be handled using the Browser API HTMLIFrameElement.goBack() and HTMLIFrameElement.goForward() methods. You'll also notice that we're also firing these functions on the touchend event, which is effective as Firefox OS devices are generally touchscreen. Enabli...
...RL bar The URL bar for our simple browser is a <form> containing a single text <input>. When you tap the URL bar, you can enter a URL using the built-in Firefox OS keyboard (although note that we haven't implemented anything sophisticated in this app, like autofilling the http://, etc.). When you press the keyboard's return button, the 'submit' event is fired, which we handle like this: urlForm.
addEventListener('submit',function(e) { e.preventDefault(); browser.src = urlBar.value; urlBar.blur(); }); We first call preventDefault() to stop the form just submitting and reloading the page -- which is really not what we want. We then set the browser iframe's src attribute to equal the value of the URL bar, which causes the new URL to be loaded in the iframe. Finally, we call blur() on the url bar to s...
... get our full screen view back. There's another event listener added later on in the code that listens for the mozbrowserlocationchange event. When this fires, we set the value inside the URL bar input to be equal to the event object detail property -- this is so that the URL displayed continues to match the website being shown when the user navigates back and forth through the history. browser.
addEventListener('mozbrowserlocationchange', function (e) { urlBar.value = e.detail; }); Zooming in and out The browser content can be programmatically zoomed in and out using the HTMLIFrameElement.zoom() method. This takes a single method -- a zoom factor -- which dictates the percentage to zoom in or out by. For example, 1.1 would mean "zoom in by 10%", and 0.9 would mean "zoom out by 10%". var zoomFactor ...
...And 10 more matches
HTML text fundamentals - Learn web development
: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Sho...
... solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show solution'; } updateCode(); }); var htmlSolution = '<h1>My short story</h1>\n<p>I am a statistician and my name is Trish.</p>\n<p>My legs are made of cardboard and I am married to a fish.</p>'; var solutionEntry = htmlSolution; textarea.
addEventListener('input', updateCode); window.
addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur(); } }; function insertAtCaret(text) { var scrollPos = textarea.scrollT...
...: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Sho...
...And 9 more matches
Box-shadow generator - CSS: Cascading Style Sheets
i-slider-pointer'; node.appendChild(pointer); this.pointer = pointer; setMouseTracking(node, updateSlider.bind(this)); sliders[topic] = this; setValue(topic, this.value); } var setButtonComponent = function setButtonComponent(node) { var type = node.getAttribute('data-type'); var topic = node.getAttribute('data-topic'); if (type === "sub") { node.textContent = '-'; node.
addEventListener("click", function() { decrement(topic); }); } if (type === "add") { node.textContent = '+'; node.
addEventListener("click", function() { increment(topic); }); } } var setInputComponent = function setInputComponent(node) { var topic = node.getAttribute('data-topic'); var unit_type = node.getAttribute('data-unit'); var input = document.createElement('input'); v...
... }); } } var setInputComponent = function setInputComponent(node) { var topic = node.getAttribute('data-topic'); var unit_type = node.getAttribute('data-unit'); var input = document.createElement('input'); var unit = document.createElement('span'); unit.textContent = unit_type; input.setAttribute('type', 'text'); node.appendChild(input); node.appendChild(unit); input.
addEventListener('click', function(e) { this.select(); }); input.
addEventListener('change', function(e) { setValue(topic, e.target.value | 0); }); subscribe(topic, function(value) { node.children[0].value = value; }); } var increment = function increment(topic) { var slider = sliders[topic]; if (slider === null || slider === undefined) return; if (slider.value + slider.step <= sl...
...var delta = slider.max - slider.min; var width = slider.node.clientWidth; var offset = slider.pointer.clientWidth; var pos = (value - slider.min) * width / delta; slider.value = value; slider.pointer.style.left = pos - offset / 2 + "px"; slider.node.setAttribute('data-value', value); notify.call(slider); } var setMouseTracking = function setMouseTracking(elem, callback) { elem.
addEventListener("mousedown", function(e) { callback(e); document.
addEventListener("mousemove", callback); }); document.
addEventListener("mouseup", function(e) { document.removeEventListener("mousemove", callback); }); } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscr...
...And 8 more matches
Cross-browser audio basics - Developer guides
f we want to show progress, buffering and only activate the buttons when the media is ready to play? Fortunately, there are a number of events we can use to let our player know exactly what is happening. First, let's take a look at the media loading process in order: loadstart The loadstart event tells us simply that load process has started and the browser is connecting to the media. ...
... started and the browser is connecting to the media. myAudio.
addEventListener("loadstart", function() { //grabbing the file }); durationchange If you just want to know as soon as the duration of your media is established, this is the event for you. This can be useful because the initial value for duration is NaN (Not a Number), which you probably don't want to display to your users. myAudio.
addEventListener("durationchange", function() { //you can display the duration now }); loadedmetadata Metadata can consist of more than just duration -- if you want to wait for all the metadata to download before doing something, you can detect the loadedmetadata event. ...
... initial value for duration is NaN (Not a Number), which you probably don't want to display to your users. myAudio.
addEventListener("durationchange", function() { //you can display the duration now }); loadedmetadata Metadata can consist of more than just duration -- if you want to wait for all the metadata to download before doing something, you can detect the loadedmetadata event. myAudio.
addEventListener("loadedmetadata", function() { //you can display the duration now }); loadeddata The loadeddata event is fired when the first bit of media arrives. The playhead is in position but not quite ready to play. myAudio.
addEventListener("loadeddata", function() { //you could display the playhead now }); progress The progress event indicates that the download of media is still in progress. It is...
...And 8 more matches
Creating a cross-browser video player - Developer guides
var progressBar = document.getElementById('progress-bar'); var fullscreen = document.getElementById('fs'); Using these handles, events can now be attached to each of the custom control buttons making them interactive. Most of these buttons require a simple click event listener to be added, and a Media API defined method and/or attributes to be called/checked on the video. Play/Pause playpause.
addEventListener('click', function(e) { if (video.paused || video.ended) video.play(); else video.pause(); }); When a click event is detected on the play/pause button, the handler first of all checks if the video is currently paused or has ended (via the Media API's paused and ended attributes); if so, it uses the play() method to playback the video. Otherwise the video must be playing, so it is paused us...
....paused || video.ended) video.play(); else video.pause(); }); When a click event is detected on the play/pause button, the handler first of all checks if the video is currently paused or has ended (via the Media API's paused and ended attributes); if so, it uses the play() method to playback the video. Otherwise the video must be playing, so it is paused using the pause() method. ...
...ed using the pause() method. Stop stop.
addEventListener('click', function(e) { video.pause(); video.currentTime = 0; progress.value = 0; }); The Media API doesn't have a stop method, so to mimic this the video is paused, and its currentTime (i.e. the video's current playing position) and the <progress> element's position is set to 0 (more on the <progress> element later). Mute mute.
addEventListener('click', function(e) { video.muted = !video.muted; }); The mute button is a simple toggle button that uses the Media API's muted attribute to mute the video: this is a Boolean indicating whether the video is muted or not. To get it to toggle, we set it to the inverse of itself. ...
...And 8 more matches
ui/frame - Archive of obsolete content
two arguments, the message itself and a target origin. ...
...The data property of the event is the message payload. ...
...In this way you can customize the frame for each browser window. To do this, you call postMessage()...
...And 6 more matches
How to build custom form controls - Learn web development
} This CSS visually hides one of the elements, but it is still available to screen readers. Now we need a JavaScript switch to determine if the script is running or not. This switch is a couple of lines: if at page load time our script is running, it will remove the no-widget class and add the widget class, thereby swapping the visibility of the <select> element and the custom control. ...
... a class switch it's far better to just add the widget class to hide the <select> elements, and to dynamically add the DOM tree representing the custom control after every <select> element in the page. Making the job easier In the code we are about to build, we will use the standard JavaScript and DOM APIs to do all the work we need. 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. The object returned by the querySelectorAll() function is a NodeList rather than an Array. This is important because Array objects support the forEach function, but NodeList doesn't. Because NodeList really looks like an Array and because for...
...ve the highlight from all options optionList.forEach(function (other) { other.classList.remove('highlight'); }); // We highlight the right option option.classList.add('highlight'); }; You need these in order to handle the various states of the custom control. Next, we bind these functions to the appropriate events: // We handle the event binding when the document is loaded. ...
...And 6 more matches
Using files from web applications - Web APIs
ted by the user. The multiple attribute on the input element allows the user to select multiple files. Accessing the first selected file using a classical DOM selector: const selectedFile = document.getElementById('input').files[0]; Accessing selected file(s) on a change event It is also possible (but not mandatory) to access the FileList through the change event. ...
... file using a classical DOM selector: const selectedFile = document.getElementById('input').files[0]; Accessing selected file(s) on a change event It is also possible (but not mandatory) to access the FileList through the change event. You need to use EventTarget.
addEventListener() to add the change event listener, like this: const inputElement = document.getElementById("input"); inputElement.
addEventListener("change", handleFiles, false); function handleFiles() { const fileList = this.files; /* now you can work with the file list */ } Getting information about selected file(s) The FileList object provided by the DOM lists all of the files selected by the user, each specified as a File object. You can determine how many files the user selected by checking the value of the file list's length attrib...
...You can do this by styling the input element with display:none and calling the click() method on the <input> ...
...And 6 more matches
Communicating With Other Scripts - Archive of obsolete content
See the section below on using postMessage() before Firefox 31. You can communicate between the content script and page scripts using window.postMessage(). Messaging From Content Script To Page Script Suppose we have a page called "listen.html" hosted at "my-domain.org", and we want to send messages from the add-on to a script embedded in that page...
...clude: "http://my-domain.org/listen.html", contentScriptFile: data.url("talk.js") }); The "talk.js" content script uses window.postMessage() to send the message to the page: // content-script (talk.js) window.postMessage("Message from content script", "http://my-domain.org/"); The second argument may be '*' which will allow communication with any domain. ...
...() to send the message to the page: // content-script (talk.js) window.postMessage("Message from content script", "http://my-domain.org/"); The second argument may be '*' which will allow communication with any domain. Finally, "listen.html" uses window.
addEventListener() to listen for messages from the content script: <!DOCTYPE html> <html> <head></head> <body> <script> window.
addEventListener('message', function(event) { window.alert(event.data); // Message from content script }, false); </script> </body> </html> Messaging From Page Script To Content Script Sending messages from the page script to the content script is just the same, but in reverse. Here "main.js" creates a page-mod that attaches "listen.js" to the web page: var data = require("sdk/self").dat...
...And 5 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
a web page to an extension is by using custom DOM events. In your extension's browser.xul overlay, write code which listens for a custom DOM event. Here we call the event MyExtensionEvent. var myExtension = { myListener: function(evt) { alert("Received from web page: " + evt.target.getAttribute("attribute1") + "/" + evt.target.getAttribute("attribute2")); } } document.
addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); // The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event. The data from the web page (unprivileged code) will be the values of attribute1 and attribute2. To trigger the alert() in the listener and pass the data from the web page, write code such as this in the web pag...
... Note: If you're using HTML5's postMessage() to send a message from unprivileged code to privileged code, adding 'true' to the end of your event listener in your privileged chrome code will allow th...
...xtension.myListener(e); }, false, true); If you need to to pass lots of data, consider using CDATA sections instead of the simple attributes on a custom element. Note: If you're using HTML5's postMessage() to send a message from unprivileged code to privileged code, adding 'true' to the end of your event listener in your privileged chrome code will allow the message to be received. document.
addEventListener("message", function(e) { yourFunction(e); }, false, true); Sending data from chrome to unprivileged document To "answer" the web page (e.g., return code), your extension can set an attribute or attach child elements on the event target element (<MyExtensionDataElement/> in this example). You can optionally clean up the created element, or create it once when the web page loads then re-use it e...
...And 5 more matches
Introduction to events - Learn web development
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.
addEventListener() and removeEventListener() The newest type of event mechanism is defined in the Document Object Model (DOM) Level 2 Events Specification, which provides browsers with a new function --
addEventListener(). This functions in a similar way to the event handler properties, but the syntax is obviously different. We could rewrite our random color example to look like this: const btn = document.query...
...n --
addEventListener(). This functions in a similar way to the event handler properties, but the syntax is obviously different. We could rewrite our random color example to look like this: const btn = document.querySelector('button'); function bgChange() { const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; } btn.
addEventListener('click', bgChange); Note: You can find the full source code for this example on GitHub (also see it running live). Inside the
addEventListener() function, we specify two parameters -- the name of the event we want to register this handler for, and the code that comprises the handler function we want to run in response to it. Note: It is perfectly appropriate to put all the code inside the add...
...his example on GitHub (also see it running live). Inside the
addEventListener() function, we specify two parameters -- the name of the event we want to register this handler for, and the code that comprises the handler function we want to run in response to it. Note: It is perfectly appropriate to put all the code inside the
addEventListener() function, in an anonymous function, like this: btn.
addEventListener('click', function() { var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundColor = rndCol; }); This mechanism has some advantages over the older mechanisms discussed earlier. First, there is a counterpart function, removeEventListener(), which removes a previously added listener. For example, this would remove the listener set in the ...
...And 5 more matches
Looping code - Learn web development
canvas.height = HEIGHT; function random(number) { return Math.floor(Math.random()*number); } function draw() { ctx.clearRect(0,0,WIDTH,HEIGHT); for (let i = 0; i < 100; i++) { ctx.beginPath(); ctx.fillStyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI); ctx.fill(); } } btn.
addEventListener('click',draw); </script> </body> </html> You don't have to understand all the code for now, but let's look at the part of the code that actually draws the 100 circles: for (let i = 0; i < 100; i++) { ctx.beginPath(); ctx.fillStyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI); ctx.fill(); } random(x), defined earlier in the code,...
...sults in: <label for="search">Search by contact name: </label> <input id="search" type="text"> <button>Search</button> <p></p> Now on to the JavaScript: const contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975']; const para = document.querySelector('p'); const input = document.querySelector('input'); const btn = document.querySelector('button'); btn.
addEventListener('click', function() { let searchName = input.value.toLowerCase(); input.value = ''; input.focus(); for (let i = 0; i < contacts.length; i++) { let splitContact = contacts[i].split(':'); if (splitContact[0].toLowerCase() === searchName) { para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.'; break; } else { para.textContent = 'Contact ...
...abel for="search">Search by contact name: </label> <input id="search" type="text"> <button>Search</button> <p></p> <script> const contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975']; const para = document.querySelector('p'); const input = document.querySelector('input'); const btn = document.querySelector('button'); btn.
addEventListener('click', function() { let searchName = input.value.toLowerCase(); input.value = ''; input.focus(); for (let i = 0; i < contacts.length; i++) { let splitContact = contacts[i].split(':'); if (splitContact[0].toLowerCase() === searchName) { para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.'; break; } else ...
...And 5 more matches
What is JavaScript? - Learn web development
So what can it really ...
...but these are advanced techniques that we won't cover in this course. JavaScript running order When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in. For example, let's return to the block of JavaScript we saw in our first example: const para = document.querySelector('p'); para.
addEventListener('click', updateName); function updateName() { let name = prompt('Enter a new name'); para.textContent = 'Player 1: ' + name; } Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the updateName() code block (lines 5-8) is run. The updateName() code block (these types of reusable code blocks are called "funct...
...tes a simple web page containing a clickable button. ...
...And 5 more matches
Advanced animations - Web APIs
We need to check if the x and y position of the ball is out of the canvas dimensions and invert the direction of the velocity...
...We need to check if the x and y position of the ball is out of the canvas dimensions and invert the direction of the velocity vectors. To do so, we add the following checks to the draw method: if (ball.y + ball.vy > canvas.h...
...tx.fill(); } }; function draw() { ctx.clearRect(0,0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } raf = window.requestAnimationFrame(draw); } canvas.
addEventListener('mouseover', function(e) { raf = window.requestAnimationFrame(draw); }); canvas.
addEventListener('mouseout', function(e) { window.cancelAnimationFrame(raf); }); ball.draw(); Acceleration To make the motion more real, you can play with the velocity like this, for example: ball.vy *= .99; ball.vy += .25; This slows down the vertical velocity each frame, so that the ball will just bounc...
...And 5 more matches
Using the Gamepad API - Web APIs
o the focused page when the user presses a button or moves an axis. In Firefox, gamepads are only exposed to a page when the user interacts with one with the page visible. This helps prevent gamepads being used for fingerprinting the user. Once one gamepad has been interacted with, other gamepads that are connected will automatically be visible. You can use gamepadconnected like this: window.
addEventListener("gamepadconnected", function(e) { console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.", e.gamepad.index, e.gamepad.id, e.gamepad.buttons.length, e.gamepad.axes.length); }); Each gamepad has a unique ID associated with it, which is available on the event's gamepad property. Disconnecting a gamepad When a gamepad is disconnected, and if a page has previously received ...
... e.gamepad.id, e.gamepad.buttons.length, e.gamepad.axes.length); }); Each gamepad has a unique ID associated with it, which is available on the event's gamepad property. Disconnecting a gamepad When a gamepad is disconnected, and if a page has previously received data for that gamepad (e.g. gamepadconnected), a second event is dispatched to the focused window, gamepaddisconnected: window.
addEventListener("gamepaddisconnected", function(e) { console.log("Gamepad disconnected from index %d: %s", e.gamepad.index, e.gamepad.id); }); The gamepad's index property will be unique per-device connected to the system, even if multiple controllers of the same type are used. The index property also functions as the index into the Array returned by Navigator.getGamepads(). var gamepads = {}; function ...
... type are used. The index property also functions as the index into the Array returned by Navigator.getGamepads(). var gamepads = {}; function gamepadHandler(event, connecting) { var gamepad = event.gamepad; // Note: // gamepad === navigator.getGamepads()[gamepad.index] if (connecting) { gamepads[gamepad.index] = gamepad; } else { delete gamepads[gamepad.index]; } } window.
addEventListener("gamepadconnected", function(e) { gamepadHandler(e, true); }, false); window.
addEventListener("gamepaddisconnected", function(e) { gamepadHandler(e, false); }, false); This previous example also demonstrates how the gamepad property can be held after the event has completed -- a technique we will use for device state querying later. Querying the Gamepad object As you can see, the gamepad even...
...And 5 more matches
Using Service Workers - Web APIs
. Note: The Cache API is not supported in every browser. (See the Browser compatibility section for more information.) If you want to use this now, you could consider using a polyfill like the one available in Google's Topeka demo, or perhaps store your assets in IndexedDB. ...
...ncludes the documents inside the specified scope, and any resources referenced in those documents (for example if index.html makes a cross origin request to embed an image, that still goes through its service worker.) You can attach a fetch event listener to the service worker, then call the respondWith() method on the event to hijack our HTTP responses and update them with your own magic. ...
...r.) You can attach a fetch event listener to the service worker, then call the respondWith() method on the event to hijack our HTTP responses and update them with your own magic. self.
addEventListener('fetch', (event) => { event.respondWith( // magic goes here ); }); We could start by simply responding with the resource whose url matches that of the network request, in each case: self.
addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request) ); }); caches.match(event.request) allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via url and vary headers, just like with normal HTTP requests. Let's look at a few other options we have when def...
...And 5 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
We need to add a GainNode and connect that through our audio graph...
...ep="0.1" /> Now we can create some variables over in JavaScript and have them change when the input values are updated: let attackTime = 0.2; const attackControl = document.querySelector('#attack'); attackControl.
addEventListener('input', function() { attackTime = Number(this.value); }, false); let releaseTime = 0.5; const releaseControl = document.querySelector('#release'); releaseControl.
addEventListener('input', function() { releaseTime = Number(this.value); }, false); The final playSweep() function Now we can expand our playSweep() function. We need to add a GainNode and connect that through our audio graph to actually apply amplitude variations to our sound. The gain node has one property: gain, which is of type AudioParam. This is really useful -- now we can start to harness the power ...
...st wave: <label for="hz">Hz</label> <input name="hz" id="hz" type="range" min="660" max="1320" value="880" step="1" /> <label for="lfo">LFO</label> <input name="lfo" id="lfo" type="range" min="20" max="40" value="30" step="1" /> As before, we'll vary the parameters when the range input values are changed by the user. ...
...And 5 more matches
Audio and video manipulation - Developer guides
his.video.ended) { return; } this.computeFrame(); var self = this; setTimeout(function () { self.timerCallback(); }, 16); // roughly 60 frames per second }, doLoad: function() { this.video = document.getElementById("my-video"); this.c1 = document.getElementById("my-canvas"); this.ctx1 = this.c1.getContext("2d"); var self = this; this.video.
addEventListener("play", function() { self.width = self.video.width; self.height = self.video.height; self.timerCallback(); }, false); }, computeFrame: function() { this.ctx1.drawImage(this.video, 0, 0, this.width, this.height); var frame = this.ctx1.getImageData(0, 0, this.width, this.height); var l = frame.data.length / 4; for (var i = 0; i < l; i++) { var grey ...
... Audio manipulation playbackRate aside, to manipulate audio you'll typically use the Web Audio API. Selec...
... Audio manipulation playbackRate aside, to manipulate audio you'll typically use the Web Audio API. Selecting an audio source The Web Audio API can receive audio from a variety of sources, then proce...
...And 5 more matches
Tabbed browser - Archive of obsolete content
of the newly opened tab, you'll need to wait until the content has finished loading. // WRONG WAY (the page hasn't finished loading yet) var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); alert(newTabBrowser.contentDocument.body.innerHTML); // BETTER WAY var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/")); newTabBrowser.
addEventListener("load", function () { newTabBrowser.contentDocument.body.innerHTML = "<div>hello world</div>"; }, true); (The event target in the onLoad handler will be a 'tab' XUL element). See tabbrowser for getBrowserForTab(). Note that the code above does not work inside of the Electrolysis (e10s) enabled tabs. Opening a URL in the correct window/tab There are methods available in chrome://browser/cont...
... of // the frameset. If you don't want do anything when frames/iframes // are loaded in this web page, uncomment the following line: // return; // Find the root document: win = win.top; } } } // do not try to add a callback until the browser window has // been initialised. We add a callback to the tabbed browser // when the browser's window gets loaded. window.
addEventListener("load", function () { // Add a callback to be run every time a document loads. // note that this includes frames/iframes within the document gBrowser.
addEventListener("load", examplePageLoad, true); }, false); ... // When no longer needed gBrowser.removeEventListener("load", examplePageLoad, true); ... Notification when a tab is added or removed function exampleTabAdded(event) { var b...
... } function exampleTabMoved(event) { var browser = gBrowser.getBrowserForTab(event.target); // browser is the XUL element of the browser that's been moved } function exampleTabRemoved(event) { var browser = gBrowser.getBrowserForTab(event.target); // browser is the XUL element of the browser that's been removed } // During initialization var container = gBrowser.tabContainer; container.
addEventListener("TabOpen", exampleTabAdded, false); container.
addEventListener("TabMove", exampleTabMoved, false); container.
addEventListener("TabClose", exampleTabRemoved, false); // When no longer needed container.removeEventListener("TabOpen", exampleTabAdded, false); container.removeEventListener("TabMove", exampleTabMoved, false); container.removeEventListener("TabClose", exampleTabRemoved, false); Note...
...And 4 more matches
Getting started with HTML - Learn web development
0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Sho...
...Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show solution'; } updateCode(); }); var htmlSolution = '<em>This is my text.</em>'; var solutionEntry = htmlSolution; textarea.
addEventListener('input', updateCode); window.
addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur(); } }; function insertAtCaret(text) { var scrollPos = textarea.scrollT...
...: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Sho...
...And 4 more matches
EventTarget.removeEventListener() - Web APIs
The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal Syntax target.removeEventListener(type, listener[, options]); target.removeEventListener(type, listener[, useCapture]); Parameters type A string which specifies the type of event for which to remove an event listener. ...
... or not. If this parameter is absent, a default value of false is assumed. If a listener is registered twice, one with capture and one without, remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa. ...
...on of the same listener, and vice versa. Return value undefined Matching event listeners for removal Given an event listener previously added by calling
addEventListener(), you may eventually come to a point at which you need to remove it. Obviously, you need to specify the same type and listener parameters to removeEventListener(). But what about the options or useCapture parameters? ...
...And 4 more matches
Inputs and input sources - Web APIs
ce it. An inputsourceschange event is sent to your XRSession whenever one or more of the input sources change, or when an input source is added to or removed from the list. ...
...mple as throwing an object or pulling the trigger of a gun in a game, or as involved as placing an object that they were dragging around the world back down again in a new location. If your primary action is a simple trigger action and you don't need to animate anything while the trigger is engaged, you can ignore the selectstart and selectend events and simply act on the start event. xrSession.
addEventListener("select", event => { let inputSource = event.inputSource; let frame = event.frame; /* handle the event */ }); Some actions may send these events very quickly, one after the other. The time that elapses between these events depends on both the hardware apparatus that causes the action as well as the software drivers that interpret the hardware action and turn it into a series of events. Do...
...cene. The code presumes the existence of an avatar object representing the character, as used in several other eamples on this page, as well as the pickUpObject() and dropObject() functions, which handle transferring an object from the world to a particular hand and releasing an object from the hand and placing it back into the world. ...
...And 4 more matches
Border-radius generator - CSS: Cascading Style Sheets
-select: text; -ms-user-select: text; user-select: text; float: right; } JavaScript Content 'use strict'; /** * UI-InputSliderManager */ var InputSliderManager = (function InputSliderManager() { var subscribers = {}; var sliders = []; var InputComponent = function InputComponent(obj) { var input = document.createElement('input'); input.setAttribute('type', 'text'); input.
addEventListener('click', function(e) { this.select(); }); input.
addEventListener('change', function(e) { var value = parseInt(e.target.value); if (isNaN(value) === true) setValue(obj.topic, obj.value); else setValue(obj.topic, value); }); subscribe(obj.topic, function(value) { input.value = value + obj.unit; }); return input; } var SliderComponent = function SliderCompon...
...eInt(e.target.value); if (isNaN(value) === true) setValue(obj.topic, obj.value); else setValue(obj.topic, value); }); subscribe(obj.topic, function(value) { input.value = value + obj.unit; }); return input; } var SliderComponent = function SliderComponent(obj, sign) { var slider = document.createElement('div'); var startX = null; var start_value = 0; slider.
addEventListener("click", function(e) { setValue(obj.topic, obj.value + obj.step * sign); }); slider.
addEventListener("mousedown", function(e) { startX = e.clientX; start_value = obj.value; document.body.style.cursor = "e-resize"; document.
addEventListener("mousemove", sliderMotion); }); document.
addEventListener("mouseup", function(e) { document.removeEventListener("mousemove", slider...
...opic; checkbox.id = id; checkbox.setAttribute('type', 'checkbox'); checkbox.checked = state; label.setAttribute('for', id); if (name) { label.className = 'text'; if (align) label.className += ' ' + align; label.textContent = name; } node.appendChild(checkbox); node.appendChild(label); this.node = node; this.topic = topic; this.checkbox = checkbox; checkbox.
addEventListener('change', function(e) { notify.call(this); }.bind(this)); buttons[topic] = this; } var getNode = function getNode(topic) { return buttons[topic].node; } var setValue = function setValue(topic, value) { try { buttons[topic].checkbox.checked = value; } catch(error) { console.log(error); } } var subscribe = function subscribe(topic, callback) { if (subscribers[top...
...And 4 more matches
Miscellaneous - Archive of obsolete content
a. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. This is the scrolling area. </div> <script type="text/javascript"> var elm = document.getElementById("scrollArea"); elm.
addEventListener("DOMMouseScroll", function scroll(event){ //event.detail is positive for a downward scroll, negative for an upward scroll alert("scrolling " + event.detail + " lines"); }, false); </script> If you do not receive a DOMMouseScroll event while holding any of the modifier keys (Ctrl,Shift,Alt,Meta) you should check the mousewheel.withcontrolkey.action and related preferences. The meaning ...
...4 Discovering which element in the loaded document has focus // focusedControl stores the focused field, or null if there is none. // This excludes textareas for simplicity, but onPageLoad() can easily be // modified to cycle through textareas as well. Further enhancements would include // handling for fields dynamically added to the page (e.g., by page javascript). ...
..., or null if there is none. // This excludes textareas for simplicity, but onPageLoad() can easily be // modified to cycle through textareas as well. Further enhancements would include // handling for fields dynamically added to the page (e.g., by page javascript). ...
...And 3 more matches
On page load - Archive of obsolete content
lay Firefox chrome://browser/content/browser.xul Thunderbird chrome://messenger/content/messenger.xul Navigator from SeaMonkey chrome://navigator/content/navigator.xul Attaching a script Attach a script to your overlay (see "Attaching a Script to an Overlay") that adds a load event listener to appcontent element (browsers) or messagepane (mail): window.
addEventListener("load", function load(event){ window.removeEventListener("load", load, false); //remove listener, no longer needed myExtension.init(); },false); var myExtension = { init: function() { var appcontent = document.getElementById("appcontent"); // browser if(appcontent){ appcontent.
addEventListener("DOMContentLoaded", myExtension.onPageLoad, true); } var messagepane ...
... // doc.location is a Location object (see below for a link). // You can use it to make your code executed on certain pages only. if(doc.location.hr...
...get; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a Location object (see below for a link). // You can use it to make your code executed on certain pages only. if(doc.location.href.search("forum") > -1) alert("a forum page is loaded"); // add event listener for page unload aEvent.originalTarget.defaultView.
addEventListener("unload", function(event){ myExtension.onPageUnload(event); }, true); }, onPageUnload: function(aEvent) { // do something } }; Current Firefox trunk nightlies will fire the onPageLoad function for not only documents, but xul:images (favicons in tabbrowser). If you only want to handle documents, ensure aEvent.originalTarget.nodeName == "#document" . If you are running code on a page ...
...And 3 more matches
Advanced text formatting - Learn web development
width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); const code = textarea.value; const userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Sho...
...ntry; solution.value = 'Show solution'; } updateCode(); }); const htmlSolution = '<dl>\n <dt>Bacon</dt>\n <dd>The glue that binds the world together.</dd>\n <dt>Eggs</dt>\n <dd>The glue that binds the cake together.</dd>\n <dt>Coffee</dt>\n <dd>The drink that gets the world running in the morning.</dd>\n <dd>A light brown color.</dd>\n</dl>'; const solutionEntry = htmlSolution; textarea.
addEventListener('input', updateCode); window.
addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur(); } }; function insertAtCaret(text) { const scrollPos = textarea.scrol...
...width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); const code = textarea.value; const userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Sho...
...And 3 more matches
Making decisions in your code — conditionals - Learn web development
Wear shorts! Go to the beach, or the park, and get an ice cream.'; } else if (choice === 'rainy') { para.textContent = 'Rain is falling outside; take a rain coat and an umbrella, and don\'t stay out for too long.'; } else i...
...Wear shorts! Go to the beach, or the park, and get an ice cream.'; break; case 'rainy': para.textContent = 'Rain is falling outside; take a rain coat and an umbrella, and don\'t stay out for too long.';...
...y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show ...
...And 3 more matches
Video and Audio APIs - Learn web development
sibility = 'visible'; These two lines remove the default browser controls from the video, and make the custom controls visible. Playing and pausing the video Let's implement probably the most important control -- the play/pause button. First of all, add the following to the bottom of your code, so that the playPauseMedia() function is invoked when the play button is clicked: play.
addEventListener('click', playPauseMedia); Now to define playPauseMedia() -- add the following, again at the bottom of your code: function playPauseMedia() { if(media.paused) { play.setAttribute('data-icon','u'); media.play(); } else { play.setAttribute('data-icon','P'); media.pause(); } } Here we use an if statement to check whether the video is paused. The HTMLMediaElement.pau...
...ribute value on the play button to "u", which is a "paused" icon, and invoke the HTMLMediaElement.play() method to play the media. On the second click, the button will be toggled back again -- the "play" icon will be shown again, and the video will be paused with HTMLMediaElement.pause(). Stopping the video Next, let's add functionality to handle stopping the video. Add the following
addEventListener() lines below the previous one you added: stop.
addEventListener('click', stopMedia); media.
addEventListener('ended', stopMedia); The click event is obvious -- we want to stop the video by running our stopMedia() function when the stop button is clicked. We do however also want to stop the video when it finishes playing -- this is marked by the ended event firing, so we also set up a listen...
...deo was paused or playing when the stop button is pressed, you want it to be ready to play afterwards. Seeking back and forth There are many ways that you can implement rewind and fast forward functionality; here we are showing you a relatively complex way of doing it, which doesn't break when the different buttons are pressed in an unexpected order. ...
...And 3 more matches
Useful string methods - Learn web development
y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show ...
... \'Get well soon\'];' + '\n' + '\nfor (let i = 0; i < greetings.length; i++) {' + '\n let input = greetings[i];' + '\n if (greetings[i].indexOf(\'Christmas\') !== -1) {' + '\n let result = input;' + '\n let listItem = document.createElement(\'li\');' + '\n listItem.textContent = result;' + '\n list.appendChild(listItem);' + '\n }' + '\n}'; let solutionEntry = jsSolution; textarea.
addEventListener('input', updateCode); window.
addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur(); } }; function insertAtCaret(text) { const scrollPos = textarea.scrol...
...y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show ...
...And 3 more matches
Animation.playbackRate - Web APIs
effectively pauses the animation (however, its playstate does not necessarily become paused). Examples In the Growing/Shrinking Alice Game example, clicking or tapping the bottle causes Alice's growing animation (aliceChange) to reverse, causing her to shrink: var shrinkAlice = function() { aliceChange.playbackRate = -1; aliceChange.play(); } // On tap or click, Alice will shrink. ...
...oes not necessarily become paused). Examples In the Growing/Shrinking Alice Game example, clicking or tapping the bottle causes Alice's growing animation (aliceChange) to reverse, causing her to shrink: var shrinkAlice = function() { aliceChange.playbackRate = -1; aliceChange.play(); } // On tap or click, Alice will shrink. ...
...Change.play(); } // On tap or click, Alice will shrink. bottle.
addEventListener("mousedown", shrinkAlice, false); bottle.
addEventListener("touchstart", shrinkAlice, false); Contrariwise, clicking on the cake causes her to "grow," playing aliceChange forwards again: var growAlice = function() { aliceChange.playbackRate = 1; aliceChange.play(); } // On tap or click, Alice will grow. ...
...And 3 more matches
TrackEvent - Web APIs
Track, or TextTrack). Methods TrackEvent has no methods of its own; however, it is based on Event, so it provides the methods available on Event objects. Example This example sets up a function, handleTrackEvent(), which is callled for any addtrack or removetrack event on the first <video> element found in the document. ...
...r, it is based on Event, so it provides the methods available on Event objects. Example This example sets up a function, handleTrackEvent(), which is callled for any addtrack or removetrack event on the first <video> element found in the document. ...
... Example This example sets up a function, handleTrackEvent(), which is callled for any addtrack or removetrack event on the first <video> element found in the document. ...
...And 3 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
to be applied to convert them to simulate the viewer's current position and orientation. The fragment shader returns the color of each vertex, interpolating as needed from the values found in the texture and applying the lighting effects. Starting up and shutting down WebXR Upon initially loading the script, we install a handler for the load event, so that we can perform initialization. ...
... the color of each vertex, interpolating as needed from the values found in the texture and applying the lighting effects. Starting up and shutting down WebXR Upon initially loading the script, we install a handler for the load event, so that we can perform initialization. ...
...tting up event handlers, compiling and installing the GLSL code for the vertex and fragment shaders, and attaching the WebGL layer to the WebXR session before kicking off the rendering loop. It gets called as the handler for the promise returned by isSessionSupported(). ...
...And 3 more matches
Video player styling basics - Developer guides
== 'playpause') { if (video.paused || video.ended) { playpause.setAttribute('data-state', 'play'); } else { playpause.setAttribute('data-state', 'pause'); } } // Mute button else if (type == 'mute') { mute.setAttribute('data-state', video.muted ? ...
...('data-state', 'play'); } else { playpause.setAttribute('data-state', 'pause'); } } // Mute button else if (type == 'mute') { mute.setAttribute('data-state', video.muted ? ...
... 'pause'); } } // Mute button else if (type == 'mute') { mute.setAttribute('data-state', video.muted ? ...
...And 3 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
at sits inside the app.js file; everything else that is Service Worker-specific is written in the sw.js file itself. Lifecycle of a Service Worker When registration is complete, the sw.js file is automatically downloaded, then installed, and finally activated. Installation The API allows us to add event listeners for key events we are interested in -- the first one is the install event: self.
addEventListener('install', (e) => { console.log('[Service Worker] Install'); }); In the install listener, we can initialize the cache and add files to it for offline use. Our js13kPWA app does exactly that. First, a variable for storing the cache name is created, and the app shell files are listed in one array. var cacheName = 'js13kPWA-v1'; var appShellFiles = [ '/pwa-examples/js13kpwa/', '/pwa-examp...
... be loaded along with the content from the data/games.js file are generated in the second array. After that, both arrays are merged using the Array.prototype.concat() function. var gamesImages = []; for(var i=0; i<games.length; i++) { gamesImages.push('data/img/'+games[i].slug+'.jpg'); } var contentToCache = appShellFiles.concat(gamesImages); Then we can manage the install event itself: self.
addEventListener('install', (e) => { console.log('[Service Worker] Install'); e.waitUntil( caches.open(cacheName).then((cache) => { console.log('[Service Worker] Caching all: app shell and content'); return cache.addAll(contentToCache); }) ); }); There are two things that need an explanation here: what ExtendableEvent.waitUntil does, and what the caches object is. The service worke...
...es that are no longer necessary and clean up after the app in general. We don't need to do that in our app, so we'll skip it. Responding to fetches We also have a fetch event at our disposal, which fires every time an HTTP request is fired off from our app. This is very useful, as it allows us to intercept requests and respond to them with custom responses. Here is a simple usage example: self.
addEventListener('fetch', (e) => { console.log('[Service Worker] Fetched resource '+e.request.url); }); The response can be anything we want: the requested file, its cached copy, or a piece of JavaScript code that will do something specific -- the possibilities are endless. In our example app, we serve content from the cache instead of the network as long as the resource is actually in the cache. We do this...
...And 3 more matches
dev/panel - Archive of obsolete content
tooltip: "My new devtool's panel", icon: "./my-icon.png", url: "./my-panel.html", onReady: function() { this.postMessage("Message from the add-on"); } }); // export the constructor exports.MyPanel = MyPanel; // create a new tool, initialized // with the new constructor const myTool = new Tool({ panels: { myPanel: MyPanel } }); In the panel document script: // my-panel.js window.
addEventListener("message", function(event) { var content = document.getElementById("content"); content.textContent = event.data; }); Note that at the moment you have to pass an array of ports into postMessage, even if you don't need to use them: // main.js // require the SDK modules const { Panel } = require("dev/panel"); const { Tool } = require("dev/toolbox"); const { Class } = require("sdk/core/herita...
...e panel document this.postMessage("Message from the add-on", [panelSide]); } }); // export the constructor exports.MyPanel = MyPanel; // create a new tool, initialized // with the new constructor const myTool = new Tool({ panels: { myPanel: MyPanel } }); In the panel document: retrieve the MessagePort from the event, and use it to send messages to the add-on // my-panel.js window.
addEventListener("message", function(event) { // retrieve the port var toAddon = event.ports[0]; toAddon.start(); toAddon.postMessage("Message from the panel document"); console.log(toAddon); }); Communicating with the debugger server The Firefox developer tools use a client/server protocol: a tool, such as a JavaScript debugger or style editor, is the client, and the program being debugged, such as ...
... Volcan.js: a JavaScript API for...
...And 2 more matches
Introducing the Audio API extension - Archive of obsolete content
Once the buffer is full, the event MozAudioAvailable is triggered. This event therefore contains the raw samples of a period of t...
...Content scripts can specify the audio stream's characteristics, then write audio samples. Users must c...
...Content scripts can specify the audio stream's characteristics, then write audio samples. Users must create an audio object and then use the mozSetup() function to specify the ...
...And 2 more matches
Building accessible custom components in XUL - Archive of obsolete content
he way around the tab order and coming back into the spreadsheet), we need to programmatically reset the focus to the previously focused cell. This is handled in the spreadsheet_focus function, which is registered as a handler for the focus event. ...
...e need to programmatically reset the focus to the previously focused cell. This is handled in the spreadsheet_focus function, which is registered as a handler for the focus event. ...
...= get_index_within_parent(current.parentNode); var columns = current.parentNode.parentNode.childNodes; return column == columns.length - 1 ? null : columns[column + 1].childNodes[row]; } </code> Finally, we need to register the spreadsheet_keypress event handler. <code> function install_handlers() { var spreadsheet = window.document.getElementById('accjaxspreadsheet'); spreadsheet.
addEventListener('keypress', spreadsheet_keypress, true); spreadsheet.
addEventListener('focus', spreadsheet_focus, true); spreadsheet.
addEventListener('click', spreadsheet_click, true); } </code> With this new event handler and associated helper functions, we can navigate between cells and headers using the arrow keys. Inspect32 confirms that assistive technologies track the focus as we navigate within th...
...And 2 more matches
Client-side storage - Learn web development
const h1 = document.querySelector('h1'); const personalGreeting = document.querySelector('.personal-greeting'); Next up, we need to include a small event listener to stop the form from actually submitting itself when the submit button is pressed, as this is not the behavior we want. Add this snippet below your previous code: // Stop the form from submitting when a button is pressed form.
addEventListener('submit', function(e) { e.preventDefault(); }); Now we need to add an event listener, the handler function of which will run when the "Say hello" button is clicked. The comments explain in detail what each bit does, but in essence here we are taking the name the user has entered into the text input box and saving it in web storage using setItem(), then running a function called nameDispla...
...clicked. The comments explain in detail what each bit does, but in essence here we are taking the name the user has entered into the text input box and saving it in web storage using setItem(), then running a function called nameDisplayCheck() that will handle updating the actual website text. ...
...ler to run a function when the "Forget" button is clicked -- this is only displayed after the "Say hello" button has been clicked (the two form states toggle back and forth). In this function we remove the name item from web storage using removeItem(), then again run nameDisplayCheck() to update the display. Add this to the bottom: // run function when the 'Forget' button is clicked forgetBtn.
addEventListener('click', function() { // Remove the stored name from web storage localStorage.removeItem('name'); // run nameDisplayCheck() to sort out displaying the // generic greeting again and updating the form display nameDisplayCheck(); }); It is now time to define the nameDisplayCheck() function itself. Here we check whether the name item has been stored in web storage by using localStorag...
...And 2 more matches
Creating JavaScript callbacks in components
/* get a reference to the parser somehow */ stringParser.addObserver(wordHandler); stringParser.parse("pay no attention to the man behind the curtain"); You can find examples of this pattern all over the Mozilla codebase. In fact, there is even a specific interface for this form of push callbacks, nsIObserverService. ...
...ddObserver(wordHandler); stringParser.parse("pay no attention to the man behind the curtain"); You can find examples of this pattern all over the Mozilla codebase. In fact, there is even a specific interface for this form of push callbacks, nsIObserverService. JavaScript functions as callbacks Another common use of the pattern is found in
addEventListener / removeEventListener. ...
... all over the Mozilla codebase. In fact, there is even a specific interface for this form of push callbacks, nsIObserverService. JavaScript functions as callbacks Another common use of the pattern is found in
addEventListener / removeEventListener. A nice feature of
addEventListener is that you can pass a JavaScript function in place of the callback listener interface. ...
...And 2 more matches
HTMLElement: animationcancel event - Web APIs
orts. In other words, any time it stops running without sending an animationend event. This might happen when the animation-name is changed such that the animation is removed, or when the animating node is hidden using CSS. Therefore, either directly or because any of its containing nodes are hidden. An event handler for this event can be added by setting the onanimationcancel property, or using
addEventListener(). Bubbles Yes Cancelable No Interface AnimationEvent Event handler property onanimationcancel Examples This code gets an element that's currently being animated and adds a listener to the animationcancel event. It then sets the element's display property to none, which will trigger the animationcancel event. const animated = document.quer...
... Cancelable No Interface AnimationEvent Event handler property onanimationcancel Examples This code gets an element that's currently being animated and adds a listener to the animationcancel event. It then sets the element's display property to none, which will trigger the animationcancel event. ...
...ted and adds a listener to the animationcancel event. It then sets the element's display property to none, which will trigger the animationcancel event. ...
...And 2 more matches
HTMLElement: transitioncancel event - Web APIs
.ontransitioncancel for more information. ...
...er property GlobalEventHandlers.ontransitioncancel Examples This code gets an element that has a transition defined and adds a listener to the transitioncancel event: const transition = document.querySelector('.transition'); transition.
addEventListener('transitioncancel', () => { console.log('Transition canceled'); }); The same, but using the ontransitioncancel property instead of
addEventListener(): const transition = document.querySelector('.transition'); transition.ontransitioncancel = () => { console.log('Transition canceled'); }; Live example In the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition"></div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,...
...he transitionstart, transitionrun, transitioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
...And 2 more matches
Capabilities, constraints, and settings - Web APIs
n (described above) to display the actual settings that the browser decided upon after considering our constraints and the capabilities of the hardware. If an error occurs, we log it using the handleError() method that we'll look at farther down in this article. We also need to set up an event listener to watch for the "Start Video" button to be clicked: document.getElementById("startButton").
addEventListener("click", function() { startVideo(); }, false); Applying constraint set updates Next, we set up an event listener for the "Apply Constraints" button. If it's clicked and there's not already media in use, we call startVideo(), and let that function handle starting the stream with the specified settings in place. Otherwise, we follow these steps to apply the updated constraints to the already-a...
...e, applyConstraints() is called on the audio track (if there is one) to apply the new audio constraints. If this succeeds, the contents of the audio track's current settings box are updated based on the result of calling its getSettings() method. If an error occurs applying either set of constraints, handleError() is used to output a message into the log. ...
...Settings(), null, 2); }).catch(handleError); } if (audioTrack) { audioTrack.applyConstraints(audioConstraints).then(function() { audioSettingsText.value = JSON.stringify(audioTrack.getSettings(), null, 2); }).catch(handleError); } } }, false); Handling the stop button Then we set up the handler for the stop button. ...
...And 2 more matches
Pointer Lock API - Web APIs
ozExitPointerLock; // Attempt to unlock document.exitPointerLock(); pointerlockchange event When the Pointer lock state changes--for example, when calling requestPointerLock(), exitPointerLock(), the user pressing the ESC key, etc.--the pointerlockchange event is dispatched to the document. This is a simple event and contains no extra data. ...
...hanges--for example, when calling requestPointerLock(), exitPointerLock(), the user pressing the ESC key, etc.--the pointerlockchange event is dispatched to the document. This is a simple event and contains no extra data. ...
...is now locked'); // Do something useful in response } else { console.log('The pointer lock status is now unlocked'); // Do something useful in response } } pointerlockerror event When there is an error caused by calling requestPointerLock() or exitPointerLock(), the pointerlockerror event is dispatched to the document. This is a simple event and contains no extra data. document.
addEventListener('pointerlockerror', lockError, false); document.
addEventListener('mozpointerlockerror', lockError, false); function lockError(e) { alert("Pointer lock failed"); } Note: until Firefox 50 the above events were prefixed with moz in Firefox. Extensions to mouse events The Pointer lock API extends the normal MouseEvent interface with movement attributes. Two new attributes to mouse events--movem...
...And 2 more matches
Using the Web Animations API - Web APIs
nimation, so she gets bigger as the cupcake gets eaten. We can achieve this via the following function: var growAlice = function() { // Play Alice's animation. aliceChange.play(); // Play the cake's animation. nommingCake.play(); } When a user holds their mouse down or presses their finger on the cake on a touch screen, we can now call growAlice to make all the animations play: cake.
addEventListener("mousedown", growAlice, false); cake.
addEventListener("touchstart", growAlice, false); Other useful methods In addition to pausing and playing, we can use the following Animation methods: Animation.finish() skips to the end of the animation. Animation.cancel() aborts the animation and removes its effects. Animation.reverse() sets the animation's playback rate (Animation.playbackRate) to a ...
...ion.playbackRate) to a negative value so it runs backward. Let's take a look at playbackRate first -- a negative playbackRate will cause an animation to run in reverse. When Alice drinks from the bottle, she grows smaller. ...
... Let's take a look at playbackRate first -- a negative playbackRate will cause an animation to run in reverse. When Alice drinks from the bottle, she grows smaller. ...
...And 2 more matches
<input type="button"> - HTML: Hypertext Markup Language
. ...
... updateButton() { if (button.value === 'Start machine') { button.value = 'Stop machine'; paragraph.textContent = 'The machine has started!'; } else { button.value = 'Start machine'; paragraph.textContent = 'The machine is stopped.'; } } The script gets a reference to the HTMLInputElement object representing the <input> in the DOM, saving this refence in the variable button.
addEventListener() is then used to establish a function that will be run when click events occur on the button. Adding keyboard shortcuts to buttons Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button -- just as you would with any <input> for which it makes sense -- you ...
... In this example, s is specified as the access key (you'll need to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those). ...
...And 2 more matches
Communicating using "postMessage" - Archive of obsolete content
's on function. ...
... to prefer user-defined events is that as soon as you need to send more than one type of message, then both sending and receiving messages gets more complex. Suppose the content script wants to send mouseout events as well as mouseover. ...
... and implement a switch function in the receiver to dispatch the message: var pageModScript = "window.
addEventListener('mouseover', function(event) {" + " self.postMessage({" + " kind: 'mouseover'," + " element: event.target.toString()" + " });" + "}, false);" + "window.
addEventListener('mouseout', function(event) {" + " self.postMessage({" + " kind: 'mouseout'," + " element: event.target.toString()" + " });" + " }, false);" var pageMod = require('sdk/page-mod').PageMod({ include: ['*'], contentScript: pageModScript, onAttach: function(worker) { worker.on('messa...
...r) { worker.on('message', function(message) { switch(message.kind) { case 'mouseover': console.log('mouseover: ' + message.element); break; case 'mouseout': console.log('mouseout: ' + message.element); break; } }); } }); Implementing the same add-on with user-defined events is shorter and more readable: var pageModScript = "window.
addEventListener('mouseover', function(event) {" + " self.port.emit('mouseover', event.target.toString());" + "}, false);" + "window.
addEventListener('mouseout', function(event) {" + " self.port.emit('mouseout', event.target.toString());" + "}, false);"; var pageMod = require('sdk/page-mod').PageMod({ include:...
Content Scripts - Archive of obsolete content
to ...
... to send messages from one side to the other, use port.emit() to receive messages sent from the other side, use port.on() Messages are asynchronous: that is, the sender does not wa...
...// main.js var pageMods = require("sdk/page-mod"); var self = require("sdk/self"); var pageMod = pageMods.PageMod({ include: ['*'], contentScriptFile: self.data.url("content-script.js"), onAttach: startListening }); function startListening(worker) { worker.port.on('click', function(html) { worker.port.emit('warning', 'Do not click this again'); }); } // content-script.js window.
addEventListener('click', function(event) { self.port.emit('click', event.target.toString()); event.stopPropagation(); event.preventDefault(); }, false); self.port.on('warning', function(message) { window.alert(message); }); In the add-on above there are two messages: click is sent from the page-mod to the add-on, when the user clicks an element in the page warning sends a silly string back to the ...
...with the URL of the link on which the context menu was displayed. The URL is passed to the page-mod script in the CustomEvent. ...
remote/child - Archive of obsolete content
main things: access to web content loaded into this child process port mechanisms to communicate with the main process Interacting with web content To interact with web content, the sdk/remote/child module provides a frames property that's a list of all content frames loaded into this child process. Each frame then has a content property that's the top-level DOM window for the frame, and
addEventListener/removeEventListener functions that enable you to listen to DOM events dispatched by the frame. Communicating with the parent process To communicate with the parent process, the process, frames, and frame objects in sdk/remote/child have a port object that you can use to receive messages from, and send messages to, code in the parent. See the documentation for sdk/remote/parent for more details...
...ames in this process. Each element in this list is a Frame. Listen to attach and detach events to hear as frames are created and destroyed. Methods forEvery Calls the callback for every existing frame and any new frames created in the future. This is a shortcut for enumerating existing frames and then listening for attach events. getFrameForWindow Finds the frame for a top level DOM window.
addEventListener Adds an event listener for DOM events dispatched to any existing and future frames. removeEventListener Removes an event listener that was previously registered. Properties port An event emitter that sends and receives events from every frame in this process. Events attach Triggered when a new content frame is opened (for example, the user opened a new tab). The event listener gets a Fr...
... every frame in this process. Events attach Triggered when a new content frame is opened (for example, the user opened a new tab). The event listener gets a Frame object as an argument. ...
...This can include load and unload events from any content that is loaded in the frame. Listeners are automatically removed when this frame is destroyed. ...
Adding Events and Commands - Archive of obsolete content
<< PreviousNext >> Event handlers Just like with HTML, most JavaScript code execution is triggered by event handlers attached to DOM elements. The most commonly used event is the onload event, which is used in overlays and other windows to detect when the window has loaded and then run initialization code: // rest of overlay code goes here. window.
addEventListener( "load", function() { XulSchoolChrome.BrowserOverlay.init(); }, false); You can do something similar with the onunload event, to do any cleanup you may need. Please read Appendix A for recommendations on how to use the load event to initialize your add-on without having a negative performance impact on Firefox. Another way to attach event handlers, just like HTML, is to place the handler in the XUL code: <overlay id="xulschoolhell...
...ance impact on Firefox. Another way to attach event handlers, just like HTML, is to place the handler in the XUL code: <overlay id="xulschoolhello-browser-overlay" onload="XulSchoolChrome.BrowserOverlay.init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> We prefer the first method because it keeps a better separation of content and behavior. Also, note that the
addEventListener method receives the event name without the "on" prefix, while element attributes do have the prefix. There's a long list of events you can listen to, and which you use depend on the situation. Elements only implement the events that are relevant to them, but there are several events that are implemented for most elements. These are some notable events you should keep in mind: oncommand. This i...
...g, you should read about Event Propagation. In a nutshell, events propagate from the root of the DOM tree all the way down to the target element and then all the way up back to the root, in the capture and bubble phases, respectively. You can capture and cancel events during any of these phases, provided that they aren't canceled before they reach the point where you intended to capture them. The
addEventListener method allows you to control the phase where you want to handle an event, with the last argument of the function. In general, you should avoid adding event handlers in the capturing phase, or canceling events. This can lead to unexpected behavior for the user since most events have a default behavior associated to them. Custom events This is a very powerful tool that you should know, even if i...
...ivileges. Suppose your extension interacts with pages from a website, and you want some actions on this site to trigger actions in your extension. One way to solve this is to have the actions on the site to generate a custom event that can be easily recognized by your extension. You can capture the events in the XUL overlay, since they'll bubble all the way up: // in the overlay code. document.
addEventListener( "XSHelloGreetingEvent", function(aEvent) { /* do stuff*/ }, false); Be careful when doing this! You should at least validate the URL of the page that is generating the custom event, so that you know that it's coming from the right place. You should also avoid this kind of events to trigger actions that could be destructive to the user's data, because a malicious site could try to trigger the...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
just another script tag containing generated, remotely retrieved code, is generally not secure. It might be possible to execute any retrieved JSONP code in an unprivileged Sandbox (which is complicated!), but if you have a choice, just avoid JSONP altogether! Passing around functions/code as strings Often you'll want to pass functions or code to other functions, most notoriously setTimeout and
addEventListener. ...
...sible to execute any retrieved JSONP code in an unprivileged Sandbox (which is complicated!), but if you have a choice, just avoid JSONP altogether! Passing around functions/code as strings Often you'll want to pass functions or code to other functions, most notoriously setTimeout and
addEventListener. Often this is done passing around strings. ...
...attack!'); format_computer(); alert('done');", 100); As a general rule of thumb, just don't pass code around as strings and execute it by calling eval, setTimeout and friends. Alternative: Use (anonymous) functions You can always create a small anonymous function to pass around instead. Closures will ensure the code is still valid, even if your outer function already returned from execution. ...
...This is important to know in particular when you later want to call removeEventListener: You'll have to pass the resulting function from the first .bind() call. Calling .bind() again with removeEventListener will not work. ...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
ck me!</div> <script> function handleEvent(aEvent) { // if aEvent is null, means the Internet Explorer event model, // so get window.event. var myEvent = aEvent ? aEvent : window.event; } function onPageLoad(){ document.getElementById("myDiv").onclick = handleEvent; } </script> Mozilla fully supports the W3C standard way of attaching listeners to DOM nodes. You use the
addEventListener() and removeEventListener() methods, and have the benefit of being able to set multiple listeners for the same event type. Both methods require three parameters: the event type, a function reference, and a boolean denoting whether the listener should catch events in their capture phase. If the boolean is set to false, it will only catch bubbling events. W3C events have three phases: capturing, at...
..., setting the third parameter to false results in Internet Explorer-like behavior: <div id="myDiv">Click me!</div> <script> function handleEvent(aEvent) { // if aEvent is null, it is the Internet Explorer event model, // so get window.event. var myEvent = aEvent ? aEvent : window.event; } function onPageLoad() { var element = document.getElementById("myDiv"); element.
addEventListener("click", handleEvent, false); } </script> One advantage of
addEventListener() and removeEventListener() over setting properties is that you can have multiple event listeners for the same event, each calling another function. Thus, to remove an event listener requires all three parameters be the same as the ones you use when adding the listener. Mozilla does not support Internet Explorer's me...
...her function. Thus, to remove an event listener requires all three parameters be the same as the ones you use when adding the listener. Mozilla does not support Internet Explorer's method of converting <script> tags into event handlers, which extends <script> with for and event attributes (see Table 5). It also does not support the attachEvent and detachEvent methods. ...
...pport Internet Explorer's method of converting <script> tags into event handlers, which extends <script> with for and event attributes (see Table 5). It also does not support the attachEvent and detachEvent methods. Instead, you should use the
addEventListener and removeEventListener methods. Internet Explorer does not support the W3C events specification. However, IE can be remediated to support
addEventListener and removeEventListener. Table 5. Event method differences between Mozilla and Internet Explorer Internet Explorer Method Mozilla Method Description attachEvent(aEventType, aFunctionReference)
addEventListener(aEventType, aFunctionReference, aUseCapture) Adds an event listener to a DOM element. detachEvent(aEventType, aFunctionReference) removeEventList...
Toolbar customization events - Archive of obsolete content
None of these events contain any data; if you need details, you'll need to look at the toolbar. beforecustomization This event is delivered when the user starts the toolbar customization process; for example, by right-clicking on a toolbar and choosing "Customize". customizationchange This event is delivered when the user makes a change to a toolbar while editing the toolbars, either by dragging an item to the toolbar or by dragging an item out of it. ...
...by dragging an item to the toolbar or by dragging an item out of it. aftercustomization This event is delivered when the user closes the toolbar customization panel. In all cases, the event.target is the toolbox being customized. You can look at the contents of that element and its children to determine what changes were made. Example In this example, we watch for toolbar changes. ...
... aftercustomization This event is delivered when the user closes the toolbar customization panel. In all cases, the event.target is the toolbox being customized. You can look at the contents of that element and its children to determine what changes were made. Example In this example, we watch for toolbar changes. ...
...s the toolbar customization panel. In all cases, the event.target is the toolbox being customized. You can look at the contents of that element and its children to determine what changes were made. Example In this example, we watch for toolbar changes. ...
Adding Event Handlers - Archive of obsolete content
menu. The command event is a useful event since it automatically handles different ways of activating the element. For example, the command event will occur regardless of whether the user uses the mouse to click a button, or presses the Enter key. There are two ways to attach an event listener to an element. First, by using an attribute with a script as its value. Second, by calling an element's
addEventListener method. The former may only handle bubbling events but tends to be simpler to write. The latter can handle events at any phase and may also be used to attach multiple listeners for an event to an element. Using the attribute form is more common for most events. Attribute Event Listeners To use the attribute form, place an attribute on the element where you want the event listener to be, the nam...
...dow.close();"/> Two handlers have been added here. The oncommand attribute was added to the Close menu item. By using this handler, the user will be able to close the window by clicking the menu item with the mouse or by selecting it with the keyboard. The oncommand handler was also added to the Cancel button. ...
...The first argument is the name of the event to listen to. ...
...The first argument is the name of the event to listen to. ...
XUL Event Propagation - Archive of obsolete content
s. In the diagram above, the alert dialog invoked by the menuitem itself is not displayed, since the root window element has used event capture to handle the event itself. In another example, an onload event handler for a XUL window can register a box element to capture all the click events that are raised from its child elements: var bbox = document.getElementById("bigbox"); if (bbox) bbox.
addEventListener("click", function() { alert('captured'); }, true); ... <box id="bigbox"> <menu value="File"> <menupopup> <menuitem value="New" onclick="alert('not captured')" /> ... <menupopup> </menu> </box> Adding an Event Listener In order to take advantage of event capturing (or event bubbling with elements that do not already have event listeners), you must add an event listen...
...<menupopup> <menuitem value="New" onclick="alert('not captured')" /> ... <menupopup> </menu> </box> Adding an Event Listener In order to take advantage of event capturing (or event bubbling with elements that do not already have event listeners), you must add an event listener to the element that wants to capture events taking place below it. Any XUL element may use the DOM
addEventListener method to register itself to capture events. The syntax for this in XUL is as follows: element = document.getElementById("id of the element"); element.
addEventListener(event name, event handler function, whether to register a capturing listener); The event handler code argument can be in-line code or a function. The last boolean parameter specifies whether the event listener wants to use event...
...ntById("id of the element"); element.
addEventListener(event name, event handler function, whether to register a capturing listener); The event handler code argument can be in-line code or a function. The last boolean parameter specifies whether the event listener wants to use event capturing, or be registered to listen for events that bubble up the hiearchy normally. Note: The DOM provides the
addEventListener method for creating event listeners on nodes that do not otherwise supply them. But in XUL, almost every element includes an "oncommand" event listener attribute for getting events. ...
...n. The last boolean parameter specifies whether the event listener wants to use event capturing, or be registered to listen for events that bubble up the hiearchy normally. Note: The DOM provides the
addEventListener method for creating event listeners on nodes that do not otherwise supply them. But in XUL, almost every element includes an "oncommand" event listener attribute for getting events.
addEventListener is the way to register event listeners for events other than the generalized "command" event, and the way to register a particular element for event capture, which preempts the regular flow of events. Original author: Ian Oeschger Other Documents: W3C DOM Events, Mozilla XUL Events Original Document Information Author(s): Ian Oeschger Last Updated Date: January 18, 2002 Copyright Informa...
Styling links - Learn web development
mlCode = htmlInput.value; var cssCode = cssInput.value; var output = document.querySelector(".output"); var solution = document.getElementById("solution"); var styleElem = document.createElement('style'); var headElem = document.querySelector('head'); headElem.appendChild(styleElem); function drawOutput() { output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; } reset.
addEventListener("click", function() { htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput(); }); solution.
addEventListener("click", function() { htmlInput.value = htmlCode; cssInput.value = 'p {\n font-size: 1.2rem;\n font-family: sans-serif;\n line-height: 1.4;\n}\n\na {\n outline: none;\n text-decoration: none;\n padding: 2px 1px 0;\n}\n\na:link {\n color: #265301;\n}\n\na:visite...
...Let's look at a really simple example that adds an icon to external links (links that lead to other sites.) Such an icon usuall...
...Let's look at a really simple example that adds an icon to external links (links that lead to other sites.) Such an icon usually looks like a little arrow pointing out of a bo...
...Let's look at a really simple example that adds an icon to external links (links that lead to other sites.) Such an icon usually looks like a little arrow pointing out of a box -- for this example, we'll use this great ex...
Client-side form validation - Learn web development
Inside the contained code, we check whether the email inp...
...Script that implements the custom error validation. // There are many ways to pick a DOM node; here we get the form itself and the email // input box, as well as the span element into which we will place the error message. const form = document.getElementsByTagName('form')[0]; const email = document.getElementById('mail'); const emailError = document.querySelector('#mail + span.error'); email.
addEventListener('input', function (event) { // Each time the user types something, we check if the // form fields are valid. if (email.validity.valid) { // In case there is an error message visible, if the field // is valid, we remove the error message. emailError.innerHTML = ''; // Reset the content of the message emailError.className = 'error'; // Reset the visual state of the message ...
...elds are valid. if (email.validity.valid) { // In case there is an error message visible, if the field // is valid, we remove the error message. ...
... node in the DOM // This is dangerous because you can easily build an infinite loop. // In modern browsers, you should prefer using element.nextElementSibling let error = email; while ((error = error.nextSibling).nodeType != 1); // As per the HTML5 Specification const emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; // Many legacy browsers do not support the
addEventListener method. // Here is a simple way to handle this; it's far from the only one. function addEvent(element, event, callback) { let previousEventCallBack = element["on"+event]; element["on"+event] = function (e) { const output = callback(e); // A callback that returns `false` stops the callback chain // and interrupts the execution of the event callback. if (output === false) retur...
Example 4 - Learn web development
ector('.value'); var optionList = select.querySelectorAll('.option'); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); }; function getIndex(select) { var nativeWidget = select.previousElementSibling; 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) { opti...
...oad", 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) { activeSelect(select, selectList); }); select.
addEventListener('blur', function (event) { deactivateSelect(select); }); }); }); window.
...('mouseover', function () { highlightOption(select, option); }); }); select.
addEventListener('click', function (event) { toggleOptList(select); }); select.
addEventListener('focus', function (event) { activeSelect(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...
...'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); if (event.keyCode === 27) { deactivateSelect(select); } if (event.keyCode === 40 && index < length - 1) { index++; } if (event.keyCode === 38 && index > 0) { index--;...
Images in HTML - Learn web development
: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Sho...
...ue = userEntry; solution.value = 'Show solution'; } updateCode(); }); var htmlSolution = '<img src="https://udn.realityripple.com/samples/ec/5a13bd14f6.jpg"\n alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"\n width="200"\n height="171"\n title="A T-Rex on display in the Manchester University Museum">'; var solutionEntry = htmlSolution; textarea.
addEventListener('input', updateCode); window.
addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur(); } }; function insertAtCaret(text) { var scrollPos = textarea.scrollT...
...: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getElementById('code'); var reset = document.getElementById('reset'); var solution = document.getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Sho...
...how solution'; } updateCode(); }); var htmlSolution = '<figure>\n <img src="https://udn.realityripple.com/samples/ec/5a13bd14f6.jpg"\n alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"\n width="200"\n height="171">\n <figcaption>A T-Rex on display in the Manchester University Museum</figcaption>\n</figure>'; var solutionEntry = htmlSolution; textarea.
addEventListener('input', updateCode); window.
addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur(); } }; function insertAtCaret(text) { var scrollPos = textarea.scrollT...
Third-party APIs - Learn web development
he service at the correct URL. Find the following line: let key = ' ... '; Replace the existing API key with the actual API key you got in the previous section. Add the following line to your JavaScript, below the "// Event listeners to control the functionality" comment. This runs a function called submitSearch() when the form is submitted (the button is pressed). ...
...the page URL parameter. This works because the NYTimes API only returns 10 results at a time -- if more than 10 results are available, it will return the first 10 (0-9) if the page URL parameter is set to 0 (or not included at all -- 0 is the default value), the next 10 (10-19) if it is set to 1, and so on. This allows us to write a simplistic pagination function easily. ...
...if the page URL parameter is set to 0 (or not included at all -- 0 is the default value), the next 10 (10-19) if it is set to 1, and so on. This allows us to write a simplistic pagination function easily. ...
...luded at all -- 0 is the default value), the next 10 (10-19) if it is set to 1, and so on. This allows us to write a simplistic pagination function easily. ...
Arrays - Learn web development
le-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show ...
...+) {\n let subArray = products[i].split(\':\');\n let name = subArray[0];\n let price = Number(subArray[1]);\n total += price;\n let itemText = name + \' -- $\' + price;\n\n let listItem = document.createElement(\'li\');\n listItem.textContent = itemText;\n list.appendChild(listItem);\n}\n\ntotalBox.textContent = \'Total: $\' + total.toFixed(2);'; let solutionEntry = jsSolution; textarea.
addEventListener('input', updateCode); window.
addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur(); } }; function insertAtCaret(text) { const scrollPos = textarea.scro...
...y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show ...
...earchInput.value);\n\n list.innerHTML = \'\';\n\n for(let i = 0; i < myHistory.length; i++) {\n itemText = myHistory[i];\n const listItem = document.createElement(\'li\');\n listItem.textContent = itemText;\n list.appendChild(listItem);\n }\n\n if(myHistory.length >= 5) {\n myHistory.pop();\n }\n\n searchInput.value = \'\';\n searchInput.focus();\n }\n}'; let solutionEntry = jsSolution; textarea.
addEventListener('input', updateCode); window.
addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur(); } }; function insertAtCaret(text) { const scrollPos = textarea.scrol...
What went wrong? Troubleshooting JavaScript - Learn web development
ssage along the following lines: This is a pretty easy error to track down, and the browser gives you several useful bits of information to help you out (the screenshot above is from Firefox, but other browsers provide similar information). From left to right, we've got: A red "x" to indicate that this is an error. An error message to indicate what's gone wrong: "TypeError: guessSubmit.
addeventListener is not a function" A "Learn More" link that links through to an MDN page that explains what this error means in greater detail. The name of the JavaScript file, which links through to the Debugger tab of the developer tools. If you follow this link, you'll see the exact line where the error is highlighted. The line number where the error is, and the character number in that line where th...
...t file, which links through to the Debugger tab of the developer tools. If you follow this link, you'll see the exact line where the error is highlighted. The line number where the error is, and the character number in that line where the error is first seen. In this case, we've got line 86, character number 3. If we look at line 86 in our code editor, we'll find this line: guessSubmit.
addeventListener('click', checkGuess); The error message says "guessSubmit.
addeventListener is not a function", which means that the function we're calling is not recognized by the JavaScript interpreter. Often, this error message actually means that we've spelled something wrong. If you are not sure of the correct spelling of a piece of syntax, it is often good to look up the feature on MDN. The best way to d...
...t recognized by the JavaScript interpreter. Often, this error message actually means that we've spelled something wrong. If you are not sure of the correct spelling of a piece of syntax, it is often good to look up the feature on MDN. The best way to do this currently is to search for "mdn name-of-feature" with your favorite search engine. Here's a shortcut to save you some time in this instance:
addEventListener(). So, looking at this page, the error appears to be that we've spelled the function name wrong! Remember that JavaScript is case sensitive, so any slight difference in spelling or casing will cause an error. Changing
addeventListener to
addEventListener should fix this. Do this now. Note: See our TypeError: "x" is not a function reference page for more details about this error. Syntax erro...
...re details about this error. Syntax errors round three Now if you try playing the game through again, you should get more success -- the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of guesses. At that point, the game fails again, and the same error is spat out that we got at the beginning -- "TypeError: resetButton.
addeventListener is not a function"! However, this time it's listed as coming from line 94. Looking at line number 94, it is easy to see that we've made the same mistake here. We again just need to change
addeventListener to .
addEventListener. Do this now. A logic error At this point, the game should play through fine, however after playing through a few times you'll undoubtedly notice that the "random" numbe...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
d, this behavior will be confusing at best. We'd also like to add some usability features, like disabling the Save button when required fields are empty, giving focus to certain HTML elements or auto-selecting contents when a text input receives focus. To implement all these features we'll need programmatic access to DOM nodes to run functions like focus() and select(). We will also have to use
addEventListener() and removeEventListener() to run specific tasks when the control receives focus. The problem is that all these DOM nodes are dynamically created by Svelte at runtime. So we'll have to wait for them to be created and added to the DOM in order to use them. To do so, we'll have to learn about the component lifecycle to understand when we can access them -- more on this later. Creating a NewTodo ...
... easily reused on any HTML <input> and applied in a declarative way. We will use this requirement as an excuse to show a very powerful feature that Svelte provides us to add functionality to regular HTML elements: actions. To select the text of a DOM input node we have to call select(). To get this function called whenever the node gets focused, we need an event listener along these lines: node.
addEventListener('focus', event => node.select()). And, in order to avoid memory leaks, we should also call the removeEventListener() function when the node is destroyed. Note: All this is just standard WebAPI functionality; nothing here is specific to Svelte. We could achieve all this in our Todo component whenever we add or remove the <input> from the DOM, but we would have to be very careful to add the ev...
...on't leave any memory leak behind. Let's create the function selectOnFocus(). ...
...just extract it to a file and use it from there. Create a new file, actions.js, inside the src folder. ...
AudioTrackList: change event - Web APIs
The change event is fired when an audio track is enabled or disabled, for example by changing the track's enabled property. ...
... The change event is fired when an audio track is enabled or disabled, for example by changing the track's enabled property. ...
...nt handler property onchange Examples Using
addEventListener(): const videoElement = document.querySelector('video'); videoElement.audioTracks.
addEventListener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `enabled` will trigger the `change` event const toggleTrackButton = document.querySelector('.toggle-track'); toggleTrackButton.
addEventListener('click', () => { const track = videoElement.audioTracks[0]; track.enabled = !track.enabled; }); Using the onchange event handler property: const videoElement = document.querySelector('video'); videoElement.audioTracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; // changing the value of `enabled` will trigger the `change` event const toggleTrackButton = docum...
... Living Standard ...
Battery Status API - Web APIs
charging) and for changes to the battery level and timing. This is done by listening for the chargingchange, levelchange, chargingtimechange, dischargingtimechange events. ...
...tery) { function updateAllBatteryInfo(){ updateChargeInfo(); updateLevelInfo(); updateChargingInfo(); updateDischargingInfo(); } updateAllBatteryInfo(); battery.
addEventListener('chargingchange', function(){ updateChargeInfo(); }); function updateChargeInfo(){ console.log("Battery charging? " + (battery.charging ? ...
...ener('chargingchange', function(){ updateChargeInfo(); }); function updateChargeInfo(){ console.log("Battery charging? " + (battery.charging ? ...
... Specifications Specification Status Comment Battery Status API Candidate Recommendation Initial de...
Drawing text - Web APIs
measureText() Returns a Te...
... measureText() Returns a TextMetrics object containing the width, in pixels, that the specified text will be when dra...
... measureText() Returns a TextMetrics object containing the width, in pixels, that the specified text will be when drawn in the current text style. The following code snippet shows how you...
...('reset'); var edit = document.getElementById('edit'); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.
addEventListener('click', function() { textarea.value = code; drawCanvas(); }); edit.
addEventListener('click', function() { textarea.focus(); }) textarea.
addEventListener('input', drawCanvas); window.
addEventListener('load', drawCanvas); Advanced text measurements In the case you need to obtain more details about the text, the following method allows you to measure it. measureText() Returns a TextMetrics object containing the width, in pixels, that the specified text will be when drawn in the current text style. The following code snippet shows how you can measure a text and get its width. functi...
Pixel manipulation with canvas - Web APIs
For example, to paint the entire image represented by myImageData to the...
... We get the position of the mouse and crop an image of 5 pixels left and above...
... We get the position of the mouse and crop an image of 5 pixels left and above to 5 pixels right and below. Then we copy that one over to another canvas and resize the image to the size we w...
...none'; var zoomctx = document.getElementById('zoom').getContext('2d'); var smoothbtn = document.getElementById('smoothbtn'); var toggleSmoothing = function(event) { zoomctx.imageSmoothingEnabled = this.checked; zoomctx.mozImageSmoothingEnabled = this.checked; zoomctx.webkitImageSmoothingEnabled = this.checked; zoomctx.msImageSmoothingEnabled = this.checked; }; smoothbtn.
addEventListener('change', toggleSmoothing); var zoom = function(event) { var x = event.layerX; var y = event.layerY; zoomctx.drawImage(canvas, Math.min(Math.max(0, x - 5), img.width - 10), Math.min(Math.max(0, y - 5), img.height - 10), 10, 10, 0, 0, 200, 200); }; canvas.addEventListen...
Document: DOMContentLoaded event - Web APIs
propriate. Synchronous JavaScript pauses parsing of the DOM. If you want the DOM to get parsed as fast as possible after the user has requested the page, you can make your JavaScript asynchronous and optimize loading of stylesheets. If loaded as usual, stylesheets slow down DOM parsing as they're loaded in parallel, "stealing" traffic from the main HTML document. ...
...ge, you can make your JavaScript asynchronous and optimize loading of stylesheets. If loaded as usual, stylesheets slow down DOM parsing as they're loaded in parallel, "stealing" traffic from the main HTML document. Examples Basic usage document.
addEventListener('DOMContentLoaded', (event) => { console.log('DOM fully loaded and parsed'); }); Delaying DOMContentLoaded <script> document.
addEventListener('DOMContentLoaded', (event) => { console.log('DOM fully loaded and parsed'); }); for( let i = 0; i < 1000000000; i++) {} // This synchronous script is going to delay parsing of the DOM, // so the DOMContentLoaded event is going to launch later. </script> Checking whether loading is already complete DOMContentLoaded may fire before your script has a chance to run, so it is wise to che...
...y parsing of the DOM, // so the DOMContentLoaded event is going to launch later. </script> Checking whether loading is already complete DOMContentLoaded may fire before your script has a chance to run, so it is wise to check before adding a listener. ...
...late-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } JS const log = document.querySelector('.event-log-contents'); const reload = document.querySelector('#reload'); reload.
addEventListener('click', () => { log.textContent =''; window.setTimeout(() => { window.location.reload(true); }, 200); }); window.
addEventListener('load', (event) => { log.textContent = log.textContent + 'load\n'; }); document.
addEventListener('readystatechange', (event) => { log.textContent = log.textContent + `readystate: ${document.readyState}\n`; }); document.
addEventListener('DOMConte...
Document: drag event - Web APIs
ggable </div> </div> <div class="dropzone"></div> <div class="dropzone"></div> <div class="dropzone"></div> CSS #draggable { width: 200px; height: 20px; text-align: center; background: white; } .dropzone { width: 200px; height: 20px; background: blueviolet; margin-bottom: 10px; padding: 10px; } JavaScript var dragged; /* events fired on the draggable target */ document.
addEventListener("drag", function(event) { }, false); document.
addEventListener("dragstart", function(event) { // store a ref. on the dragged elem dragged = event.target; // make it half transparent event.target.style.opacity = .5; }, false); document.
addEventListener("dragend", function(event) { // reset the transparency event.target.style.opacity = ""; }, false); /* events fired on the drop targ...
...n(event) { }, false); document.
addEventListener("dragstart", function(event) { // store a ref. ...
...= event.target; // make it half transparent event.target.style.opacity = .5; }, false); document.
addEventListener("dragend", function(event) { // reset the transparency event.target.style.opacity = ""; }, false); /* events fired on the drop targets */ document.
addEventListener("dragover", function(event) { // prevent default to allow drop event.preventDefault(); }, false); document.
addEventListener("dragenter", function(event) { // highlight potential drop target when the draggable element enters it if (event.target.className == "dropzone") { event.target.style.background = "purple"; } }, false); document.
addEventListener("dragleave", function(event) { // reset background of potential drop target when the draggable element leaves it if (event.target.className == "dropzone") ...
... when the draggable element enters it if (event.target.className == "dropzone") { event.target.style.background = "purple"; } }, false); document.
addEventListener("dragleave", function(event) { // reset background of potential drop target when the draggable element leaves it if (event.target.className == "dropzone") { event.target.style.background = ""; } }, false); document.
addEventListener("drop", function(event) { // prevent default action (open as link for some elements) event.preventDefault(); // move dragged elem to the selected drop target if (event.target.className == "dropzone") { event.target.style.background = ""; dragged.parentNode.removeChild( dragged ); event.target.appendChild( dragged ); } }, false); Specifications Specification S...
Element: blur event - Web APIs
HTML <form id="form"> <input type="text" ...
... HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> JavaScript ...
...ument.querySelector('input[type="password"]'); password.
addEventListener('focus', (event) => { event.target.style.background = 'pink'; }); password.
addEventListener('blur', (event) => { event.target.style.background = ''; }); Result Event delegation There are two ways of implementing event delegation for this event: by using the focusout event, or by setting the useCapture parameter of
addEventListener() to true. ...
... = ''; }); Result Event delegation There are two ways of implementing event delegation for this event: by using the focusout event, or by setting the useCapture parameter of
addEventListener() to true. HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> JavaScript const form = document.getElementById('form'); form.
addEventListener('focus', (event) => { event.target.style.background = 'pink'; }, true); form.
addEventListener('blur', (event) => { event.target.style.background = ''; }, true); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Document Object Model (DOM) Level 3 Events Specification Obsolete ...
Element: focus event - Web APIs
HTML <form id="form"> <input type="text" p...
... HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> JavaScript ...
...cument.querySelector('input[type="password"]'); password.
addEventListener('focus', (event) => { event.target.style.background = 'pink'; }); password.
addEventListener('blur', (event) => { event.target.style.background = ''; }); Result Event delegation There are two ways of implementing event delegation for this event: by using the focusin event, or by setting the useCapture parameter of
addEventListener() to true. ...
...d = ''; }); Result Event delegation There are two ways of implementing event delegation for this event: by using the focusin event, or by setting the useCapture parameter of
addEventListener() to true. HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> JavaScript const form = document.getElementById('form'); form.
addEventListener('focus', (event) => { event.target.style.background = 'pink'; }, true); form.
addEventListener('blur', (event) => { event.target.style.background = ''; }, true); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Document Object Model (DOM) Level 3 Events Specification Obsolete ...
Element.innerHTML - Web APIs
<div class="box"> <div><strong>Log:</strong></div> <div class="log"></div> </div> The <div> with the class "box" is just a conta...
... <div class="box"> <div><strong>Log:</strong></div> <div class="log"></div> </div> The <div> with the class "box" is just a container for layout purposes, presenting the contents...
... <div class="box"> <div><strong>Log:</strong></div> <div class="log"></div> </div> The <div> with the class "box" is just a container for layout purposes, presenting the contents with a box around it. The <div> whose class is...
...pe + "</strong> at <em>" + event.clientX + ", " + event.clientY + "</em>"; log(msg); } Then we use this as the event handler for a number of mouse events on the box that contains our log: var boxElem = document.querySelector(".box"); boxElem.
addEventListener("mousedown", logEvent); boxElem.
addEventListener("mouseup", logEvent); boxElem.
addEventListener("click", logEvent); boxElem.
addEventListener("mouseenter", logEvent); boxElem.
addEventListener("mouseleave", logEvent); HTML The HTML is quite simple for our example. <div class="box"> <div><strong>Log:</strong></div> <div class="log"></div> </div> The <div> with the class "box" is just a container for layout purposes, presenting the contents with a box around it. The <div> whose class is "log" is the container for the log text itse...
HTMLElement: transitionend event - Web APIs
sition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. If the transitioncancel event is fired, the transitionend event will not fire. ...
...he transitionstart, transitionrun, transitioncancel and transitionend events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
... cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ...
...ition end event to fire, stay hovered over the transition until the transition ends. const message = document.querySelector('.message'); const el = document.querySelector('.transition'); el.
addEventListener('transitionrun', function() { message.textContent = 'transitionrun fired'; }); el.
addEventListener('transitionstart', function() { message.textContent = 'transitionstart fired'; }); el.
addEventListener('transitioncancel', function() { message.textContent = 'transitioncancel fired'; }); el.
addEventListener('transitionend', function() { message.textContent = 'transitionend fired'; }); The transitionend event is fired in both directions: when the box finishes turning and the opacity hits 0 or 1, depending on the direction. If there is no transition delay or duration, if both are 0s or ne...
KeyboardEvent.key - Web APIs
t-flex: 1; flex: 1; } #test-target { display: block; width: 100%; margin-bottom: 10px; } JavaScript let textarea = document.getElementById('test-target'), consoleLog = document.getElementById('console-log'), btnClearConsole = document.getElementById('btn-clear-console'); function logMessage(message) { document.getElementById("console-log").innerHTML += message + "<br>"; } textarea.
addEventListener('keydown', (e) => { if (!e.repeat) logMessage(`Key "${e.key}" pressed [event: keydown]`); else logMessage(`Key "${e.key}" repeating [event: keydown]`); }); textarea.
addEventListener('beforeinput', (e) => { logMessage(`Key "${e.data}" about to be input [event: beforeinput]`); }); textarea.
addEventListener('input', (e) => { logMessage(`Key "${e.data}" input [event: input]`); }...
...e) => { if (!e.repeat) logMessage(`Key "${e.key}" pressed [event: keydown]`); else logMessage(`Key "${e.key}" repeating [event: keydown]`); }); textarea.
addEventListener('beforeinput', (e) => { logMessage(`Key "${e.data}" about to be input [event: beforeinput]`); }); textarea.
addEventListener('input', (e) => { logMessage(`Key "${e.data}" input [event: input]`); }); textarea.
addEventListener('keyup', (e) => { logMessage(`Key "${e.key}" released [event: keyup]`); }); btnClearConsole.
addEventListener('click', (e) => { let child = consoleLog.firstChild; while (child) { consoleLog.removeChild(child); child = consoleLog.firstChild; } }); Result Note: On browsers that don't fully implement the InputEvent interface which is used for the beforeinput and input events, you...
...of the key 2 key press is now "2" because the modifier shift key is no longer active. The same goes for the InputEvent.data property of the beforeinput and input events. As we finally release the key 2, a keyup event is fired but the key property will be set to the string value 2 for both keyboard layouts because the modifier shift key is no longer active. ...
...ard layouts because the modifier shift key is no longer active. Example This example uses EventTarget.
addEventListener() to listen for keydown events. When they occur, the key's value is checked to see if it's one of the keys the code is interested in, and if it is, it gets processed in some way (possibly by steering a spacecraft, perhaps by changing the selected cell in a spreadsheet). window.
addEventListener("keydown", function (event) { if (event.defaultPrevented) { return; // Do nothing if the event was already processed } switch (event.key) { case "Down": // IE/Edge specific value case "ArrowDown": // Do something for "down arrow" key press. break; case "Up": // IE/Edge specific value case "ArrowUp": // Do something for "up arrow" key press. break...
MouseEvent.relatedTarget - Web APIs
event.relatedTarget.id : "unknown"; mouseoutLog.innerText = `\nfrom ${event.target.id} into ${related} ${mouseoutLog.innerText}`; } function overListener...
...event.relatedTarget.id : "unknown"; mouseoutLog.innerText = `\nfrom ${event.target.id} into ${related} ${mouseoutLog.innerText}`; } function overListener(event) { let related = event.relatedTarget ? e...
...event.relatedTarget.id : "unknown"; mouseoutLog.innerText = `\nfrom ${event.target.id} into ${related} ${mouseoutLog.innerText}`; } function overListener(event) { let related = event.relatedTarget ? event.relatedTarget.id : "unknown"; log.innerT...
...{ flex-grow: 1; background: blue; } #log { max-height: 120px; overflow-y: scroll; } JavaScript const mouseoutLog = document.getElementById('log'), red = document.getElementById('red'), blue = document.getElementById('blue'); red.
addEventListener('mouseover', overListener); red.
addEventListener('mouseout', outListener); blue.
addEventListener('mouseover', overListener); blue.
addEventListener('mouseout', outListener); function outListener(event) { let related = event.relatedTarget ? event.relatedTarget.id : "unknown"; mouseoutLog.innerText = `\nfrom ${event.target.id} into ${related} ${mouseoutLog.innerText}`; } function overListener(event) { let related = event.relatedTarget ? event.relatedTarget.id : "unknown"; log.innerText = `\ninto ${event.target.id} from ${related} $...
Online and offline events - Web APIs
nline and offline mode. Additionally, the events bubble up from document.body, to document, ending at window. Both events are non-cancellable (you can't prevent the user from coming online, or going offline). Firefox 41 fires these events when the OS reports a change in network connectivity on Windows, Linux, and OS X. You can register listeners for these events in a few familiar ways: using
addEventListener on the window, document, or document.body by setting the .ononline or .onoffline properties on document or document.body to a JavaScript Function object. (Note: using window.ononline or window.onoffline will not work for compatibility reasons.) by specifying ononline="..." or onoffline="..." attributes on the <body> tag in the HTML markup. Example There's a simple test case that you can run ...
... (Note: using window.ononline or window.onoffline will not work for compatibility reasons.) by specifying ononline="..." or onoffline="..." attributes on the <body> tag in the HTML markup. Example There's a simple test case that you can run to verify that the events are working (does not work in Chrome due to attaching the event listener to document.body). ...
..., function() { var status = document.getElementById("status"); var log = document.getElementById("log"); function updateOnlineStatus(event) { var condition = navigator.onLine ? ...
...tus"); var log = document.getElementById("log"); function updateOnlineStatus(event) { var condition = navigator.onLine ? ...
Using the Notifications API - Web APIs
to the user and user agent. The dismissal may also happen at the operating system level and users should remain in control of this. Old versions of Chrome didn't remove notifications automatically so you can do so after a setTimeout() only for those legacy versions in order to not remove notifications from notification trays on other browsers. var n = new Notification('My Great Song'); document.
addEventListener('visibilitychange', function() { if (document.visibilityState === 'visible') { // The tab has become visible so clear the now-stale Notification. n.close(); } }); Note: This API shouldn't be used just to have the notification removed from the screen after a fixed delay (on modern browsers) since this method will also remove the notification from any notification tray, preventing us...
...notification is closed. error Triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason. show Triggered when the notification is displayed to the user. These events can be tracked using the onclick, onclose, onerror, and onshow handlers. Because Notification also inherits from EventTarget, it's possible to use the
addEventListener() method on it. Replacing existing notifications It is usually undesirable for a user to receive a lot of notifications in a short space of time -- for example, what if a messenger application notified a user for each incoming message, and they were being sent a lot? To avoid spamming the user with too many notifications, it's possible to modify the pending notifications queue, replacing single...
...tification already has the same tag and has not been displayed yet, the new notification replaces that previous notification. If the notification with the same tag has already been displayed, the previous notification is closed and the new one is displayed. ...
... var interval = window.setInterval(function () { // Th...
Page Visibility API - Web APIs
// ...
...visibilitychange"; } var videoElement = document.getElementById("videoElement"); // If the page is hidden, pause the video; // if the page is shown, play the video function handleVisibilityChange() { if (document[hidden]) { videoElement.pause(); } else { videoElement.play(); } } // Warn if the browser doesn't support
addEventListener or the Page Visibility API if (typeof document.
addEventListener === "undefined" || hidden === undefined) { console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API."); } else { // Handle page visibility change document.
addEventListener(visibilityChange, handleVisibilityChange, false); // When the video pauses, set the title. // This shows the paused videoElement.
addEventListener("pause", f...
... Firefox, that supports the Page Visibility API."); } else { // Handle page visibility change document.
addEventListener(visibilityChange, handleVisibilityChange, false); // When the video pauses, set the title. // This shows the paused videoElement.
addEventListener("pause", function(){ document.title = 'Paused'; }, false); // When the video plays, set the title. videoElement.
addEventListener("play", function(){ document.title = 'Playing'; }, false); } Properties added to the Document interface The Page Visibility API adds the following properties to the Document interface: Document.hidden Read only Returns true if the page is in a state considered to be hidden to the user, and false otherwise. Document.visibilityState Read only A DOMString indicating the document's ...
...ing unloaded from memory. Note: Not all browsers support the unloaded value. Document.onvisibilitychange An EventListener providing the code to be called when the visibilitychange event is fired. //startSimulation and pauseSimulation defined elsewhere function handleVisibilityChange() { if (document.hidden) { pauseSimulation(); } else { startSimulation(); } } document.
addEventListener("visibilitychange", handleVisibilityChange, false); Specifications Specification Status Comment Page Visibility (Second Edition) Recommendation Initial definition. ...
Sensor APIs - Web APIs
e sensor type isn't supported by the device. If a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions. ...
... if (error.name === 'SecurityError') { // See the note above about feature policy. ...
...tructor. The option is a number that specifies the number of readings per second. A whole number or decimal may be used, the latter for frequencies less than a second. The actual reading frequency depends device hardware and consequently may be less than requested. The following example illustrates this using the Magnetometer sensor. ...
...e less than requested. The following example illustrates this using the Magnetometer sensor. let magSensor = new Magnetometer({frequency: 60}); magSensor.
addEventListener('reading', e => { console.log("Magnetic field along the X-axis " + magSensor.x); console.log("Magnetic field along the Y-axis " + magSensor.y); console.log("Magnetic field along the Z-axis " + magSensor.z); }) magSensor.
addEventListener('error', event => { console.log(event.error.name, event.error.message); }) magSensor.start(); Interfaces AbsoluteOrientationSensorSecure context Describes the device's physical orientation in relation to the Earth's reference coordinate system. AccelerometerSecure context Provides the acceleration applied to the device along all three axes. AmbientLightSensorSecure context Returns the...
SubtleCrypto.exportKey() - Web APIs
ment.querySelector(".exported-key"); exportKeyOutput.textContent = `[${exportedKeyBuffer}]`; } /* Generate an encrypt/decrypt secret key, then set up an event listener on the "Export" button. */ window.crypto.subtle.generateKey( { name: "AES-GCM", length: 256, }, true, ["encrypt", "decrypt"] ).then((key) => { const exportButton = document.querySelector(".raw"); exportButton.
addEventListener("click", () => { exportCryptoKey(key); }); }); PKCS #8 export This example exports an RSA private signing key as a PKCS #8 object. The exported key is then PEM-encoded. See the complete code on GitHub. /* Convert an ArrayBuffer into a string from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String */ function ab2str(buf) { return String.fro...
...nt listener on the "Export" button. */ window.crypto.subtle.generateKey( { name: "RSA-PSS", // Consider using a 4096-bit key for systems that require long-term security modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", }, true, ["sign", "verify"] ).then((keyPair) => { const exportButton = document.querySelector(".pkcs8"); exportButton.
addEventListener("click", () => { exportCryptoKey(keyPair.privateKey); }); }); SubjectPublicKeyInfo export This example exports an RSA public encryption key as a PEM-encoded SubjectPublicKeyInfo object. See the complete code on GitHub. /* Convert an ArrayBuffer into a string from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String */ function ab2str(buf) { ...
...istener on the "Export" button. */ window.crypto.subtle.generateKey( { name: "RSA-OAEP", // Consider using a 4096-bit key for systems that require long-term security modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", }, true, ["encrypt", "decrypt"] ).then((keyPair) => { const exportButton = document.querySelector(".spki"); exportButton.
addEventListener("click", () => { exportCryptoKey(keyPair.publicKey); }); }); JSON Web Key import This code exports an ECDSA private signing key as a JSON Web Key object. See the complete code on GitHub. /* Export the given key and write it into the "exported-key" space. */ async function exportCryptoKey(key) { const exported = await window.crypto.subtle.exportKey( "jwk", key ); const expo...
...Selector(".exported-key"); exportKeyOutput.textContent = JSON.stringify(exported, null, " "); } /* Generate a sign/verify key pair, then set up an event listener on the "Export" button. */ window.crypto.subtle.generateKey( { name: "ECDSA", namedCurve: "P-384" }, true, ["sign", "verify"] ).then((keyPair) => { const exportButton = document.querySelector(".jwk"); exportButton.
addEventListener("click", () => { exportCryptoKey(keyPair.privateKey); }); }); Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.exportKey()' in that specification. Recommendation Initial definition. ...
VideoTrackList: change event - Web APIs
The change event is fired when a video track is made active or inactive, for example by changing the track's selected property. ...
... The change event is fired when a video track is made active or inactive, for example by changing the track's selected property. ...
...t handler property onchange Examples Using
addEventListener(): const videoElement = document.querySelector('video'); videoElement.videoTracks.
addEventListener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `selected` will trigger the `change` event const toggleTrackButton = document.querySelector('.toggle-track'); toggleTrackButton.
addEventListener('click', () => { const track = videoElement.videoTracks[0]; track.selected = !track.selected; }); Using the onchange event handler property: const videoElement = document.querySelector('video'); videoElement.videoTracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; // changing the value of `selected` will trigger the `change` event const toggleTrackButton = do...
... Living Standard ...
Using the Web Audio API - Web APIs
es to BaseAudioContext.destination, which handles the situation for you: track.connect(audioContext.destination); A good way to visualise these nodes is by drawing an audio graph so you can visualize it. This is what our current audio graph looks like: Now we can add the play and pause functionality. ...
...lay(); this.dataset.playing = 'true'; } else if (this.dataset.playing === 'true') { audioElement.pause(); this.dataset.playing = 'false'; } }, false); We also need to take into account what to do when the track finishes playing. Our HTMLMediaElement fires an ended event once it's finished playing, so we can listen for that and run code accordingly: audioElement.
addEventListener('ended', () => { playButton.dataset.playing = 'false'; }, false); Modifying sound Let's delve into some basic modification nodes, to change the sound that we have. This is where the Web Audio API really starts to come in handy. First of all, let's change the volume. This can be done using a GainNode, which represents how big our sound wave is. There are two ways you can create nodes with ...
...0" max="2" value="1" step="0.01"> Note: Range inputs are a really handy input type for updating values on audio nodes. You can specify a range's values and use them directly with the audio node's parameters. So let's grab this input's value and update the gain value when the input node has its value changed by the user: const volumeControl = document.querySelector('#volume'); volumeControl.
addEventListener('input', function() { gainNode.gain.value = this.value; }, false); Note: The values of node objects (e.g. GainNode.gain) are not simple values; they are actually objects of type AudioParam -- these called parameters. This is why we have to set GainNode.gain's value property, rather than just setting the value on gain directly. This enables them to be much more flexible, allowing for passin...
...methods are supported more widely. Here our values range from -1 (far left) and 1 (far right). Again let's use a range type input to vary this parameter: <input type="range" id="panner" min="-1" max="1" value="0" step="0.01"> We use the values from that input to adjust our panner values in the same way as we did before: const pannerControl = document.querySelector('#panner'); pannerControl.
addEventListener('input', function() { panner.pan.value = this.value; }, false); Let's adjust our audio graph again, to connect all the nodes together: track.connect(gainNode).connect(panner).connect(audioContext.destination); The only thing left to do is give the app a try: Check out the final demo here on Codepen. Summary Great! We have a boombox that plays our 'tape', and we can adjust the volume an...
Window: resize event - Web APIs
The resize event fires when the document view (window) has been resized. Bubbles No Cancelable No Interface UIEvent Event handler property onresize In some earlier browsers it was possible to register resize event handlers on any HTML element. It is still possible to set onresize attributes or use
addEventListener() to set a handler on any element. However, resize events are only fired on the window object (i.e. returned by document.defaultView). Only handlers registered on the window object will receive resize events. There is a proposal to allow all elements to be notified of resize changes. See Resize Observer to read the draft document, and GitHub issues to read the on-going discussions. Examples Window size logger The following example repo...
... Obsolete CSS Object Model (CSSOM) View ModuleThe definition of 'resize' in that spec...
... Obsolete CSS Object Model (CSSOM) View ModuleThe definition of 'resize' in that specification. Working Draft ...
... Obsolete CSS Object Model (CSSOM) View ModuleThe definition of 'resize' in that specification. Working Draft ...
Window: unload event - Web APIs
ing is visible anymore to the end user UI interactions are ineffective (window.open, alert, confirm, etc.) An error won't stop the unloading workflow Please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload (see example below). ...
...r won't stop the unloading workflow Please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload (see example below). ...
... Specifications ...
... Specifications Specification Status Comment UI EventsThe definition of 'unload' in that specification. W...
Using XMLHttpRequest - Web APIs
common and more obscure use cases for XMLHttpRequest are included. To send an HTTP request, create an XMLHttpRequest object, open a URL, and send the request. After the transaction completes, the object will contain useful information such as the response body and the HTTP status of the result. function reqListener () { console.log(this.responseText); } var oReq = new XMLHttpRequest(); oReq.
addEventListener("load", reqListener); oReq.open("GET", "http://www.example.org/example.txt"); oReq.send(); Types of requests A request made via XMLHttpRequest can fetch the data in one of two ways, asynchronously or synchronously. The type of request is dictated by the optional async argument (the third argument) that is set on the XMLHttpRequest.open() method. If this argument is true or not specified, the XM...
...t monitoring of XMLHttpRequest transfers follows the specification for progress events: these events implement the ProgressEvent interface. The actual events you can monitor to determine the state of an ongoing transfer are: progress The amount of data that has been retrieved has changed. load The transfer is complete; all data is now in the response var oReq = new XMLHttpRequest(); oReq.
addEventListener("progress", updateProgress); oReq.
addEventListener("load", transferComplete); oReq.
addEventListener("error", transferFailed); oReq.
addEventListener("abort", transferCanceled); oReq.open(); // ... // progress on transfers from the server to the client (downloads) function updateProgress (oEvent) { if (oEvent.lengthComputable) { var percentComplete = oEvent.loaded / oEvent.total * 100; ...
...loaded fields. However, if the lengthComputable field is false, the total length is not known and will be zero. Progress events exist for both download and upload transfers. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object, as shown below: var oReq = new XMLHttpRequest(); oReq.upload.
addEventListener("progress", updateProgress); oReq.upload.
addEventListener("load", transferComplete); oReq.upload.
addEventListener("error", transferFailed); oReq.upload.
addEventListener("abort", transferCanceled); oReq.open(); Note: Progress events are not available for the file: protocol. Note: Starting in Gecko 9.0, progress events can now be relied upon to come in for every chunk of data received, includi...
...when the load event occurs for that packet. This lets you now reliably monitor progress by only watching the "progress" event. Note: As of Gecko 12.0, if your progress event is called with a responseType of "moz-blob", the value of response is a Blob containing the data received so far. One can also detect all three load-ending conditions (abort, load, or error) using the loadend event: req.
addEventListener("loadend", loadEnd); function loadEnd(e) { console.log("The transfer finished (although we don't know if it succeeded or not)."); } Note there is no way to be certain, from the information received by the loadend event, as to which condition caused the operation to terminate; however, you can use this to handle tasks that need to be performed in all end-of-transfer scenarios. Submitting for...
XRSession: selectend event - Web APIs
tracking system or handheld controller with an accelerometer. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onselectend For details on how the selectstart, select, and selectend events work, and how you should react to them, see Primary actions in Inputs and input sources. Examples The following example uses
addEventListener() to establish handlers for the selection events: selectstart, selectend, and select. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing tho...
... object and the current target ray pose transform as inputs. This places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The selectend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
...This places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The selectend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
...d and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The selectend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
XRSession: selectstart event - Web APIs
acking system or handheld controller with an accelerometer. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onselectstart For details on how the selectstart, select, and selectend events work, and how you should react to them, see Primary actions in Inputs and input sources. Examples The following example uses
addEventListener() to establish handlers for the selection events: selectstart, selectend, and select. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing tho...
... object and the current target ray pose transform as inputs. This places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The selectend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
...This places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The selectend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
...d and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The selectend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
XRSession: squeezeend event - Web APIs
tem or handheld controller with an accelerometer. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onsqueezeend For details on how the squeezestart, squeeze, and squeezeend events work, and how you should react to them, see Primary squeeze actions in Inputs and input sources. Examples The following example uses
addEventListener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing...
...object and the current target ray pose transform as inputs. This places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The squeezeend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
...This places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The squeezeend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
...ld and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The squeezeend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
XRSession: squeezestart event - Web APIs
e simulated using triggers on hand controllers. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onsqueezestart For details on how the squeezestart, squeeze, and squeezeend events work, and how you should react to them, see Primary squeeze actions in Inputs and input sources. Examples The following example uses
addEventListener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze. This snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. In this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. Only after completing...
...object and the current target ray pose transform as inputs. This places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The squeezeend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
...This places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The squeezeend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
...ld and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc). The squeezeend event results in a myStopTracking() function being called with the object being dragged and the final target ray pose's transform. ...
Using CSS transitions - CSS: Cascading Style Sheets
to make JavaScript functionality smooth Transitions are a great tool to make things look much smoother without having to do anything to your JavaScript functionality. Take the following example. <p>Click anywhere to move the ball</p> <div id="foo"></div> Using JavaScript you can make the effect of moving the ball to a certain position happen: var f = document.getElementById('foo'); document.
addEventListener('click', function(ev){ f.style.transform = 'translateY('+(ev.clientY-25)+'px)'; f.style.transform += 'translateX('+(ev.clientX-25)+'px)'; },false); With CSS you can make it smooth without any extra effort. Simply add a transition to the element and any change will happen smoothly: p { padding-left: 60px; } #foo { border-radius: 50px; width: 50px; height: 50px; background: #c...
...ning. This is a TransitionEvent object, which has two added properties beyond a typical Event object: propertyName A string indicating the name of the CSS property whose transition completed. elapsedTime A float indicating the number of seconds the transition had been running at the time the event fired. This value isn't affected by the value of transition-delay. ...
...ed properties beyond a typical Event object: propertyName A string indicating the name of the CSS property whose transition completed. elapsedTime A float indicating the number of seconds the transition had been running at the time the event fired. This value isn't affected by the value of transition-delay. ...
... at the time the event fired. This value isn't affected by the value of transition-delay. As usual, you can use the
addEventListener() method to monitor for this event: el.
addEventListener("transitionend", updateTransition, true); You detect the beginning of a transition using transitionrun (fires before any delay) and transitionstart (fires after any delay), in the same kind of fashion: el.
addEventListener("transitionrun", signalStart, true); el.
addEventListener("transitionstart", signalStart, true); Note: The transitionend event doesn't fire if the transition is aborted before the transition is completed because either the element is made display: none or the animating property's value is changed. Specifications Specification Status Comment CSS Transitions Working...
animation - CSS: Cascading Style Sheets
eft; flex: none; } .overlay { padding: .5em; } @keyframes slidein { from { transform: scaleX(0); } to { transform: scaleX(1); } } .a1 { animation: 3s ease-in 1s 2 reverse both paused slidein; } .a2 { animation: 3s linear 1s slidein; } .a3 { animation: 3s slidein; } .animation { background: #3F87A6; width: 100%; height: calc(100% - 1.5em); transform-origin: left center; } window.
addEventListener('load', function () { var ANIMATION = Array.from(document.querySelectorAll('.animation')); var BUTTON = Array.from(document.querySelectorAll('button')); function toggleButton (btn, type) { btn.classList.remove('play', 'pause', 'restart'); btn.classList.add(type); btn.title = type.toUpperCase(type); } function playPause (i) { var btn = BUTTON[i]; var anim = ANIM...
...ause')) { anim.style.animationPlayState = 'paused'; toggleButton(btn, 'play'); } else { anim.classList.remove('a' + (i + 1)); setTimeout(function () { toggleButton(btn, i === 0 ? ...
... Constituent properties This property is a shorthand ...
...e.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 animatable is available; it's worth noting that this description is also valid for CSS transitions. Constituent properties This property is a shorthand for the following CSS properties: animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animat...
Creating and triggering events - Developer guides
*/ }, false); // Dispatch the event. ...
...nction eventHandler(e) { console.log('The time is: ' + e.detail); } The old-fashioned way The older approach to creating events uses APIs inspired by Java. The following shows an example with document.createEvent(): // Create the event. const event = document.createEvent('Event'); // Define that the event name is 'build'. event.initEvent('build', true, true); // Listen for the event. elem.
addEventListener('build', function (e) { // e.target matches elem }, false); // target can be any Element or other EventTarget. elem.dispatchEvent(event); Event bubbling It is often desirable to trigger an event from a child element, and have an ancestor catch it; optionally, with data: <form> <textarea></textarea> </form> const form = document.querySelector('form'); const textarea = document.querySel...
...('form'); const textarea = document.querySelector('textarea'); // Create a new event, allow bubbling, and provide any data you want to pass to the "detail" property const eventAwesome = new CustomEvent('awesome', { bubbles: true, detail: { text: () => textarea.value } }); // The form element listens for the custom "awesome" event and then consoles the output of the passed text() method form.
addEventListener('awesome', e => console.log(e.detail.text())); // As the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point textarea.
addEventListener('input', e => e.target.dispatchEvent(eventAwesome)); Creating and dispatching events dynamically Elements can listen for events that haven't been created yet: <form> <textarea></textarea> </f...
...triggers the event to fire, and uses itself as the starting point textarea.
addEventListener('input', e => e.target.dispatchEvent(eventAwesome)); Creating and dispatching events dynamically Elements can listen for events that haven't been created yet: <form> <textarea></textarea> </form> const form = document.querySelector('form'); const textarea = document.querySelector('textarea'); form.
addEventListener('awesome', e => console.log(e.detail.text())); textarea.
addEventListener('input', function() { // Create and dispatch/trigger an event on the fly // Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element this.dispatchEvent(new CustomEvent('awesome', { bubbles: true, detail: { text: () => textarea.va...
<a>: The Anchor element - HTML: Hypertext Markup Language
See ...
...See Referer header: privacy and security concerns for information. Using target="_blank" ...
...See Referer header: privacy and security concerns for information. Using target="_blank" without rel="noreferrer" and rel="noopener" makes the website ...
...See Referer header: privacy and security concerns for information. ...
<input type="color"> - HTML: Hypertext Markup Language
there are two events that can be used to detect changes to the color value: input and change. input is fired on the <input> element every time the color changes. The change event is fired when the user dismisses the color picker. In both cases, you can determine the new value of the element by looking at its value. ...
...the color value: input and change. input is fired on the <input> element every time the color changes. The change event is fired when the user dismisses the color picker. In both cases, you can determine the new value of the element by looking at its value. ...
...ires, and we detect that to change every paragraph to the selected color.</p> JavaScript First, there's some setup. Here we establish some variables, setting up a variable that contains the color we'll set the color well to when we first load up, and then setting up a load handler to do the main startup work once the page is fully loaded. ...
... and then setting up a load handler to do the main startup work once the page is fully loaded. var colorWell; var defaultColor = "#0000ff"; window.
addEventListener("load", startup, false); Initialization Once the page is loaded, our load event handler, startup(), is called: function startup() { colorWell = document.querySelector("#colorWell"); colorWell.value = defaultColor; colorWell.
addEventListener("input", updateFirst, false); colorWell.
addEventListener("change", updateAll, false); colorWell.select(); } This gets a reference to the color <input> element in a variable called colorWell, then sets the color input's value to the value in defaultColor. Then the color input's input event is set up to call our updateFirst() function, and the change event is set to call updateAll(). These ar...
panel - Archive of obsolete content
n communicate with the script using either the postMessage() API or (preferably, usually) the port API. For example, here's an add-on whose content script intercepts mouse clicks on links inside the panel, and sends the target URL to the main add-on code. The content script sends messages using self.port.emit() and the add-on script receives them using panel.port.on(). ...
...tation we'll just log the text to the console. textEntryPanel.port.on("text-entered", function (text) { console.log(text); textEntryPanel.hide(); }); The content script "get-text.js" looks like this: // When the user hits return, send the "text-entered" // message to main.js. // The message payload is the contents of the edit box. var textArea = document.getElementById("edit-box"); textArea.
addEventListener('keyup', function onkeyup(event) { if (event.keyCode == 13) { // Remove the newline. text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textArea.value = ''; } }, false); // Listen for the "show" event being sent from the // main add-on code. It means that the panel's about // to be shown. // // Set the focus to the text area so the user c...
...unction (text) { console.log(text); textEntryPanel.hide(); }); The page script is exactly the same as the content script above, except that instead of self, we use addon to access the messaging APIs: // When the user hits return, send the "text-entered" // message to main.js. // The message payload is the contents of the edit box. var textArea = document.getElementById("edit-box"); textArea.
addEventListener('keyup', function onkeyup(event) { if (event.keyCode == 13) { // Remove the newline. text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); addon.port.emit("text-entered", text); textArea.value = ''; } }, false); // Listen for the "show" event being sent from the // main add-on code. It means that the panel's about // to be shown. // // Set the focus to the text area so the user ...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
they're not in any namespace) elem.setAttributeNS(attrNs.namespace || "", attrNs.shortName, val); } } // Create and append this element's children...
...they're not in any namespace) elem.setAttributeNS(attrNs.namespace || "", attrNs.shortName, val); } } // Create and append this element's children var childElems = Array.slice(...
...ate event listeners and script fragments from dynamic content. Great care must be taken in these situations. Under no circumstances should code resembling 'callback("' + str + '")' appear anywhere in your add-on. Closures By far the best way to create dynamic event listeners is to use closures. The following two code fragments are roughly equivalent: function clickify(elem, address) { elem.
addEventListener("click", function (event) { openWindow(address) }, false); } function clickify(elem, address) { elem.onclick = function (event) { openWindow(address) }; } Multiple Attributes Sometimes there is a need for event listeners to appear as attributes in the DOM. In these cases, multiple attributes should be used, one for each variable: function clickify(elem, address) { elem.setAttribute("...
Intercepting Page Loads - Archive of obsolete content
portant when it comes to add-ons and page loads. Read the recommendations in Appendix A regarding performance if you're planning on implementing any of these. The Easy Way: Load Events This comes from the tabbrowser code snippets page. In a nutshell, from the chrome code in the overlay we add an event listener for the load event. this._loadHandler = function() {that._onPageLoad(); }; gBrowser.
addEventListener("load", this._loadHandler, true); gBrowser is a global object that corresponds to the tabbrowser element in the main browser window. It is full of useful functions, so you should always keep it in mind when you want to handle tabs and web content windows. Attaching the load event handler to gBrowser allows us to listen to these events for all tabs, without having to worry how many tabs are open...
... of the browser element. What does this mean? It means you have to keep track of tabs being opened and closed, in order to add and remove your listener. ...
... keep track of tabs being opened and closed, in order to add and remove your listener. ...
JavaScript crypto - Archive of obsolete content
tokens, and signing text. Handling smart card events Web sites can make themselves more SmartCard friendly by listening for SmartCard insertion and removal events. To enable your document to receive these events, you must first tell the crypto system you are interested by setting window.crypto.enableSmartCardEvents to true. You can then register event handlers for these events with the document.
addEventListener() method. Two smart card related events are generated: smartcard-insert when SmartCards are inserted, and smartcard-remove when SmartCards are removed. Web sites which use SSL clientAuth login could use the following code to refresh the page on token insertions and removals: <!DOCTYPE html> <p>... <script> function onSmartCardChange() { window.location.reload(); } function register() { win...
...ted: smartcard-insert when SmartCards are inserted, and smartcard-remove when SmartCards are removed. Web sites which use SSL clientAuth login could use the following code to refresh the page on token insertions and removals: <!DOCTYPE html> <p>... ...
...en SmartCards are removed. Web sites which use SSL clientAuth login could use the following code to refresh the page on token insertions and removals: <!DOCTYPE html> <p>... ...
Focus and Selection - Archive of obsolete content
blur events to update parts of the interface as the user selects elements. For instance, you might update a total as the user enters values in other fields, or use focus events to validate certain values. Don't display an alert during a focus or blur event as this will be distracting for the user and is poor user interface design. You can also add event handlers dynamically using the DOM function
addEventListener. You can use it for any element and event type. It takes three parameters, the event type, a function to execute when the event occurs and a boolean indicating whether to capture or not. Getting the currently focused element The currently focused element is held by an object called a command dispatcher, of which there is only one for the window. The command dispatcher is responsible for keeping t...
...ispatcher from a window using the document's commandDispatcher property. From there, you can get the focused element with the dispatcher's focusedElement property. The example below shows this. ...
... document.getElementById("focused").value = focused.tagName; } </script> <hbox> <label control="username" value="User Name:"/> <textbox id="username"/> </hbox> <button label="Hello"/> <checkbox label="Remember This Decision"/> <label id="focused" value="-No focus-"/> </window> In this example, a focus event handler is attached the window. We want to use a capturing event handler, so the
addEventListener method needs to be used. It registers a capturing event handler with the window which will call the setFocusedElement method. This method gets the focused element from the command dispatcher and sets a label to its tag name. As the focused element is changed, the label will show the tagname of the element. A few things to note. First, when the textbox is focused, the tag name is 'html:input', ...
Common causes of memory leaks in extensions - Extensions
t should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. Be careful with setInterval/setTimeout Using window.setInterval() or window.setTimeout() can be problematic, too, when it comes to zombie compartments. Consider the following example code that could be part of your browser.xul overlay: gBrowser.
addEventListener("DOMContentLoaded", function(evt) { var contentDoc = evt.originalTarget; var i = 0; // Refresh the title once each second setInterval(function() { contentDoc.title = ++i; }, 1000); }, false); One would normally expect that the interval (or timer) would be destroyed as soon as the document unloads, in the same way that event listeners are automatically destroyed. However, while th...
...ompartment) alive until the window is unloaded. If the window in question is browser.xul or some long-lived web app such as Gmail, the leaked compartment might survive for quite some time. function leakref() {} function main(window) { // This is a potential leak, as the window (e.g. browser.xul) will hold on to // the leakref function and the enclosing compartment via the listener. window.
addEventListener("leaky", leakref, true); // The following line still fails to avoid the leak, as useCapture differs // and removeEventListener will not remove anything. // This kind of subtle bug is very common. // unload(function() window.removeEventListener("leaky", leakref, false), window); // This is the right way to do it remove the listener. unload(function() window.removeEventListener("leaky...
...ence to the observer object, which will cause it to hold onto the whole window. To avoid this problem explicitly call nsIObserverService.removeObserver() in an unload event listener. You may also specify ownsWeak = true in the call to nsIObserverService.addObserver(), but that might require you to properly implement weak references as well. In overlay code you may use an unload event listener:
addEventListener("unload", function() { Services.obs.removeObserver(myObserver, "private-browsing"); }, false); In bootstrap.js (restartless add-ons) unregister your observer in your shutdown function: function shutdown() { // ... Services.obs.removeObserver(myObserver, "private-browsing"); } In JavaScript code modules it recommended to also observe the xpcom-shutdown or quit-application notifications ...
Mobile touch controls - Game development
od thing about using Phaser is that it offers helper variables and functions for easier and faster development, but it's entirely up to you which approach you to choose. Pure JavaScript approach We could implement touch events on our own -- setting up event listeners and assigning relevant functions to them would be quite straightforward: var el = document.getElementsByTagName("canvas")[0]; el.
addEventListener("touchstart", handleStart); el.
addEventListener("touchmove", handleMove); el.
addEventListener("touchend", handleEnd); el.
addEventListener("touchcancel", handleCancel); This way, touching the game's <canvas> on the mobile screen would emit events, and thus we could manipulate the game in any way we want (for example, moving the space ship around). The events are as follows: touchstart is fired...
...ve the player's ship by touching the screen on a mobile device. We will use two events: touchstart and,touchmove both handled by one function. ...
... device. We will use two events: touchstart and,touchmove both handled by one function. ...
Unconventional controls - Game development
= this.input.keyboard.createCursorKeys(); //... if(this.cursors.right.isDown) { // move player right } It works out of the box. The cursors are the four directional arrow keys on the keyboard, and these have exactly the same key codes as the arrow keys on the remote. How do you know the codes for the other remote keys? You can check them by printing the responses out in the console: window.
addEventListener("keydown", function(event) { console.log(event.keyCode); }, this); Every key pressed on the remote will show its key code in the console. You can also check this handy cheat sheet seen below if you're working with Panasonic TVs running Firefox OS: You can add moving between states, starting a new game, controlling the ship and blowing stuff up, pausing and restarting the game. All that is...
...(event.keyCode); }, this); Every key pressed on the remote will show its key code in the console. You can also check this handy cheat sheet seen below if you're working with Panasonic TVs running Firefox OS: You can add moving between states, starting a new game, controlling the ship and blowing stuff up, pausing and restarting the game. All that is needed is checking for key presses: window.
addEventListener("keydown", function(event) { switch(event.keyCode) { case 8: { // pause the game break; } case 588: { // detonate bomb break; } // ... } }, this); You can see it in action by watching this video. Leap Motion Have you ever thought about controlling a game only with your hands? It's possible with Leap...
... Proximity API Another interesting idea is to use the built-in proximity sensors of your hardware to detect how far an object, for example a hand, is from the given sensor. It could work similar to the doppler effect in terms of manipulating the player's ship on the screen by moving your hand closer or further from the device. An event listener for device proximity would look like this: window.
addEventListener('deviceproximity', function(event) { var min = event.min; var max = event.max; var proximity = event.value; }); The min and max values are the minimum and the maximum distances respectively between which the sensor can detect the exact proximity value. All three are calculated in centimetres. Note: See the DeviceProximityEvent reference page for more details. MaKey MaKey If you ...
Fundamental text and font styling - Learn web development
You've reached the end of this article, and already did some skill testing in our Active Learning section, but can you remember the ...
... You've reached the end of this article, and already did some skill testing in our Active Learning section, but can you remember the most important information going forward? You can find an assessment to verify that you've retained this information at the end ...
...ent.createElement('style'); const headElem = document.querySelector('head'); headElem.appendChild(styleElem); function drawOutput() { output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; } reset.
addEventListener("click", function() { htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput(); }); htmlInput.
addEventListener("input", drawOutput); cssInput.
addEventListener("input", drawOutput); window.
addEventListener("load", drawOutput); Test your skills! You've reached the end of this article, and already did some skill testing in our Active Learning section, but can you remember the most important information going forward? You can find an assessment to verify that you've retained this information at the end of the module -- see Typesetting a community sch...
Example 3 - Learn web development
ct, 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) { opti...
...oad", 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); }); selec...
...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
se'); }); optionList[index].setAttribute('aria-selected', 'true'); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); }; function getIndex(select) { var nativeWidget = select.previousElementSibling; 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.
...'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); }); option.
addEventListener('click', function (event) { updateValue(select, index); }); }); select.
addEventListener('click', function (event) { toggleOptList(select); }); select.
addEventListener('focus', function (event) { activeSelect(select, selectList); }); sele...
...ouseover', function () { highlightOption(select, option); }); option.
addEventListener('click', function (event) { updateValue(select, index); }); }); select.
addEventListener('click', function (event) { toggleOptList(select); }); select.
addEventListener('focus', function (event) { activeSelect(select, selectList); }); select.
addEventListener('blur', function (event) { deactivateSelect(select); }); select.
addEventListener('keyup', function (event) { var length = optionList.length, index = getIndex(select); if (event.keyCode === 27) { deactivateSelect(select); } if (event.keyCode === 40 && index < length - 1) { index++; } if (event.keyCode === 38 && index > 0) { index--; } updat...
Introducing asynchronous JavaScript - Learn web development
chronous JavaScript is. This section recaps some of the information we saw in the previous article. A lot of the functionality we have looked at in previous learning area modules is synchronous -- you run some code, and the result is returned as soon as the browser can do so. Let's look at a simple example (see it live here, and see the source): const btn = document.querySelector('button'); btn.
addEventListener('click', () => { alert('You clicked me!'); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem); }); In this block, the lines are executed one after the other: We grab a reference to a <button> element that is already available in the DOM. We add a click event listener to it so that when the button is clic...
...rt executing code in the background. When the background code finishes running, it calls the callback function to let you know the work is done, or to let you know that something of interest has happened. Using callbacks is slightly old-fashioned now, but you'll still see them in use in a number of older-but-still-commonly-used APIs. An example of an async callback is the second parameter of the
addEventListener() method (as we saw in action above): btn.
addEventListener('click', () => { alert('You clicked me!'); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem); }); The first parameter is the type of event to be listened for, and the second parameter is a callback function that is invoked when the event is fired. ...
...lock has completely finished running and delivering its result through the .then() blocks will we finally see the second console.log() message (It worked :)) appear. So the messages have appeared in a different order to what you might expect: Starting All done! It worked :) If this confuses you, then consider the following smaller example: console.log("registering click handler"); button.
addEventListener('click', () => { console.log("get click"); }); console.log("all done"); This is very similar in behavior -- the first and third console.log() messages will be shown immediately, but the second one is blocked from running until someone clicks the mouse button. The previous example works in the same way, except that in that case the second message is blocked on the promise chain fetching a reso...
Introduction to web APIs - Learn web development
st playBtn = document.querySelector('button'); const volumeSlider = document.querySelector('.volume'); const audioSource = audioCtx.createMediaElementSource(audioElement); Next up we include a couple of event handlers that serve to toggle between play and pause when the button is pressed and reset the display back to the beginning when the song has finished playing: // play/pause audio playBtn.
addEventListener('click', function() { // check if context is in suspended state (autoplay policy) if (audioCtx.state === 'suspended') { audioCtx.resume(); } // if track is stopped, play it if (this.getAttribute('class') === 'paused') { audioElement.play(); this.setAttribute('class', 'playing'); this.textContent = 'Pause' // if track is playing, stop it } els...
... Next, we create a GainNode object using the AudioContext.createGain(...
...rt of the HTMLMediaElement API, which is different but closely-related. ...
A first splash into JavaScript - Learn web development
} else { lastResult.textContent = 'Wrong!'; lastResult.style.backgroundColor = 'red'; if(userGuess < randomNumber) { lowOrHi.textContent = 'Last guess was too low!' ; } else if(userGuess > randomNumber) { lowOrHi.textContent = 'Last guess was too high!'; } } guessCount++; guessField.value = ''; } guessSubmit.
addEventListener('click', checkGuess); function setGameOver() { guessField.disabled = true; guessSubmit.disabled = true; resetButton = document.createElement('button'); resetButton.textContent = 'Start new game'; document.body.append(resetButton); resetButton.
addEventListener('click', resetGame); } function resetGame() { guessCount = 1; const resetPara...
... are things that happen in the browser -- a button being clicked, a page loading, a video playing, etc. -- in response to which we can run blocks of code. The constructs that listen out for the event happening are called event listeners, and the blocks of code that run in response to the event firing are called event handlers. Add the following line below your checkGuess() function: guessSubmit.
addEventListener('click', checkGuess); Here we are adding an event listener to the guessSubmit button. This is a method that takes two input values (called arguments) -- the type of event we are listening out for (in this case click) as a string, and the code we want to run when the event occurs (in this case the checkGuess() function). Note that we don't need to specify the parentheses when writing it inside ad...
...ng the game functionality Let's add that setGameOver() function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript: function setGameOver() { guessField.disabled = true; guessSubmit.disabled = true; resetButton = document.createElement('button'); resetButton.textContent = 'Start new game'; document.body.append(resetButton); resetButton.
addEventListener('click', resetGame); } The first two lines disable the form text input and button by setting their disabled properties to true. This is necessary, because if we didn't, the user could submit more guesses after the game is over, which would mess things up. The next three lines generate a new <button> element, set its text label to "Start new game", and add it to the bottom of our existing HTML...
Cross Process Object Wrappers
g CPOWs from frame scripts Frame scripts can send messages to chrome using one of two global functions: sendAsyncMessage() or sendSyncMessage(). The optional third parameter to each of these functions is an object whose properties are objects to wrap. For example, this frame script sends a DOM node to chrome when the user clicks it, as the clicked property of the third argument: // frame script
addEventListener("click", function (event) { sendAsyncMessage("my-e10s-extension-message", {}, { clicked : event.target }); }, false); In the chrome script, the DOM node is now accessible through a Cross Process Object Wrapper, as a property of the objects property of the message. The chrome script can get and set the wrapped object's properties and call its functions: // chrome script windowMM.addMessageList...
... are bidirectional. This means that if content passes a CPOW to the chrome process, the chrome process can synchronously pass objects (such as event listener functions) into functions defined in the CPOW. This means you can write code like this: // frame script /* On mouseover, send the button to the chrome script as a CPOW. */ var button = content.document.getElementById("click-me"); button.
addEventListener("mouseover", function (event) { sendAsyncMessage("my-addon-message", {}, { element : event.target }); }, false); // chrome script /* Load the frame script, then listen for the message. When we get the message, extract the CPOW and add a function as a listener to the button's "click" event. */ browserMM.loadFrameScript("chrome://my-addon/content/frame-script.js", false); browserMM.addMess...
... false); // chrome script /* Load the frame script, then listen for the message. When we get the message, extract the CPOW and add a function as a listener to the button's "click" event. */ browserMM.loadFrameScript("chrome://my-addon/content/frame-script.js", false); browserMM.addMessageListener("my-addon-message", function(message) { let wrapper = message.objects.element; wrapper.
addEventListener("click", function() { console.log("they clicked"); }); }); Mapping content documents to XUL browsers A common pattern is to get the XUL <browser> that corresponds to a content document. To enable this, gBrowser.getBrowserForDocument and gBrowser.getBrowserForContentWindow can be passed a CPOW for the content document and content window, respectively, and return the XUL <browser> t...
source-editor.jsm
osed through source-editor.jsm. ...
... addBreakpoint( Number aLineIndex, [optional] String aCondition ); Parameters aLineIndex The 0-based line number at which to place the breakpoint. aCondition Optional A string describing the condition under which the breakpoint should be triggered. This information is simply recorded as part of the breakpoint annotation. NEED LINK TO TEXT ABOUT HANDLING BREAKPOINT CONDITIONS HERE.
addEventListener() Adds a new event listener to the editor. You can listen for any of the events listed in Event name constants. To stop listening for the event, call removeEventListener(). void
addEventListener( String aEventType, Function aCallback ); Parameters aEventType The name of the event type to listen for; see Event name constants for possible values. aCallback The function to call when th...
...ange was redone, otherwise false. removeBreakpoint Removes the breakpoint from the specified line of code. Boolean removeBreakpoint( Number aLineIndex ); Parameters aLineIndex The 0-based line number from which to remove the breakpoint. Return value true if a breakpoint was removed, otherwise false. removeEventListener() Removes an event listener (previously established by calling
addEventListener() from the editor. void removeEventListener( String aEventType, Function aCallback ); Parameters aEventType The name of the event type to stop listening for; see Event name constants for possible values. aCallback The function to stop calling when the specified event occurs. resetUndo Resets the undo stack, removing all possible undo and redo operations from the stack. void reset...
Components.utils.cloneInto
eference to the cloned object. Example This add-on script creates an object, clones it into the content window and makes it a property of the content window global: // add-on script var addonScriptObject = {"greeting" : "hello from add-on"}; contentWindow.addonScriptObject = cloneInto(addonScriptObject, contentWindow); Scripts running in the page can now access the object: // page script button.
addEventListener("click", function() { console.log(window.addonScriptObject.greeting); // "hello from add-on" }, false); Of course, you don't have to assign the clone to the window itself: you can assign it to some other object in the target scope: contentWindow.foo.addonScriptObject = cloneInto(addonScriptObject, contentWindow); You can also pass it into a function defined in the page script. Suppose the p...
...If you pass the {wrapReflectors:true} flag, then the object you clone is allowed to contain these objects: // add-on script var addonS...
... ...
Components.utils.exportFunction
Xray filtering and waiving Xrays provide a filtered view of the original object. For the...
...Because you can call Function Xrays just like normal functions, this means that passing callbacks into the exported function just works, making the allowCallbacks option redundant: // privileged scope: for example, a content script functi...
...This prevents passing cross-origin objects (like Window or Location) to privileged functions, since the privileged code will have full access to those objects and might unintentionall...
customDBHeaders Preference
If the .msf file is rebuilt, all the msgHdrs should have the string property se...
...If the .msf file is rebuilt, all the msgHdrs should have the string property set correctly. The attaching of the column handler through the Obser...
...~ ~ ~ ~ \n"); IMPORTANT Be aware that only messages that are added to the .msf database after the customDBHeaders pref is set will have the corresponding string property set on the msgHdr. If the .msf file is rebuilt, all the msgHdrs should have the string property set correctly. The attaching of the column handler through the ObserverService object is some pretty new stuff, so I was using the
addEventListener("select"...) stuff as a backup. Depending on the release you use one, both, or none of the methods may work. Building the Extension For this extension, I used a directory tree exactly like this: superfluous/ chrome.manifest install.rdf Makefile chrome/ content/ superfluous.js ...
BroadcastChannel: messageerror event - Web APIs
The messageerror event is fired on a BroadcastChannel object when a message arrives on the channel that can't be deserialized. ...
...ror event is fired on a BroadcastChannel object when a message arrives on the channel that can't be deserialized. ...
...can't be deserialized. ...
CSSStyleDeclaration.setProperty() - Web APIs
Working Draft Document Object Model (DOM) Level 2 Style Specifi...
... Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSStyleDeclaration' in that s...
... Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSStyleDeclaration' in that specification. Obsolete ...
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
ocusIfNeeded() method is used to draw a focus ring when appropriate. ...
... when appropriate. ...
... <button id="button1">Continue</button> <button id="button2">Quit</button> </canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const button1 = document.getElementById('button1'); const button2 = document.getElementById('button2'); document.
addEventListener('focus', redraw, true); document.
addEventListener('blur', redraw, true); canvas.
addEventListener('click', handleClick, false); redraw(); function redraw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawButton(button1, 20, 20); drawButton(button2, 20, 80); } function handleClick(e) { // Calculate click coordinates const x = e.clientX - canvas.offsetLeft; const y = e.clientY - canvas.offsetTop; // Focus button1, if appropriate drawButton(button1, 20, 20); if (ctx.
Using channel messaging - Web APIs
use later on to display confirmation messages that we will receive back from the <iframe>. ...
...ar input = document.getElementById('message-input'); var output = document.getElementById('message-output'); var button = document.querySelector('button'); var iframe = document.querySelector('iframe'); var channel = new MessageChannel(); var port1 = channel.port1; // Wait for the iframe to load iframe.
addEventListener("load", onLoad); function onLoad() { // Listen for button clicks button.
addEventListener('click', onClick); // Listen for messages on port1 port1.onmessage = onMessage; // Transfer port2 to the iframe iframe.contentWindow.postMessage('init', '*', [channel.port2]); } // Post a message on port1 when the button is clicked function onClick(e) { e.preventDefault(); port1.postMessage(input.value); } // Handle messages received on port1 function onMessage(e) { output.inner...
...icate with the main page. When our button is clicked, we prevent the form from submitting as normal and then send the value entered in our text input to the IFrame via the MessageChannel. ...
Detecting device orientation - Web APIs
ent is more commonly found in mobile devices. Processing orientation events All you need to do in order to begin receiving orientation change is to listen to the deviceorientation event: Note: gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation. window.
addEventListener("deviceorientation", handleOrientation, true); After registering your event listener (in this case, a JavaScript function called handleOrientation()), your listener function periodically gets called with updated orientation data. The orientation event contains four values: DeviceOrientationEvent.absolute DeviceOrientationEvent.alpha DeviceOrientationEvent.beta DeviceOrientationEvent.gamm...
... Warning: Chrome and Firefox do not handle the angles the same way, so on some axes the direction are reversed. Processing motion events Motion events are handled the same way as the orientation events except that th...
...e to open this example in a new window; because deviceorientation doesn't work in a cross-origin <iframe> in all browsers. Warning: Chrome and Firefox do not handle the angles the same way, so on some axes the direction are reversed. Processing motion events Motion events are handled the same way as the orientation events except that they have their own event's name: devicemotion window.
addEventListener("devicemotion", handleMotion, true); What's really changed are the information provided within the DeviceMotionEvent object passed as a parameter of the HandleMotion function. The motion event contains four properties: DeviceMotionEvent.acceleration DeviceMotionEvent.accelerationIncludingGravity DeviceMotionEvent.rotationRate DeviceMotionEvent.interval Motion values explained The Devic...
Using light sensors - Web APIs
a change in light intensity, the browser is notified of the change and fires a DeviceLightEvent event. The event gives information about the light intensity of the device's environment. The DeviceLightEvent provides a value attribute with light intensity in lux which is generally treated as shown below. ...
...f the change and fires a DeviceLightEvent event. The event gives information about the light intensity of the device's environment. The DeviceLightEvent provides a value attribute with light intensity in lux which is generally treated as shown below. 10 ~ 50 lux : Dim Environment 100 ~ 1000 lux : Normal > 10000 lux : Bright It uses the
addEventListener method of the window object. ...
...nt provides a value attribute with light intensity in lux which is generally treated as shown below. 10 ~ 50 lux : Dim Environment 100 ~ 1000 lux : Normal > 10000 lux : Bright It uses the
addEventListener method of the window object. window.
addEventListener("devicelight", function (event) { // Read out the lux value var luminosity = event.value; alert(luminosity); }); Example: window.
addEventListener('devicelight', function(event) { var bodyBg= document.body.style; //event.value is the lux value returned by the sensor on the device if (event.value < 100) { alert('Hey, you! You are working in a dark environment'); bodyBg.backgroundColor="lightgrey"; } else { bodyBg.backgroundColor="#fff"; } }); This example shows how the API can actually be used in the wild. If your app contains a lot...
Document: gotpointercapture event - Web APIs
. Bubbles No Cancelable No Interface PointerEvent Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture() on the element on a pointerdown event, which will trigger gotpointercapture. ...
... Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture() on the element on a pointerdown event, which will trigger gotpointercapture. ...
... document.
addEventListener('gotpointercapture', () => { console.log('I\'ve been captured!') }); para.
addEventListener('pointerdown', (event) => { para.setPointerCapture(event.pointerId); }); The same example, using the ongotpointercapture event handler property: const para = document.querySelector('p'); document.ongotpointercapture = () => { console.log('I\'ve been captured!') }; para.
addEventListener('pointerdown', (event) => { para.setPointerCapture(event.pointerId); }); Specifications Specification Status Pointer Events Obsolete ...
Document: keydown event - Web APIs
nts are now fired during IME composition, to improve cross-browser compatibility for CJKT users (bug 354358, also see keydown and keyup events are now fired during IME composition for more useful details). ...
...s are now fired during IME composition for more useful details). To ignore all keydown events that are part of composition, do something like this (229 is a special value set for a keyCode relating to an event that has been processed by an IME): eventTarget.
addEventListener("keydown", event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples
addEventListener keydown example This example logs the KeyboardEvent.code value whenever you press down a key. <p>Focus the IFrame first (e.g. ...
...rocessed by an IME): eventTarget.
addEventListener("keydown", event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples
addEventListener keydown example This example logs the KeyboardEvent.code value whenever you press down a key. <p>Focus the IFrame first (e.g. ...
Document: lostpointercapture event - Web APIs
es No Cancelable No Interface PointerEvent Event handler property onlostpointercapture Examples This example listens for the lostpointercapture event, and captures the pointer for an element on pointerdown. When the user subsequently releases the pointer, the lostpointercapture event will be fired. ...
...operty onlostpointercapture Examples This example listens for the lostpointercapture event, and captures the pointer for an element on pointerdown. When the user subsequently releases the pointer, the lostpointercapture event will be fired. ...
...nt.
addEventListener('lostpointercapture', () => { console.log('I\'ve been released!') }); para.
addEventListener('pointerdown', (event) => { para.setPointerCapture(event.pointerId); }); The same example, but using the onlostpointercapture event handler property: const para = document.querySelector('p'); document.onlostpointercapture = () => { console.log('I\'ve been released!') }; para.
addEventListener('pointerdown', (event) => { para.setPointerCapture(event.pointerId); }); Specifications Specification Status Pointer Events Obsolete ...
Element: mousedown event - Web APIs
lack; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. ...
...s let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. ...
...Y gives the (x,y) offset from the edge of the canvas. ...
Element: mousemove event - Web APIs
lack; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. ...
...s let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. ...
...Y gives the (x,y) offset from the edge of the canvas. ...
Element: mouseup event - Web APIs
lack; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. ...
...s let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. ...
...Y gives the (x,y) offset from the edge of the canvas. ...
Event.eventPhase - Web APIs
scription Event.NONE 0 No event is being processed at this time. Event.CAPTURING_PHASE 1 The event is being propagated through the target's ancestor objects. This process starts with the Window, then Document, then the HTMLHtmlElement, and so on through the elements until the target's parent is reached. Event listeners registered for capture mode when EventTarget.
addEventListener() was called are triggered during this phase. Event.AT_TARGET 2 The event has arrived at the event's target. Event listeners registered for this phase are called at this time. If Event.bubbles is false, processing the event is finished after this phase is complete. Event.BUBBLING_PHASE 3 The event is propagating back up through the target's ancestors in reverse order...
..."none" : ...
..."none" : e.eventPhase == 1 ? "capturing" : e.eventPhase == 2 ? "target" : ...
Event.type - Web APIs
String containing the type of Event. Example This example logs the event type whenever you press a keyboard key or click a mouse button. ...
...event type whenever you press a keyboard key or click a mouse button. ...
... HTML <p>Press any key or click the mouse to get the event type.</p> <p id="log"></p> JavaScript function getEventType(event) { const log = document.getElementById('log'); log.innerText = event.type + '\n' + log.innerText; } // Keyboard events document.
addEventListener('keydown', getEventType, false); // first document.
addEventListener('keypress', getEventType, false); // second document.
addEventListener('keyup', getEventType, false); // third // Mouse events document.
addEventListener('mousedown', getEventType, false); // first document.
addEventListener('mouseup', getEventType, false); // second document.
addEventListener('click', getEventType, false); // third Result Specifications Specification Status Comment DOMThe definition of 'Event.type' in that sp...
EventSource - Web APIs
list element already in the document. Note: You can find a full example on GitHub -- see Simple SSE demo using PHP. To listen to named events, you'll require a listener for each type of event sent. ...
...a listener for each type of event sent. ...
...}) /* Similarly, this will listen for events * with the field `event: update` */ sse.
addEventListener("update", function(e) { console.log(e.data) }) /* The event "message" is a special case, as it * will capture events without an event field * as well as events that have the specific type * `event: message` It will not trigger on any * other event type. */ sse.
addEventListener("message", function(e) { console.log(e.data) }) Specifications Specification Status HTML Living StandardThe definition of 'EventSource' in that specification. Living Standard ...
Using FormData Objects - Web APIs
d size="32" maxlength="64" /><br /> <label>Custom file label:</label> <input type="text" name="filelabel" size="12" maxlength="32" /><br /> <label>File to stash:</label> <input type="file" name="file" required /> <input type="submit" value="Stash the file!" /> </form> <div></div> Then you can send it using code like the following: var form = document.forms.namedItem("fileinfo"); form.
addEventListener('submit', function(ev) { var oOutput = document.querySelector("div"), oData = new FormData(form); oData.append("CustomField", "This is some extra data"); var oReq = new XMLHttpRequest(); oReq.open("POST", "stash.php", true); oReq.onload = function(oEvent) { if (oReq.status == 200) { oOutput.innerHTML = "Uploaded!"; } else { oOutput.innerHTML = "Error " + oRe...
...o a formdata event firing, rather than needing to put it together yourself. ...
...vent: formElem.
addEventListener('submit', (e) => { // on form submission, prevent default e.preventDefault(); // construct a FormData object, which fires the formdata event new FormData(formElem); }); When the formdata event fires we can access the FormData object using FormDataEvent.formData, then do what we like with it (below we post it to the server using XMLHttpRequest). ...
GlobalEventHandlers.onerror - Web APIs
erty of the GlobalEventHandlers mixin is an EventHandler that processes error events. Error events are fired at various targets for different kinds of errors: When a JavaScript runtime error (including syntax errors and exceptions thrown within handlers) occurs, an error event using interface ErrorEvent is fired at window and window.onerror() is invoked (as well as handlers attached by window.
addEventListener (not only capturing)). When a resource (such as an <img> or <script>) fails to load, an error event using interface Event is fired at the element that initiated the load, and the onerror() handler on the element is invoked. These error events do not bubble up to window, but (at least in Firefox) can be handled with a window.
addEventListener configured with useCapture set to True. Installing a ...
... window.onerror window.onerror = function(message, source, lineno, colno, error) { ... }; Function parameters: message: error message (string). Available as event (sic!) in HTML onerror="" handler. ...
...essage: error message (string). Available as event (sic!) in HTML onerror="" handler. source: URL of the script where the error was raised (string) lineno: Line number where error was raised (number) colno: Column number for the line where the error occurred (number) error: Error Object (object) When the function returns true, this prevents the firing of the default event handler. window.
addEventListener('error') window.
addEventListener('error', function(event) { ... }) event of type ErrorEvent contains all the information about the event and the error. element.onerror element.onerror = function(event) { ... } element.onerror accepts a function with a single argument of type Event. A good example for this is when you are using an image tag, and need to specify a backup image in case the o...
HTMLElement: animationend event - Web APIs
e DOM or the animation is removed from the element, the animationend event is not fired. ...
...: 2; } @keyframes slidein { from { margin-left: 100%; width: 300%; } to { margin-left: 0%; width: 100%; } } JS const animation = document.querySelector('p.animation'); const animationEventLog = document.querySelector('.animation-example>.event-log'); const applyAnimation = document.querySelector('.animation-example>button.activate'); let iterationCount = 0; animation.
addEventListener('animationstart', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.
addEventListener('animationiteration', () => { iterationCount++; animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.
addEventListener('animationend', () => { animationEventLog.textContent =...
...ration', () => { iterationCount++; animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.
addEventListener('animationend', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`; animation.classList.remove('active'); applyAnimation.textContent = "Activate animation"; }); animation.
addEventListener('animationcancel', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`; }); applyAnimation.
addEventListener('click', () => { animation.classList.toggle('active'); animationEventLog.textContent = ''; iterationCount = 0; let active = animation.classList.contains('active'); if (active) { applyAnimation.textContent = "Cancel animation"; } ...
HTMLElement: animationiteration event - Web APIs
ns with an animation-iteration-count of one. ...
... } @keyframes slidein { from { transform: translateX(100%) scaleX(3); } to { transform: translateX(0) scaleX(1); } } JS const animation = document.querySelector('p.animation'); const animationEventLog = document.querySelector('.animation-example>.event-log'); const applyAnimation = document.querySelector('.animation-example>button.activate'); let iterationCount = 0; animation.
addEventListener('animationstart', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.
addEventListener('animationiteration', () => { iterationCount++; animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.
addEventListener('animationend', () => { animationEventLog.textContent =...
...ration', () => { iterationCount++; animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.
addEventListener('animationend', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`; animation.classList.remove('active'); applyAnimation.textContent = "Activate animation"; }); animation.
addEventListener('animationcancel', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`; }); applyAnimation.
addEventListener('click', () => { animation.classList.toggle('active'); animationEventLog.textContent = ''; iterationCount = 0; let active = animation.classList.contains('active'); if (active) { applyAnimation.textContent = "Cancel animation"; } ...
HTMLElement: animationstart event - Web APIs
lay (and, correspondingly, the animation will begin playing at that time index into the sequence). ...
... } @keyframes slidein { from { transform: translateX(100%) scaleX(3); } to { transform: translateX(0) scaleX(1); } } JS const animation = document.querySelector('p.animation'); const animationEventLog = document.querySelector('.animation-example>.event-log'); const applyAnimation = document.querySelector('.animation-example>button.activate'); let iterationCount = 0; animation.
addEventListener('animationstart', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.
addEventListener('animationiteration', () => { iterationCount++; animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.
addEventListener('animationend', () => { animationEventLog.textContent =...
...ration', () => { iterationCount++; animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.
addEventListener('animationend', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`; animation.classList.remove('active'); applyAnimation.textContent = "Activate animation"; }); animation.
addEventListener('animationcancel', () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`; }); applyAnimation.
addEventListener('click', () => { animation.classList.toggle('active'); animationEventLog.textContent = ''; iterationCount = 0; let active = animation.classList.contains('active'); if (active) { applyAnimation.textContent = "Cancel animation"; } ...
HTMLElement: gotpointercapture event - Web APIs
e(). Bubbles Yes Cancelable No Interface PointerEvent Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture() on the element on a pointerdown event, which will trigger gotpointercapture. ...
... Event handler property ongotpointercapture Examples This example gets a <p> element and listens for the gotpointercapture event. It then calls setPointerCapture() on the element on a pointerdown event, which will trigger gotpointercapture. ...
...r('p'); para.
addEventListener('gotpointercapture', () => { console.log('I\'ve been captured!') }); para.
addEventListener('pointerdown', (event) => { para.setPointerCapture(event.pointerId); }); The same example, using the ongotpointercapture event handler property: const para = document.querySelector('p'); para.ongotpointercapture = () => { console.log('I\'ve been captured!') }; para.
addEventListener('pointerdown', (event) => { para.setPointerCapture(event.pointerId); }); Specifications Specification Status Pointer Events Obsolete ...
HTMLElement: lostpointercapture event - Web APIs
Cancelable No Interface PointerEvent Event handler property onlostpointercapture Examples This example listens for the lostpointercapture event for an element, and captures the pointer for the element on pointerdown. When the user subsequently releases the pointer, the lostpointercapture event will be fired. ...
...lostpointercapture Examples This example listens for the lostpointercapture event for an element, and captures the pointer for the element on pointerdown. When the user subsequently releases the pointer, the lostpointercapture event will be fired. ...
... para.
addEventListener('lostpointercapture', () => { console.log('I\'ve been released!') }); para.
addEventListener('pointerdown', (event) => { para.setPointerCapture(event.pointerId); }); The same example, but using the onlostpointercapture event handler property: const para = document.querySelector('p'); para.onlostpointercapture = () => { console.log('I\'ve been released!') }; para.
addEventListener('pointerdown', (event) => { para.setPointerCapture(event.pointerId); }); Specifications Specification Status Pointer Events Obsolete ...
HTMLElement: transitionrun event - Web APIs
The transitionrun event is fired when a CSS transition is first created, i.e. before any transition-delay has begun. ...
...bbles Yes Cancelable No Interface TransitionEvent Event handler property ontransitionrun Examples This code adds a listener to the transitionrun event: el.
addEventListener('transitionrun', () => { console.log('Transition is running but hasn\'t necessarily started transitioning yet'); }); The same, but using the ontransitionrun property instead of
addEventListener(): el.ontransitionrun = () => { console.log('Transition started running, and will start transitioning when the transition delay has expired'); }; Live example In the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">Hover over me</div> <div class="message"></div> .transition { width: 100px; height: 100px; backg...
...,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. const el = document.querySelector('.transition'); const message = document.querySelector('.message'); el.
addEventListener('transitionrun', function() { message.textContent = 'transitionrun fired'; }); el.
addEventListener('transitionstart', function() { message.textContent = 'transitionstart fired'; }); el.
addEventListener('transitionend', function() { message.textContent = 'transitionend fired'; }); The difference is that: transitionrun fires when the transition is created (i.e. at the start of any d...
HTMLElement: transitionstart event - Web APIs
The transitionstart event is fired when a CSS transition has actually started, i.e., after any transition-delay has ended. ...
...nsition-delay has ended. ...
...ion-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } To this, we'll add some JavaScript to indicate where the transitionstart and transitionrun events fire. const transition = document.querySelector('.transition'); const message = document.querySelector('.message'); transition.
addEventListener('transitionrun', function() { message.textContent = 'transitionrun fired'; }); transition.
addEventListener('transitionstart', function() { message.textContent = 'transitionstart fired'; }); transition.
addEventListener('transitionend', function() { message.textContent = 'transitionend fired'; }); The difference is that: transitionrun fires when the transition is created (i.e. at the...
HTMLTrackElement: cuechange event - Web APIs
ires when a TextTrack has changed the currently displaying cues. The event is fired at both the TextTrack and at the HTMLTrackElement in which it's being presented, if any. ...
...the currently displaying cues. The event is fired at both the TextTrack and at the HTMLTrackElement in which it's being presented, if any. ...
...ceives a cuechange event every time the currently-presented cue is changed. This happens even if the track isn't associated with a media element. If the track is associated with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the HTMLTrackElement. ...
IDBRequest: error event - Web APIs
Cancelable No Interface Event Event handler property onerror Examples This example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given taskTitle already exists): // Open the database const DBOpenRequest = window.indexedDB.open('toDoList', 4); DBOpenRequest.
addEventListener('upgradeneeded', event => { const db = event.target.result; db.onerror = () => { console.log('Error creating database'); }; // Create an objectStore for this database var objectStore = db.createObjectStore('toDoList', { keyPath: 'taskTitle' }); // define what data items the objectStore will contain objectStore.createIndex('hours', 'hours', { unique: false }); objectStore.cr...
... }); // define what data items the objectStore will contain objectStore.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }); DBOpenRequest.
addEventListener('success', event => { const db = DBOpenRequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); const objectStore = transaction.objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2020 }; const objectStoreRequest = objectStore.add...
...b = DBOpenRequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); const objectStore = transaction.objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2020 }; const objectStoreRequest = objectStore.add(newItem); objectStoreRequest.
addEventListener('error', () => { console.log(`Error adding new item: ${newItem.taskTitle}`); }); }); The same example, using the onerror property instead of
addEventListener(): // Open the database const DBOpenRequest = window.indexedDB.open('toDoList', 4); DBOpenRequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('Error creating database'); ...
Using IndexedDB - Web APIs
tml('<span class="action-success">' + msg + '</span>'); } function displayActionFailure(msg) { msg = typeof msg != 'undefined' ? ...
...sg + '</span>'); } function displayActionFailure(msg) { msg = typeof msg != 'undefined' ? ...
...This means that a function (e.g. openDb()) that calls open() and onsuccess will return before the onsuccess handler has run. This issue is also true of other request methods such as transacti...
KeyboardEvent.code - Web APIs
ead. Code values The code values for Windows, Linux, and macOS are list on the KeyboardEvent: code values page. Examples Exercising KeyboardEvent HTML <p>Press keys on the keyboard to see what the KeyboardEvent's key and code values are for each one.</p> <div id="output"> </div> CSS #output { font-family: Arial, Helvetica, sans-serif; border: 1px solid black; } JavaScript window.
addEventListener("keydown", function(event) { let str = "KeyboardEvent: key='" + event.key + "' | code='" + event.code + "'"; let el = document.createElement("span"); el.innerHTML = str + "<br/>"; document.getElementById("output").appendChild(el); }, true); Try it out To ensure that keystrokes go to the sample, click in the output box below before pressing keys. Handle keyboard events in...
...(position.y > 399) { position.y = 0; } } The refresh() function handles applying the rotation and position by using an SVG transform. ...
...tion.y - (shipSize.height/2); let transform = "translate(" + x + " " + y + ") rotate(" + angle + " 15 15) "; spaceship.setAttribute("transform", transform); } Finally, the
addEventListener() method is used to start listening for keydown events, acting on each key by updating the ship position and rotation angle, then calling refresh() to draw the ship at its new position and angle. ...
MediaQueryList - Web APIs
g a serialized media query. Methods The MediaQueryList interface inherits methods from its parent interface, EventTarget. addListener() Adds to the MediaQueryList a callback which is invoked whenever the media query status--whether or not the document matches the media queries in the list--changes. This method exists primarily for backward compatibility; if possible, you should instead use
addEventListener() to watch for the change event. removeListener() Removes the specified listener callback from the callbacks to be invoked when the MediaQueryList changes media query status, which happens any time the document switches between matching and not matching the media queries listed in the MediaQueryList. This method has been kept for backward compatibility; if possible, you should generally use rem...
...backs to be invoked when the MediaQueryList changes media query status, which happens any time the document switches between matching and not matching the media queries listed in the MediaQueryList. This method has been kept for backward compatibility; if possible, you should generally use removeEventListener() to remove change notification callbacks (which should have previously been added using
addEventListener()). Events The following events are delivered to MediaQueryList objects: change Sent to the MediaQueryList when the result of running the media query against the document changes. For example, if the media query is (min-width: 400px), the change event is fired any time the width of the document's viewport changes such that its width moves across the 400px boundary in either direction. Als...
... You can find other examples on the individual property and method pages. Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'MediaQueryList' in that specification. Working Draft Initial definiti...
MediaRecorder: dataavailable event - Web APIs
dataavailable event is fired when the MediaRecorder delivers media data to your application for its use. Bubbles No Cancelable No Interface BlobEvent Event handler property ondataavailable For details of the all the possible reasons this event may raise, see the documentation for the event handler property: ondataavailable. ...
...n for its use. Bubbles No Cancelable No Interface BlobEvent Event handler property ondataavailable For details of the all the possible reasons this event may raise, see the documentation for the event handler property: ondataavailable. Examples Using
addEventListener to listen for dataavailable events: ... ...
... The same, but using the ondataavailable event handler property: ... ...
MessagePort: message event - Web APIs
he ports to a different browsing context, such as another <iframe>, using code like this: const channel = new MessageChannel(); const myPort = channel.port1; const targetFrame = window.top.frames[1]; const targetOrigin = 'https://example.org'; const messageControl = document.querySelector('#message'); const channelMessageButton = document.querySelector('#channel-message'); channelMessageButton.
addEventListener('click', () => { myPort.postMessage(messageControl.value); }) targetFrame.postMessage('init', targetOrigin, [channel.port2]); The target can receive the port and start listening for messages on it using code like this: window.
addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.
addEventListener('message', (event) => { received.textContent = event.
...ning for messages on it using code like this: window.
addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.
addEventListener('message', (event) => { received.textContent = event.data; }); myPort.start(); }); Note that the listener must call MessagePort.start() before any messages will be delivered to this port. ...
...myPort = event.ports[0]; myPort.
addEventListener('message', (event) => { received.textContent = event.data; }); myPort.start(); }); Note that the listener must call MessagePort.start() before any messages will be delivered to this port. ...
MessagePort.start() - Web APIs
The start() method of the MessagePort interface starts the sending of messages queued on the port. This method is only needed when using EventTarget.
addEventListener; it is implied when using MessageChannel.onmessage. Note: This feature is available in Web Workers. Syntax port.start() Returns Void. Parameters None. ...
...eature is available in Web Workers. Syntax port.start() Returns Void. Parameters None. ...
... Living Standard ...
PaymentResponse: payerdetailchange event - Web APIs
} Specifications Specification Status Comment Payment Request APIThe definition of 'payerdetailchange event' in that specification. Candidate Recommendation ...
...} Specifications Specification Status Comment Payment Request APIThe definition of 'payerdetailchange event' in that specification. Candidate Recommendation ...
...} Specifications Specification Status Comment Payment Request APIThe definition of 'payerdetailchange event' in that specification. Candidate Recommendation ...
Using the Payment Request API - Web APIs
mentRequest). In the following snippet, a merchant page performs this check, and if it returns true updates the checkout button to use PaymentRequest instead of legacy web forms. const checkoutButton = document.getElementById('checkout-button'); if (window.PaymentRequest) { let request = new PaymentRequest(buildSupportedPaymentMethodNames(), buildShoppingCartDetails()); checkoutButton.
addEventListener('click', function() { request.show().then(function(paymentResponse) { // Handle successful payment }).catch(function(error) { // Handle cancelled or failed payment. For example, redirect to // the legacy web form checkout: window.location.href = '/legacy-web-form-checkout'; }); // Every click on the checkout button should use a new instance of // Paymen...
...ces are known demo for the full code. Recommending a payment app when user has no apps If you select to pay with the BobPay demo payment provider on this merchant page, it tries to call PaymentRequest.show(), while intercepting the NOTSUPPORTEDERR exception. If this payment method is not supported, it redirects to the signup page for BobPay. The code looks something like this: checkoutButton.
addEventListener('click', function() { var request = new PaymentRequest(buildSupportedPaymentMethodData(), buildShoppingCartDetails()); request.show().then(function(paymentResponse) { // Here we would process the payment. For this demo, simulate immediate success: paymentResponse.complete('success') .then(function() { // For demo purposes: introPanel.style.display = 'no...
...ayment() .then(function(res) { if (res) { // The payment handler has pre-authorized a transaction // with some static amount, e.g., USD $1.00. } else { // Pre-authorization failed or payment handler not installed. } }) .catch(function(ex1) { // Unexpected error occurred. }); The payment handler would include the following code: self.
addEventListener('canmakepayment', function(evt) { // Pre-authorize here. let preAuthSuccess = ...; evt.respondWith(preAuthSuccess); }); This payment handler would need to live in a service worker at https://example.com/preauth scope. Note: See our Pre-authorizing transactions demo for the full code. ...
RTCPeerConnection: icecandidate event - Web APIs
d compatibility purposes and does not need to be delivered onward to the remote peer (which is why the code snippet above checks to see if event.candidate is null prior to sending the candidate along. ...
...lete, you know that ICE gathering has just ended. This is a more reliable approach than looking at the individual ICE messages for one indicating that the ICE session is finished. Examples This example creates a simple handler for the icecandidate event that uses a function called sendMessage() to create and send a reply to the remote peer through the signaling server. ...
...gathering has just ended. This is a more reliable approach than looking at the individual ICE messages for one indicating that the ICE session is finished. Examples This example creates a simple handler for the icecandidate event that uses a function called sendMessage() to create and send a reply to the remote peer through the signaling server. ...
RTCPeerConnection.onsignalingstatechange - Web APIs
nalingstatechange = errorHandler; Value Set this to a function which you provide that receives an Event object as input; this contains the signalingstatechange event. This event object doesn't provide details about what changed, but you can examine the signalingState property to determine what the new state is. ...
... Set this to a function which you provide that receives an Event object as input; this contains the signalingstatechange event. This event object doesn't provide details about what changed, but you can examine the signalingState property to determine what the new state is. ...
...nt object doesn't provide details about what changed, but you can examine the signalingState property to determine what the new state is. You may also, as always, set up a handler for the signalingstatechange event using
addEventListener(): myRTCPeerConnection.
addEventListener("signalingstatechange", mySignalingStateChangeHandler); Or, using an anonymous (inline) handler: myRTCPeerConnection.
addEventListener("signalingstatechange", event => { /* handle the event here */ }); Example This snippet shows a handler for signalingstatechange that looks for the "have-local-pranswer" signaling state--indicating that a remote offer has been received and a local description of type "pranswer" has been applied in response. pc.onsignalingstatechange = function(event) { if (pc.signalingState === "have-local...
Using server-sent events - Web APIs
lement = document.createElement("li"); const eventList = document.getElementById("list"); newElement.innerHTML = "message: " + event.data; eventList.appendChild(newElement); } This code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's HTML. ...
...("li"); const eventList = document.getElementById("list"); newElement.innerHTML = "message: " + event.data; eventList.appendChild(newElement); } This code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's HTML. ...
... represented by the field name, followed by a colon, followed by the text data for that field's value. Fields Each message received has some combination of the following fields, one per line: event A string identifying the type of event described. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use
addEventListener() to listen for named events. The onmessage handler is called if no event name is specified for a message. data The data field for the message. When the EventSource receives multiple consecutive lines that begin with data:, it concatenates them, inserting a newline character between each one. Trailing newlines are removed. id The event ID to set the EventSource object's last event ID value. ...
ServiceWorkerGlobalScope.onpush - Web APIs
The ServiceWorkerGlobalScope.onpush event of the ServiceWorkerGlobalScope interface is fired whenever a push message is received by a service worker via a push server. Syntax ServiceWorkerGlobalScope.onpush = function(PushEvent) { ... } self.
addEventListener('push', function(PushEvent) { ... }) Example The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
.... Syntax ServiceWorkerGlobalScope.onpush = function(PushEvent) { ... } self.
addEventListener('push', function(PushEvent) { ... }) Example The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
... Working Draft Initial definition. This event is specified in the Push API, but accessed through ServiceWorkerGlob...
SubtleCrypto.deriveBits() - Web APIs
rivateKey, publicKey) { const sharedSecret = await window.crypto.subtle.deriveBits( { name: "ECDH", namedCurve: "P-384", public: publicKey }, privateKey, 128 ); const buffer = new Uint8Array(sharedSecret, 0, 5); const sharedSecretValue = document.querySelector(".ecdh .derived-bits-value"); sharedSecretValue.classList.add("fade-in"); sharedSecretValue.
addEventListener("animationend", () => { sharedSecretValue.classList.remove("fade-in"); }); sharedSecretValue.textContent = `${buffer}...[${sharedSecret.byteLength} bytes total]`; } // Generate 2 ECDH key pairs: one for Alice and one for Bob // In more normal usage, they would generate their key pairs // separately and exchange public keys securely const generateAlicesKeyPair = window.crypto.subtle.gener...
... // Bob could generate the same secret using his private key and Alice's public key. deriveSharedSecret(alicesKeyPair.privateKey, bobsKeyPair.publicKey); }); }); PBKDF2 In this example we ask the user for a password, then use it to derive some bits using PBKDF2. See the complete code on Gi...
...); const derivedBits = await window.crypto.subtle.deriveBits( { "name": "PBKDF2", salt: salt, "iterations": 100000, "hash": "SHA-256" }, keyMaterial, 256 ); const buffer = new Uint8Array(derivedBits, 0, 5); const derivedBitsValue = document.querySelector(".pbkdf2 .derived-bits-value"); derivedBitsValue.classList.add("fade-in"); derivedBitsValue.
addEventListener("animationend", () => { derivedBitsValue.classList.remove("fade-in"); }); derivedBitsValue.textContent = `${buffer}...[${derivedBits.byteLength} bytes total]`; } const deriveBitsButton = document.querySelector(".pbkdf2 .derive-bits-button"); deriveBitsButton.
addEventListener("click", () => { getDerivedBits(); }); Specifications Specification Status Comment Web...
TextTrack: cuechange event - Web APIs
anged the currently displaying cues. The event is fired at both the TextTrack and at the HTMLTrackElement in which it's being presented, if any. ...
...s. The event is fired at both the TextTrack and at the HTMLTrackElement in which it's being presented, if any. ...
...ceives a cuechange event every time the currently-presented cue is changed. This happens even if the track isn't associated with a media element. If the track is associated with a media element, using the <track> element as a child of the <audio> or <video> element, the cuechange event is also sent to the HTMLTrackElement. ...
VisualViewport - Web APIs
tive to the initial containing block origin of the top edge in CSS pixels. VisualViewport.width Read only Returns the width of the visual viewport in CSS pixels. VisualViewport.height Read only Returns the height of the visual viewport in CSS pixels. VisualViewport.scale Read only Returns the pinch-zoom scaling factor applied to the visual viewport. Events Listen to these events using
addEventListener() or by assigning an event listener to the relevant oneventname property of this interface. resize Fired when the visual viewport is resized. Also available via the VisualViewport.onresize property. scroll Fired when the visual viewport is scrolled. Also available via the VisualViewport.onscroll property. Examples Hiding an overlaid box on zoom This example, taken from the Visual View...
...ay) when the user zooms in. This is a nice way to improve the user experience when zooming in on pages. A live sample is also available. var bottomBar = document.getElementById('bottombar'); var viewport = window.visualViewport; function resizeHandler() { if (viewport.scale > 1.3) bottomBar.style.display = "none"; else bottomBar.style.display = "block"; } window.visualViewport.
addEventListener('resize', resizeHandler); Simulating position: device-fixed This example, also taken from the Visual Viewport README, shows how to use this API to simulate position: device-fixed, which fixes elements to the visual viewport. A live sample is also available. var bottomBar = document.getElementById('bottombar'); var viewport = window.visualViewport; function viewportHandler() { var layoutViewp...
...oundingClientRect().height + viewport.offsetTop; // You could also do this by setting style.left and style.top if you // use width: 100% instead. bottomBar.style.transform = 'translate(' + offsetLeft + 'px,' + offsetTop + 'px) ' + 'scale(' + 1/viewport.scale + ')' } window.visualViewport.
addEventListener('scroll', viewportHandler); window.visualViewport.
addEventListener('resize', viewportHandler); Note: This technique should be used with care; emulating position: device-fixed in this way can result in the fixed element flickering during scrolling. Specifications Specification Status Comment Visual Viewport APIThe definition of 'VisualViewport' in that specification. ...
WakeLockSentinel - Web APIs
se event which can be used to give appropriate UI feedback. The sentinel can be acquired or released via appropriate interactions. ...
... Unknown Initial definition. ...
... Unknown Initial definition. ...
Hello vertex attributes - Web APIs
/x-vertex" id="vertex-shader"> #version 100 precision highp float; attribute float position; void main() { gl_Position = vec4(position, 0.0, 0.0, 1.0); gl_PointSize = 64.0; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 precision mediump float; void main() { gl_FragColor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.
addEventListener("load", setupWebGL, false); var gl, program; function setupWebGL (evt) { window.removeEventListener(evt.type, setupWebGL, false); if (!(gl = getRenderingContext())) return; var source = document.querySelector("#vertex-shader").innerHTML; var vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader,source); gl.compileShader(vertexShader); source = documen...
...er); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { var linkErrLog = gl.getProgramInfoLog(program); cleanup(); document.querySelector("p").innerHTML = "Shader program did not link successfully. ...
...loat32Array([clickXinWebGLCoords]), gl.STATIC_DRAW); gl.drawArrays(gl.POINTS, 0, 1); }, false); } var buffer; function initializeAttributes() { gl.enableVertexAttribArray(0); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.0]), gl.STATIC_DRAW); gl.vertexAttribPointer(0, 1, gl.FLOAT, false, 0, 0); } window.
addEventListener("beforeunload", cleanup, true); function cleanup() { gl.useProgram(null); if (buffer) gl.deleteBuffer(buffer); if (program) gl.deleteProgram(program); } function getRenderingContext() { var canvas = document.querySelector("canvas"); canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; var gl = canvas.getContext("webgl") || canvas.getContext("experim...
Scissor animation - Web APIs
var gl, color = getRandomColor(), position; function setupAnimation (evt) { window.removeEventListener(evt.type, setupAnimation, false); if (!(gl = getRenderingContext())) return; gl.enable(gl.SCISSOR_TEST); gl.clearColor(color[0], color[1], color[2], 1.0); ...
...r window, vertical position in WebGL is // measured from bottom to top. In here we set the initial // position of the square to be at the top left corner of the // drawing buffer. ...
...r timer; function startAnimation(evt) { button.removeEventListener(evt.type, startAnimation, false); button.
addEventListener("click", stopAnimation, false); document.querySelector("strong").innerHTML = "stop"; timer = setInterval(drawAnimation, 17); drawAnimation(); } function stopAnimation(evt) { button.removeEventListener(evt.type, stopAnimation, false); button.
addEventListener("click", startAnimation, false); document.querySelector("strong").innerHTML = "start"; clearInterval(timer); } stopAnimation({type: "click"}); } // Variables to hold the size and velocity of the square. var size = [60, 60], velocity = 3.0; function drawAnimation () { gl.scissor(position[0], position[1], size[0] , size[1]); gl.clear(gl.COLOR_BUFFER_BIT); // Every frame the ver...
Taking still photos with WebRTC - Web APIs
ence to the <canvas> element after the page is done loading. photo This will be a reference to the <img> element after the page is done loading. startbutton This will be a reference to the <button> element that's used to trigger capture. We'll get that after the page is done loading. The startup() function The startup() function is run when the page has finished loading, courtesy of window.
addEventListener(). This function's job is to request access to the user's webcam, initialize the output <img> to a default state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image. Getting element references First, we grab references to the major elements we need to be able to access. function startup() { v...
...lement.play() on the <video>, there's a (hopefully brief) period of time that elapses before the stream of video begins to flow. To avoid blocking until that happens, we add an event listener to video for the canplay event, which is delivered when the video playback actually begins. At that point, all the properties in the video object have been configured based on the stream's format. ...
...e two properties on each element, and setting widths and heights as appropriate. Finally, we set the streaming variable to true to prevent us from inadvertently running this setup code again. Handle clicks on the button To capture a still photo each time the user clicks the startbutton, we need to add an event listener to the button, to be called when the click event is issued: startbutton.
addEventListener('click', function(ev){ takepicture(); ev.preventDefault(); }, false); This method is simple enough: it just calls our takepicture() function, defined below in the section Capturing a frame from the stream, then calls Event.preventDefault() on the received event to prevent the click from being handled more than once. Wrapping up the startup() method There are only two more lines...
Controlling multiple parameters with ConstantSourceNode - Web APIs
the tones. Now let's look at the setup() function, which is our handler for the window's load event; it handles all the initialization tasks that require the DOM to be in place. ...
... our handler for the window's load event; it handles all the initialization tasks that require the DOM to be in place. ...
...Then we get references to the control widgets, setting playButton to reference the play button and volumeControl to reference the slider control that the user will use to adjust the gain on the linked pair of oscillators. Then we assign a handler for the play button's click event (see T...
Example and tutorial: Simple synth keyboard - Web APIs
t exist. if (!Object.entries) { Object.entries = function entries(O) { return reduce(keys(O), (e, k) => concat(e, typeof k === 'string' && isEnumerable(O, k) ? [[k, O[k]]] : []), []); }; } Building the keyboard The setup() function is responsible for building the keyboard and preparing the app to play music. function setup() { noteFreq = createNoteTable(); volumeControl.
addEventListener("change", changeVolume, false); masterGainNode = audioContext.createGain(); masterGainNode.connect(audioContext.destination); masterGainNode.gain.value = volumeControl.value; // Create the keys; skip any that are sharp or flat; for // our purposes we don't need them. Each octave is inserted // into a <div> of class "octave". noteFreq.forEach(function(keys, idx) { let keyList ...
...ms = new Float32Array([0, 0, 1, 0, 1]); cosineTerms = new Float32Array(sineTerms.length); customWaveform = audioContext.createPeriodicWave(cosineTerms, sineTerms); for (i=0; i<9; i++) { oscList[i] = []; } } setup(); The table which maps note names and octaves to their frequenies is created by calling createNoteTable(). An event handler is established (by calling our old friend
addEventListener() to handle change events on the master gain control. This will simply update the master gain node's volume to the new value of the control. Next, we iterate over each octave in the note frequencies table. For each octave, we use Object.entries() to get a list of the notes in that octave. Create a <div> to contain that octave's notes (so we can have a small bit of space drawn between octaves), ...
...eKey(note, octave, freq) { let keyElement = document.createElement("div"); let labelElement = document.createElement("div"); keyElement.className = "key"; keyElement.dataset["octave"] = octave; keyElement.dataset["note"] = note; keyElement.dataset["frequency"] = freq; labelElement.innerHTML = note + "<sub>" + octave + "</sub>"; keyElement.appendChild(labelElement); keyElement.
addEventListener("mousedown", notePressed, false); keyElement.
addEventListener("mouseup", noteReleased, false); keyElement.
addEventListener("mouseover", notePressed, false); keyElement.
addEventListener("mouseleave", noteReleased, false); return keyElement; } After creating the elements that will represent the key and its label, we configure the key's element by setting its class to "key" (which establi...
Window.onbeforeinstallprompt - Web APIs
The Window.onbeforeinstallprompt property is an event handler for processing a beforeinstallprompt, which is dispatched on devices when a user is about to be prompted to "install" a web application. Its associated event may be saved for later and used to prompt the user at a more suitable time. Syntax window.
addEventListener("beforeinstallprompt", function(event) { ... ...
...plication. Its associated event may be saved for later and used to prompt the user at a more suitable time. Syntax window.
addEventListener("beforeinstallprompt", function(event) { ... }); window.onbeforeinstallprompt = function(event) { ...}; Example The following example uses the beforeinstallprompt event to make an install button operable, by using the event inside a click handler. ...
...nt) { ...}; Example The following example uses the beforeinstallprompt event to make an install button operable, by using the event inside a click handler. ...
window.postMessage() - Web APIs
target discloses the data you send to any interested malicious site. transfer Optional Is a sequence of Transferable objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. The dispatched event otherWindow can listen for dispatched messages by executing the following JavaScript: window.
addEventListener("message", receiveMessage, false); function receiveMessage(event) { if (event.origin !== "http://example.org:8080") return; // ... } The properties of the dispatched message are: data The object passed from the other window. origin The origin of the window that sent the message at the time postMessage was called. This string is the concatenation of the protocol and "://", the ho...
... changed its location. popup.postMessage("hello there!", "http://example.com"); function receiveMessage(event) { // Do we trust the sender of this message? (might be // different from what we originally opened, for example). ...
...ng you've verified the origin of the received message (which // you must do in any case), a convenient idiom for replying to a // message is to call postMessage on event.source and provide // event.origin as the targetOrigin. event.source.postMessage("hi there yourself! the secret response " + "is: rheeeeet!", event.origin); } window.
addEventListener("message", receiveMessage, false); Notes Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. This cannot be overstated: Failure to ch...
WindowEventHandlers.onbeforeunload - Web APIs
ndler for processing beforeunload events. These events fire when a window is about to unload its resources. At this point, the document is still visible and the event is still cancelable. Note: To combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. Moreover, some don't display them at all. Syntax window.
addEventListener("beforeunload", function(event) { ... }); window.onbeforeunload = function(event) { ... }; Typically, it is better to use window.
addEventListener() and the beforeunload event, instead of onbeforeunload. Example This example prompts the user before unloading. The HTML specification states that authors should use the Event.preventDefault() method instead of using Event.returnValue to prompt the...
..., function(event) { ... }); window.onbeforeunload = function(event) { ... }; Typically, it is better to use window.
addEventListener() and the beforeunload event, instead of onbeforeunload. Example This example prompts the user before unloading. The HTML specification states that authors should use the Event.preventDefault() method instead of using Event.returnValue to prompt the user. ...
...thod instead of using Event.returnValue to prompt the user. window.
addEventListener('beforeunload', function (e) { // Cancel the event e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown // Chrome requires returnValue to be set e.returnValue = ''; }); Guarantee the browser unload by removing the returnValue property of the event window.
addEventListener('beforeunload', function (e) { // the absence of a returnValue property on the event will guarantee the browser unload happens delete e['returnValue']; }); Notes When your page uses JavaScript to render content, the JavaScript may stop when leaving and then navigating back to the page. You can bind to window.onbeforeunload to prevent the browser from fully caching the page. If you do so, Ja...
WindowEventHandlers.onhashchange - Web APIs
property of the WindowEventHandlers mixin is the EventHandler for processing hashchange events. The hashchange event fires when a window's hash changes (see Window.location and HTMLHyperlinkElementUtils.hash). Syntax Using an event handler: window.onhashchange = funcRef; Using an HTML event handler: <body onhashchange="funcRef();"> Using an event listener: To add an event listener, use
addEventListener(): window.
addEventListener("hashchange", funcRef, false); Parameters funcRef A reference to a function. Examples Using an event handler This example uses an event handler (window.onhashchange) to check the new hash value whenever it changes. If it equals #cool-feature, the script logs a message to the console. function locationHashChanged() { if (location.hash === '#cool-feature') {...
...gs a message to the console. function locationHashChanged() { if (location.hash === '#cool-feature') { console.log("You're visiting a cool feature!"); } } window.onhashchange = locationHashChanged; Using an event listener This example uses an event listener to log a notification whenever the hash has changed. function hashHandler() { console.log('The hash has changed!'); } window.
addEventListener('hashchange', hashHandler, false); Overriding the hash This function sets a new hash dynamically, setting it randomly to one of two values. function changeHash() { location.hash = (Math.random() > 0.5) ? 'location1' : 'location2'; } The hashchange event The dispatched hashchange event has the following properties: Field Type Description newURL DOMString The...
... Field Type Description newURL DOMString The new URL to which the window is navigating. oldURL DOMString The previous URL from which the window was navigated. ...
Worker: messageerror event - Web APIs
The messageerror event is fired on a Worker object when it receives a message that can't be deserialized. ...
... on a Worker object when it receives a message that can't be deserialized. ...
...able No Interface MessageEvent Event handler property onmessageerror Examples Create a worker, and listen for message and messageerror events using
addEventListener(): // inside main.js const worker = new Worker("static/scripts/worker.js"); worker.
addEventListener("message", (event) => { console.error(`Received message from worker: ${event}`); }); worker.
addEventListener("messageerror", (event) => { console.error(`Error receiving message from worker: ${event}`); }); The same, but using the onmessageerror event handler property: // inside main.js const worker = new Worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.error(`Received message from worker: ${event}`); }; worker.onmessageerror = (event) => { console.error(`Error...
msthumbnailclick - Web APIs
l not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The msthumbnailclick event occurs when a user clicks a button or thumbnail icon in the taskbar. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax Event Property object.onmsthumbnailclick = handler;
addEventListener Method object.
addEventListener("msthumbnailclick", handler, useCapture) General info Synchronous No Bubbles No Cancelable No Note The onmsthumbnailclick event is available only to documents that are launched from a pinned site shortcut. Parameters pEvtObj [in] Type: IHTMLEventObj Pointer to an IHTMLEventObj interface for the current event. Example function thumbnail...
... General info Synchronous No Bubbles No Cancelable No Note The onmsthumbnailclick event is available only to documents that are launched from a pinned site shortcut. Parameters pEvtObj [in] Type: IHTMLEventObj Pointer to an IHTMLEventObj interface for the current event. ...
...ntListener('msthumbnailclick', thumbnailClickHandler); Example 2 // Adds an overlay icon on your app pinned to the taskbar window.external.msSiteModeSetIconOverlay(iconUri, toolTip); // removes an overlay icon window.external.msSiteModeClearIconOverlay(); // pinned icons on your taskbar can be instructed to trigger specific events on your site from the taskbar // add an event handlerdocument.
addEventListener('msthumbnailclick', onButtonClicked, false); // add the buttons var btnPlay = window.external.msSiteModeAddThumbBarButton(iconUri, toolTip); // refresh the taskbar window.external.msSiteModeShowThumbBar(); // call a javascript function when the button is pressed function onButtonClicked(e) { switch (e.buttonID) { case btnPlay: play(); break;} } See also Microsoft API extensi...
ARIA: tab role - Accessibility
lement. We then find all tabs with aria-selected=true inside the parent element and sets it to false, then sets the triggering element's aria-selected to true. After that, we find all tabpanel elements in the grandparent element, make them all hidden, and finally select the element whose id is equal to the triggering tab's aria-controls and removes the hidden attribute, making it visible. ...
...ll hidden, and finally select the element whose id is equal to the triggering tab's aria-controls and removes the hidden attribute, making it visible. ...
...ing it visible. ...
Media buffering, seeking, and time ranges - Developer guides
dio = document.getElementById('my-audio'); var myCanvas = document.getElementById('my-canvas'); var context = myCanvas.getContext('2d'); context.fillStyle = 'lightgray'; context.fillRect(0, 0, myCanvas.width, myCanvas.height); context.fillStyle = 'red'; context.strokeStyle = 'white'; var inc = myCanvas.width / myAudio.duration; // display TimeRanges myAudio.
addEventListener('seeked', function() { for (i = 0; i < myAudio.buffered.length; i++) { var startX = myAudio.buffered.start(i) * inc; var endX = myAudio.buffered.end(i) * inc; var width = endX - startX; context.fillRect(startX, 0, width, myCanvas.height); context.rect(startX, 0, width, myCanvas.height); context.stroke(); } }); } This works bette...
... block; height: 100%; background-color: #777; width: 0; } .progress { margin-top: -20px; height: 20px; position: relative; width: 300px; } #progress-amount { display: block; height: 100%; background-color: #595; width: 0; } And the following JavaScript provides our functionality: window.onload = function(){ var myAudio = document.getElementById('my-audio'); myAudio.
addEventListener('progress', function() { var duration = myAudio.duration; if (duration > 0) { for (var i = 0; i < myAudio.buffered.length; i++) { if (myAudio.buffered.start(myAudio.buffered.length - 1 - i) < myAudio.currentTime) { document.getElementById("buffered-amount").style.width = (myAudio.buffered.end(myAudio.buffered.length - 1 - i) / duration) * 100 + "%"; ...
... The timeupdate event is fired 4 times a second ...
Audio and Video Delivery - Developer guides
For more information, see Creating your own custom audio player. Other tips for audio/video Stopping the download of media While stopping the playback of media is as easy as calling the element's pause() method, the browser keeps downloading the...
...rol'); function switchState() { if (myAudio.paused == true) { myAudio.play(); myControl.innerHTML = "pause"; } else { myAudio.pause(); myControl.innerHTML = "play"; } } function checkKey(e) { if (e.keycode == 32 ) { //spacebar switchState(); } } myControl.
addEventListener('click', function() { switchState(); }, false); window.
addEventListener( "keypress", checkKey, false ); } You can try this example out here. For more information, see Creating your own custom audio player. Other tips for audio/video Stopping the download of media While stopping the playback of media is as easy as calling the element's pause() method, the browser keeps downloading the media until the media element is disposed of through garbage collection. Here's...
...The most popular libraries allow you to choose a consistent player design over all browsers and provide a fallback for browsers that don't support audio and video nativ...
DOM onevent handlers - Developer guides
This page focuses on how the latter work. Registering onevent handlers The onevent handlers are properties on certain DOM elements to manage how that element reacts to events. Elements can be interactive (links, buttons, images, forms, and so forth) or non-interactive (such as the base <body> element). Events are actions like: Being clicked Detecting pressed keys Getting focus The onevent handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc. ...
...nttype>: <button onclick="handleClick()">, Or by setting the corresponding property from JavaScript: document.querySelector("button").onclick = function(event) { ... }. An onevent event handler property serves as a placeholder of sorts, to which a single event handler can be assigned. In order to allow multiple handlers to be installed for the same event on a given object, you can call its
addEventListener() method, which manages a list of handlers for the given event on the object. A handler can then be removed from the object by calling its removeEventListener() function. When an event occurs that applies to an element, each of its event handlers is called to allow them to handle the event, one after another. You don't need to call them yourself, although you can do so in many cases to easily si...
...on or object that is registered to be notified of events Or more specifically, to the mechanism of registering event listeners via on... attributes in HTML or properties in Web APIs, such as <button onclick="alert(this)"> or window.onload = function() { ... }. When discussing the various methods of listening to events: Event listener refers to a function or object registered via EventTarget.
addEventListener() Event handler refers to a function registered via on... attributes or properties Specifications Specification Status Comment HTML Living StandardThe definition of 'event handlers' in that specification. Living Standard HTML5The definition of 'event handlers' in that specification. Recommendation Browser compatibility Detecting the p...
Overview of events and handlers - Developer guides
eb browsers which define many events emitted in response to user input or browser activity. Modern web browsers follow the event pattern using a standardized approach. Browsers use as the data structure for the properties of the event, an object derived from the EventPrototype object. Browsers use as the registration method for the function which will handle those data structures a method called
addEventListener which expects as arguments a string event type name and the handler function. Finally, browsers define a large number of objects as event emitters and define a wide variety of event types generated by the objects. Button event handler demo For example, browser <button> elements are intended to emit events named 'click' in response to a mouse click or, when displayed in touch sensitive surfaces,...
... This code relies on the agreement that there is a kind of event called 'click' which will call any listener (or 'handler') function with an Event object argument (actually, in this case a derivativ...
...ed into web pages is wrapped into an event function call to ensure that the code is only executed when the HTML has been processed and is available for alteration or decoration. For example, code might be attached as: var funcInit = function(){ // user code goes here and can safely address all the HTML elements from the page // since the document has successfully been 'loaded' } document.
addEventListener('DOMContentLoaded', funcInit); so that this code will only be executed after the document object emits the 'DOMContentLoaded' event because the HTML has been parsed and Javasript objects created representing each of the nodes of the HTML document. Note that in this example, the code does not even name the event argument to the function because the code never needs to use the data structure desc...
<input type="checkbox"> - HTML: Hypertext Markup Language
the recipe name's checkbox is set to indeterminate. If all three are checked, the recipe name's checkbox is set to checked. So in this case the indeterminate state is used to state that collecting the ingredients has started, but the recipe is not yet complete. ...
... case the indeterminate state is used to state that collecting the ingredients has started, but the recipe is not yet complete. ...
... Living Standard HTML5The definition of '...
Browser detection using the user agent - HTTP
What you want to do for screen size is not slash off information on smaller screens. That will only annoy people because it will force them to use the desktop version. Rather, try to have fewer columns of information in a longer page on smaller screens while having more columns with a shorter page on larger screen sizes. This effe...
... ? function(mQ, f) { if(/height|width/.test(mQ.media)) mqL.push([mQ, f]); mQ.addListener(f), mQ.addListener(whenMediaChanges); } : function(){}; var destroyMediaQuery = isWebkit ? ...
...ener(whenMediaChanges); } : function(){}; var destroyMediaQuery = isWebkit ? function(mQ) { for (var i=0,len=mqL.length|0; i<len; i=i+1|0) if (mqL[i][0] === mQ) mqL.splice(i, 1); mQ.removeListener(whenMediaChanges); } : listenToMediaQuery; var orientationChanged = false;
addEventListener("orientationchange", function(){ orientationChanged = true; }, PASSIVE_LISTENER_OPTION);
addEventListener("resize", setTimeout.bind(0,function(){ if (orientationChanged && !mediaQueryUpdated) for (var i=0,len=mqL.length|0; i<len; i=i+1|0) mqL[i][1]( mqL[i][0] ); mediaQueryUpdated = orientationChanged = false; },0)); Which part of the user agent contains the information you are looking for? As there is no uniformity of the different part of the user agent string, this is ...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
e very useful when combined with them. Let's look at them in isolation to begin with. Request permission To show a notification, we have to request permission to do so first. Instead of showing the notification immediately though, best practice dictates that we should show the popup when the user requests it by clicking on a button: var button = document.getElementById("notifications"); button.
addEventListener('click', function(e) { Notification.requestPermission().then(function(result) { if(result === 'granted') { randomNotification(); } }); }); This shows a popup using the operating system's own notifications service: When the user confirms to receive notifications, the app can then show them. The result of the user action can be default, granted or denied. The...
...lowing everyone to send push messages unsecured using your app would be a terrible idea. See the Web Push data encryption test page for detailed information about securing the server. The server stores all the information received when the user subscribed, so the messages can be sent later on when needed. To receive push messages, we can listen to the push event in the Service Worker file: self.
addEventListener('push', function(e) { /* ... */ }); The data can be retrieved and then shown as a notification to the user immediately. This, for example, can be used to remind the user about something, or let them know about new content being available in the app. Push example Push needs the server part to work, so we're not able to include it in the js13kPWA example hosted on GitHub Pages, as it offers host...
...event.data.text() : 'no payload'; event.waitUntil( self.registration.showNotification('ServiceWorker Cookbook', { body: payload, }) ); }); All it does is add a listener for the push event, create the payload variable consisting of the text taken from the data (or create a string to use if data is empty...
Structural overview of progressive web apps - Progressive web apps (PWAs)
egisters a service worker: if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/pwa-examples/js13kpwa/sw.js"); } After that, the app adds a handler for clicks on a button whose ID is notifications; this handler requests permission to send notifications to the user, then generates and sends a random notification. ...
...kpwa/icons/icon-256.png', '/pwa-examples/js13kpwa/icons/icon-512.png' ]; var gamesImages = []; for(var i=0; i<games.length; i++) { gamesImages.push('data/img/'+games[i].slug+'.jpg'); } var contentToCache = appShellFiles.concat(gamesImages); With the file list prepared, it's time to install the service worker itself. The service worker will actually handle caching all the listed files. ...
... caches.open(cacheName).then(function(cache) { console.log('[Service Worker] Caching all: app shell and content'); return cache.addAll(contentToCache); }) ); }); With that done, we implement the service worker's fetch event handler; its job is to return the contents of the specified file, either from the cache or by loading it over the network (caching it upon doing so): self.
addEventListener('fetch', function(e) { e.respondWith( caches.match(e.request).then(function(r) { console.log('[Service Worker] Fetching resource: '+e.request.url); return r || fetch(e.request).then(function(response) { return caches.open(cacheName).then(function(cache) { console.log('[Service Worker] Caching new resource: '+e.request.url); cache.put(e.request, respon...
Scripting - SVG: Scalable Vector Graphics
One can override default browser behaviors with the evt.preventDefault( ) method, add eventListeners to objects with the syntax element.
addEventListener(event, function, useCapture), and set element properties with syntax svgElement.style.setProperty("fill-opacity", "0.0", ""). Note the existence of all three arguments setting properties. Preventing default behavior in event code When writing drag and drop code, sometimes you'll find that text on the page gets accidently selected while dragging. ...
... When writing drag and drop code, sometimes you'll find that text on the page gets accidently selected while dragging. Or if you want to use the backspace key in your code, you want to override the browser's default behavior when the backspace key is pressed, which is to go back to the previous page. The evt.preventDefault() method lets you do this. Using eventListeners with objects The methods
addEventListener() and removeEventListener() are very useful when writing interactive SVG. You can pass an object that implements the handleEvent interface as the second parameter to these methods. function myRect(x,y,w,h,message){ this.message=message this.rect=document.createElementNS("http://www.w3.org/2000/svg","rect") this.rect.setAttributeNS(null,"x",x) this.rect.setAttributeNS(null,"y",y) this.rect.
...ace as the second parameter to these methods. function myRect(x,y,w,h,message){ this.message=message this.rect=document.createElementNS("http://www.w3.org/2000/svg","rect") this.rect.setAttributeNS(null,"x",x) this.rect.setAttributeNS(null,"y",y) this.rect.setAttributeNS(null,"width",w) this.rect.setAttributeNS(null,"height",h) document.documentElement.appendChild(this.rect) this.rect.
addEventListener("click",this,false) this.handleEvent= function(evt){ switch (evt.type){ case "click": alert(this.message) break; } } } Inter-document scripting: referencing embedded SVG When using SVG within HTML, Adobe's SVG Viewer 3.0 automatically includes a window property called svgDocument that points to the SVG document. This is not the case for Mozilla's native SVG impleme...
Forms related code snippets - Archive of obsolete content
document.attachEvent("onmousedown", onDocClick) : (document.onmousedown = onDocClick); })(); </script> <style type="text/css"> table.zdp-calend...
..."Oct", "Nov", "Dec"], sDays = ["M", "T", "W", "T", "F", "S", "S"], bZeroIsMonday = true, /* internal usage */ aInstances = [], aMonthLengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], rBgnNaN = /^\D+/, rBgnANDEnd = /^\D+|\D+\d+$/g, rMonth = /\-month\-/, rDecrease = /\-decr\-/; var /* customizable by user */ nZIndex = 1000; window.
addEventListener ?
addEventListener("load", buildCalendars, false) : window.attachEvent ? attachEvent("onload", buildCalendars) : (onload = buildCalendars); document.
addEventListener ? document.
addEventListener("mousedown", onDocClick, false) : document.attachEvent ? document.attachEvent("onmousedown", onDocClick) : (document.onmousedown = onDocClick); })(); </script> <style type="text/css"> table.zdp-calendar { border: 1px ...
HTML to DOM - Archive of obsolete content
d(frame); // or // document.documentElement.appendChild(frame); // set restrictions as needed frame.webNavigation.allowAuth = false; frame.webNavigation.allowImages = false; frame.webNavigation.allowJavascript = false; frame.webNavigation.allowMetaRedirects = true; frame.webNavigation.allowPlugins = false; frame.webNavigation.allowSubframes = false; // listen for load frame.
addEventListener("load", function (event) { // the document of the HTML in the DOM var doc = event.originalTarget; // skip blank page or frame if (doc.location.href == "about:blank" || doc.defaultView.frameElement) return; // do something with the DOM of doc alert(doc.location.href); // when done remove frame or set location "about:blank" setTimeout(function (){ var frame =...
...The most interesting piece of code here is the DOMContentLoaded event listener we define for the element. Let's take a look at the donkeyfire.donkeybrowser_onPageLoad() handler: donkeybrowser_onPageLoad: function(aEve...
Progress Listeners - Archive of obsolete content
Example: Example of listener for anchor change The above example "Notification whe...
... Example: Example of listener for anchor change The above example "Notification when the value in Address Bar changes" fires multiple times, one of which is w...
Communication between HTML and your extension - Archive of obsolete content
em all in many different ways. Some of the events only apply to certain types of elements so I included trying to modify the result of the AJAX request to be of the appropriate element type (img, which supports "onLoad," rather than span, which doesn't, for example). The problem with the events is the timing. I wasn't sure about the difference between the capture or bubbling flag that you pass to
addEventListener but every time I would catch the event in the extension, the element from the AJAX request wasn't fully updated into the HTML page. What that meant is that everytime the extension went looking for the element, it wasn't there yet. As a last ditch effort I tried setting a timeout using setTimeout when I got the event in the extension to wait a few milliseconds before looking for the desired elemen...
...ument.body.dispatchEvent(event); In the code of the extension that catches the loading of a new page I added this code: var doc = aEvent.originalTarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a Location object (see below for a link). // You can use it to make your code executed on certain pages only. if (doc && doc.
addEventListener) doc.
addEventListener("my-custom-event", myExtension.customReceived, false); Since the event is dispatched after the element in the HTML is updated by the statusChanged function, the element that extension is looking for is there to find. ...
Index - Archive of obsolete content
om toolbar (SM ver. 1.x) Add-ons, Extensions, SeaMonkey This page tells you step-by-step how to make a custom toolbar button in SeaMonkey 1.x. (For SeaMonkey 2, Firefox, Thunderbird and Sunbird, see the page: Custom Toolbar Button) 1692 Toolbar customization events Toolbars, XUL When toolbars are customized, events are sent to their parent window. You can use window.
addEventListener() to listen for these events in order to keep abreast of changes to toolbars. 1693 Tree Widget Changes XUL This describes changes in XUL Trees API for Gecko 1.8. 1694 Urlbar-icons XUL Reference, XUL_Element The location of UI elements like the bookmarks, feed and go buttons. Create new image or button child elements to add your own items. 1695 ...
...Firefox 1.5. 1708 XUL Coding Style Guidelines XUL No summary! 1709 XUL Event Propagation DOM, XUL No summary! 1710 XUL Events Mozilla, Non-standard, Overview, Reference, XUL, XUL_Events, events The following tables and sections describe the event handler that are valid for most XUL elements. The events listeners can be attached using
addEventListener and removed using removeEventListener. 1711 CheckboxStateChange Event, events The CheckboxStateChange event is executed when the state of a <checkbox> element has changed. 1712 DOMMenuItemActive The DOMMenuItemActive event is executed when a <menu> or a <menuitem> has been hovered or highlighted. 1713 DOMMenuItemInactive The DOMMen...
XUL Events - Archive of obsolete content
Some of the events can be attached using attributes as well. When attaching event listeners using attributes, be aware that only one listener can be attached at a time. Any previously attached listeners are disconnected. The attribute name is the event name with an 'on' prefix. ...
...s event bubbles. DOMMenuItemInactive This event is sent when a menu or menuitem is no longer being hovered over, or highlighted. This event bubbles. Window events The following events are dispatched to top-level DOM windows and can be listened to using window.
addEventListener. Event Description activate Sent when a window becomes active. deactivate Sent when a window becomes inactive. sizemodechange Sent when a window is minimized or un-minimized, switche...
Index - Archive of obsolete content
tom toolbar (SM ver. 1.x) Add-ons, Extensions, SeaMonkey This page tells you step-by-step how to make a custom toolbar button in SeaMonkey 1.x. (For SeaMonkey 2, Firefox, Thunderbird and Sunbird, see the page: Custom Toolbar Button) 961 Toolbar customization events Toolbars, XUL When toolbars are customized, events are sent to their parent window. You can use window.
addEventListener() to listen for these events in order to keep abreast of changes to toolbars. 962 Tree Widget Changes XUL This describes changes in XUL Trees API for Gecko 1.8. 963 Urlbar-icons XUL Reference, XUL_Element The location of UI elements like the bookmarks, feed and go buttons. Create new image or button child elements to add your own items. 964 Usi...
...or Firefox 1.5. 977 XUL Coding Style Guidelines XUL No summary! 978 XUL Event Propagation DOM, XUL No summary! 979 XUL Events Mozilla, Non-standard, Overview, Reference, XUL, XUL_Events, events The following tables and sections describe the event handler that are valid for most XUL elements. The events listeners can be attached using
addEventListener and removed using removeEventListener. 980 CheckboxStateChange Event, events The CheckboxStateChange event is executed when the state of a <checkbox> element has changed. 981 DOMMenuItemActive The DOMMenuItemActive event is executed when a <menu> or a <menuitem> has been hovered or highlighted. 982 DOMMenuItemInactive The DOMMenuIt...
PopupEvents - Archive of obsolete content
pdated and the popup is visible. One possible use of the popupshown event is to open another menu. This technique, as shown in the following example, is needed if you wish to open a submenu programmatically. This is because you cannot open a submenu directly without first opening the parent menu. ...
...enupopup"> <menu id="open-menu" label="Open"> <menupopup> <menuitem label="File..."/> <menuitem label="Page"/> </menupopup> </menu> </menupopup> </menu> <button label="Open" oncommand="openFileMenu();"/> When the button is pressed, the openFileMenu function is called. Within this function, a popupshown event listener is attached to the 'File' menu using the
addEventListener method. This will cause the fileMenuOpened function to be called when the popupshown event is fired on the 'File' menu. The fileMenuOpened function first checks that the target of the event is the right popup and returns early if not. Next, the popupshown event listener is removed again. We need to make sure to do this to ensure that the event listener isn't added multiple times. Finally, we use ...
More Event Handlers - Archive of obsolete content
<< PreviousNext >> In this section, the event object is examined and additional events are described. The Event Object Every event handler is passed an event object. In the attribute form of the event handler, the event object is an implied argument to the script code which can be referred to using the name 'event'. In the
addEventListener form, the first argument passed to the listener function will be the event object. Other arguments can be passed to a listener function, if required. The event object has a number of properties which can be examined during an event. For a full list, see the reference. We already saw the event's target property in the last section. It holds a reference to the element where the event occurred. A similar property currentTarget holds the element that is cur...
...propagation, call the event object's stopPropagation method, as in the following example. Example 2 : Source View <hbox id="outerbox"> <button id="okbutton" label="OK"/> </hbox> <script> function buttonPressed(event){ alert('Button was pressed!'); } function boxPressed(event){ alert('Box was pressed!'); event.stopPropagation(); } var button = document.getElementById("okbutton"); button.
addEventListener('command',buttonPressed,true); var outerbox = document.getElementById("outerbox"); outerbox.
addEventListener('command',boxPressed,true); </script> Here, an event listener has been added to the button and another event listener has been added to the box. The stopPropagation method has been called in the box's listener, so the button's listener never gets called. If this call was removed, both li...
Audio for Web games - Game development
onds. The "countdown.mp3" MP3 file consists of a number being spoken every 2 seconds, the idea being that we play back that number when the corresponding button is pressed. Let's add some JavaScript to make this work: var myAudio = document.getElementById('myAudio'); var buttons = document.getElementsByTagName('button'); var stopTime = 0; for (var i = 0; i < buttons.length; i++) { buttons[i].
addEventListener('click', function() { myAudio.currentTime = this.getAttribute("data-start"); stopTime = this.getAttribute("data-stop"); myAudio.play(); }, false); } myAudio.
addEventListener('timeupdate', function() { if (this.currentTime > stopTime) { this.pause(); } }, false); Note: You can try out our audio sprite player live on JSFiddle. Note: On mobile we may need to trigger this ...
... In the context of your game world you may have loops and samples that ...
Desktop gamepad controls - Game development
caniuse.com. The list of supported devices is also quite extensive -- most popular gamepads (e.g. XBox 360 or PS3) should be suitable for web implementations. Pure JavaScript approach Let's think about implementing pure JavaScript gamepad controls in our little controls demo first to see how it would work. ...
... layout: [], cache: [], status: [], pressed: function(button, state) {} } axes: { status: [] } }; The controller variable stores the information about the connected gamepad, and there's an active boolean variable we can use to know if the controller is connected or not. The connect() and disconnect() functions are bound to the following events: window.
addEventListener("gamepadconnected", GamepadAPI.connect); window.
addEventListener("gamepaddisconnected", GamepadAPI.disconnect); They are fired when the gamepad is connected and disconnected respectively. The next function is update(), which updates the information about the pressed buttons and axes. The buttons variable contains the layout of a given controller (for example which buttons are where, because an ...
Paddle and keyboard controls - Game development
les like in the example. Add these lines somewhere near the rest of your variables: var rightPressed = false; var leftPressed = false; The default value for both is false because at the beginning the control buttons are not pressed. To listen for key presses, we will set up two event listeners. Add the following lines just above the setInterval() line at the bottom of your JavaScript: document.
addEventListener("keydown", keyDownHandler, false); document.
addEventListener("keyup", keyUpHandler, false); When the keydown event is fired on any of the keys on your keyboard (when they are pressed), the keyDownHandler() function will be executed. The same pattern is true for the second listener: keyup events will fire the keyUpHandler() function (when the keys stop being pressed). Add these to your code now, ...
..., keyDownHandler, false); document.
addEventListener("keyup", keyUpHandler, false); When the keydown event is fired on any of the keys on your keyboard (when they are pressed), the keyDownHandler() function will be executed. The same pattern is true for the second listener: keyup events will fire the keyUpHandler() function (when the keys stop being pressed). ...
Styling lists - Learn web development
mlCode = htmlInput.value; var cssCode = cssInput.value; var output = document.querySelector(".output"); var solution = document.getElementById("solution"); var styleElem = document.createElement('style'); var headElem = document.querySelector('head'); headElem.appendChild(styleElem); function drawOutput() { output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; } reset.
addEventListener("click", function() { htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput(); }); solution.
addEventListener("click", function() { htmlInput.value = htmlCode; cssInput.value = 'ul {\n list-style-type: square;\n}\n\nul li, ol li {\n line-height: 1.5;\n}\n\nol {\n list-style-type: lower-alpha\n}'; drawOutput(); }); htmlInput.
addEventListener("input", drawOutput); cssInpu...
...click", function() { htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput(); }); solution.
addEventListener("click", function() { htmlInput.value = htmlCode; cssInput.value = 'ul {\n list-style-type: square;\n}\n\nul li, ol li {\n line-height: 1.5;\n}\n\nol {\n list-style-type: lower-alpha\n}'; drawOutput(); }); htmlInput.
addEventListener("input", drawOutput); cssInput.
addEventListener("input", drawOutput); window.
addEventListener("load", drawOutput); ...
UI pseudo-classes - Learn web development
aaa; } We've directly selected the inputs we want to disable using input[type="text"]:disabled, but we also wanted to gray out the corresponding text labels. These weren't quite as easy to select, so we've used a class to provide them with that styling. ...
...text labels. These weren't quite as easy to select, so we've used a class to provide them with that styling. ...
Adding vector graphics to the Web - Learn web development
; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Sho...
...n; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Show solution'; } updateCode(); }); const htmlSolution = ''; let solutionEntry = htmlSolution; textarea.
addEventListener('input', updateCode); window.
addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur(); } }; function insertAtCaret(text) { const scrollPos = textarea.scrol...
From object to iframe — other embedding technologies - Learn web development
; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getElementById('code'); const reset = document.getElementById('reset'); const solution = document.getElementById('solution'); const output = document.querySelector('.output'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.
addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = htmlSolution; solution.value = 'Show solution'; updateCode(); }); solution.
addEventListener('click', function() { if(solution.value === 'Show solution') { textarea.value = solutionEntry; solution.value = 'Hide solution'; } else { textarea.value = userEntry; solution.value = 'Sho...
...\n\n<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d37995.65748333395!2d-2.273568166412784!3d53.473310471916975!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x487bae6c05743d3d%3A0xf82fddd1e49fc0a1!2sThe+Lowry!5e0!3m2!1sen!2suk!4v1518171785211" width="600" height="450" frameborder="0" style="border:0" allowfullscreen>\n</iframe>'; let solutionEntry = htmlSolution; textarea.
addEventListener('input', updateCode); window.
addEventListener('load', updateCode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keyCode === 9) { e.preventDefault(); insertAtCaret('\t'); } if (e.keyCode === 27) { textarea.blur(); } }; function insertAtCaret(text) { const scrollPos = textarea.scrol...
General asynchronous programming concepts - Learn web development
the processor. Let's look at a couple of examples that show what we mean by blocking. ...
...d fills the available <canvas> with 1 million blue circles. A "Click me for alert" button that when clicked shows an alert message. function expensiveOperation() { for(let i = 0; i < 1000000; i++) { ctx.fillStyle = 'rgba(0,0,255, 0.2)'; ctx.beginPath(); ctx.arc(random(0, canvas.width), random(0, canvas.height), 10, degToRad(0), degToRad(360), false); ctx.fill() } } fillBtn.
addEventListener('click', expensiveOperation); alertBtn.
addEventListener('click', () => alert('You clicked me!') ); If you click the first button and then quickly click the second one, you'll see that the alert does not appear until the circles have finished being rendered. The first operation blocks the second one until it has finished running. Note: OK, in our case, it is ugly and we are faking the blocki...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
aw() to start the spinner spinning and display it in the UI, hides the Start button so you can't mess up the game by starting it multiple times concurrently, and runs a setTimeout() call that runs a setEndgame() function after a random interval between 5 and 10 seconds has passed. The following block also adds an event listener to your button to run the start() function when it is clicked. btn.
addEventListener('click', start); function start() { draw(); spinnerContainer.style.display = 'block'; btn.style.display = 'none'; setTimeout(setEndgame, random(5000,10000)); } Note: You'll see this example is calling setTimeout() without storing the return value. (So, not let myTimeout = setTimeout(functionName, interval).) This works just fine, as long as you don't need to clear your interval...
...made to wait a random amount of time before they are asked to press their button. This last part is handled by the setEndgame() function, which you'll define next. ...
Communicating with frame scripts
to prefix messages with your add-on's ID. After the name, you can pass detailed data as a string or a JSON-serializable object, and after that you can pass any objects it wants to pass to content as CPOWs. The example below sends a message named "my-e10s-extension-message", with a data payload containing details and tag properties, and exposes the event.target object as a CPOW: // frame script
addEventListener("click", function (event) { sendAsyncMessage("my-addon@me.org:my-e10s-extension-message", { details : "they clicked", tag : event.target.tagName }, { target : event.target }); }, false); To receive messages from content, a chrome script needs to add a message listener using the message manager's addMessageListener() API. The message passed to the listener is an object con...
...-message", listener); function listener(message) { return "value from chrome"; } This value is then presented to the frame script in the return value of sendSyncMessage(). Because a single message can be received by more than one listener, the return value of sendSyncMessage() is an array of all the values returned from every listener, even if it only contains a single value: // frame script
addEventListener("click", function (event) { var results = sendSyncMessage("my-addon@me.org:my-e10s-extension-message", { details : "they clicked", tag : event.target.tagName }); content.console.log(results[0]); // "value from chrome" }, false); Like arguments, return values from sendSyncMessage() must be JSON-serializable, so chrome can't return functions. removeMessageListener() To stop list...
mozbrowserloadend
top (x) and reload (R), as appropriate. In addition, the background of the controls UI bar is changed to the background color of the site that has just loaded, to provide a more integrated experience. When the front page of https://developer.mozilla.org is loaded, for example, the e.detail.backgroundColor value reported is rgb(0, 83, 159). ...
...rience. When the front page of https://developer.mozilla.org is loaded, for example, the e.detail.backgroundColor value reported is rgb(0, 83, 159). ...
mozbrowserloadstart
nly Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. Example In this example the mozbrowserloadend and mozbrowserloadstart events are used to change the icon shown on the stop/reload button between stop (x) and reload (R), as appropriate. ...
...oolean Whether the event is cancellable or not. Example In this example the mozbrowserloadend and mozbrowserloadstart events are used to change the icon shown on the stop/reload button between stop (x) and reload (R), as appropriate. ...
PromiseWorker.jsm
method` with args `args` return self[method](...args); }; worker.postMessage = function(...args) { // Post a message to the main thread self.postMessage(...args); }; worker.close = function() { // Close the worker self.close(); }; worker.log = function(...args) { // Log (or discard) messages (optional) dump('Worker: ' + args.join(' ') + '\n'); }; // Connect it to message port. self.
addEventListener('message', msg => worker.handleMessage(msg)); AbstractWorker is a base class for the worker, and it's designed to be used by derived class, which provides above four methods (dispatch, postMessage, close, and log). but you can instantiate AbstractWorker itself and set its properties later, instead of creating derived class. Main thread file The BasePromiseWorker object needs to be imported: ...
...= require('resource://gre/modules/workers/PromiseWorker.js'); let worker = new PromiseWorker.AbstractWorker(); worker.dispatch = function(method, args = []) { return self[method](...args); }; worker.postMessage = function(...args) { self.postMessage(...args); }; worker.close = function() { self.close(); }; worker.log = function(...args) { dump('Worker: ' + args.join(' ') + '\n'); }; self.
addEventListener('message', msg => worker.handleMessage(msg)); // start - my functionalities function resolveTest(shouldResolve) { if (shouldResolve) { return 'You sent to PromiseWorker argument of: `' + shouldResolve + '`'; } else { throw new Error('You passed in a non-true value for shouldResolve argument and therefore this will reject the main thread promise'); } } Main thread file bootstrap...
MathML In Action
</mrow> </mfrac> </mrow> </mstyle> </math> </p> JavaScript Content function zoomToggle() { if (this.hasAttribute("mathsize")) { this.removeAttribute("mathsize"); } else { this.setAttribute("mathsize", "200%"); } } function load() { document.getElementById("zoomableMath"). ...
...yle> </math> </p> JavaScript Content function zoomToggle() { if (this.hasAttribute("mathsize")) { this.removeAttribute("mathsize"); } else { this.setAttribute("mathsize", "200%"); } } function load() { document.getElementById("zoomableMath"). ...
L20n Javascript API
eeds to be first registered with registerLocales. ctx.linkResource(function(locale) { return '../locales/' + locale + '/strings.l20n'; }); The resource is added to all registered locales. If there are no registered locales (see registerLocales), the default i-default locale is used. In this case, addResource(String) and linkResource(String) might be better suited for adding resources. ctx.
addEventListener(event: String, callback: Function) Register an event handler on the Context instance. Currently available event types: ready - fired when all resources are available and the Context instance is ready to be used. This event is also fired after each change to locale order (retranslation). error - fired when an error occurs which prevents the Context instance from working correctly or ...
...hain, Compiler.Error, when L20n is unable to evaluate an entity to a string; there are two types of errors in this category: Compiler.ValueError, when L20n can still try to use the literal source string of the entity as fallback, and Compiler.IndexError otherwise. ctx.removeEventListener(event: String, callback: Function) Remove an event listener previously registered with
addEventListener. ctx.updateData(ctxdata: Object) Update the context data which will be available to all entities in the context. The ctxdata is an object which extends the context data per key and per level of hierarchy. In other words, the following two calls: ctx.updateData({ user: { name: "Bob" } }); ctx.updateData({ user: { gender: "masculine" } }); will make the internally-stored context data look l...
nsIMacDockSupport
= win.document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menupopup'); macMenu.setAttribute('id', 'myMacMenu'); var macMenuItem = win.document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem'); macMenuItem.setAttribute('label', 'Show Most Recent Window'); macMenuItem.setAttribute('id', 'myMacMenuItem'); macMenuItem.
addEventListener('command', function(){ var dockSupport = Cc['@mozilla.org/widget/macdocksupport;1'].getService(Ci.nsIMacDockSupport); dockSupport.activateApplication(true); Services.wm.getMostRecentWindow(null).focus() }) macMenu.appendChild(macMenuItem); var mainPopupSet = win.document.getElementById('mainPopupSet'); mainPopupSet.appendChild(macMenu); let dockMenuElement = macMenu; //document.getElementB...
...f the hidden window. This is the recommended way to add to the native menu, just maniuplate the default menu DOM element. ...
nsIWindowMediator
ndow by pressing Ctrl + N and then in the new window, selecting tabs will fire the alert. ...
... domWindow.removeEventListener("load", arguments.callee, false); //this removes this load function from the window //window has now loaded now do stuff to it //as example this will add a function to listen to tab select and will fire alert in that window if (domWindow.gBrowser && domWindow.gBrowser.tabContainer) { domWindow.gBrowser.tabContainer.
addEventListener('TabSelect', function () { domWindow.alert('tab was selected') }, false); } }, false); }, onCloseWindow: function (aWindow) {}, onWindowTitleChange: function (aWindow, aTitle) {} }; //to register Services.wm.addListener(windowListener); //Services.wm.removeListener(windowListener); //once you want to remove this listener execut...
nsIXMLHttpRequest
date) From native code, the way to set up onload and onerror handlers is a bit different. Here is a comment from Johnny Stenback <jst@netscape.com>: The mozilla implementation of nsIXMLHttpRequest implements the interface nsIDOMEventTarget and that's how you're supported to add event listeners. Try something like this: nsCOMPtr<nsIDOMEventTarget> target(do_QueryInterface(myxmlhttpreq)); target->
AddEventListener(NS_LITERAL_STRING("load"), mylistener, PR_FALSE) where mylistener is your event listener object that implements the interface nsIDOMEventListener. The 'onload', 'onerror', and 'onreadystatechange' attributes moved to nsIJSXMLHttpRequest, but if you're coding in C++ you should avoid using those. Though actually, if you use
addEventListener from C++ weird things will happen too, since the result w...
...you only want this if your url is to a zip file or some file you want ...
Browser Console - Firefox Developer Tools
e. This example here makes it so that when you mouse over the "Clear" button it will clear the Browser Console: Components.utils.import("resource://devtools/shared/Loader.jsm"); var HUDService = devtools.require("devtools/client/webconsole/hudservice"); var hud = HUDService.getBrowserConsole(); var clearBtn = hud.chromeWindow.document.querySelector('.webconsole-clear-console-button'); clearBtn.
addEventListener('mouseover', function() { hud.jsterm.clearOutput(true); }, false); Bonus Features Available For Add-on SDK add-ons, the console API is available automatically. Here's an example add-on that just logs an error when the user clicks a widget: widget = require("sdk/widget").Widget({ id: "an-error-happened", label: "Error!", width: 40, content: "Error!", onClick: logError }); function ...
... browser The command line interpreter gets access to the tabbrowser object, through the gBrowser global, and that enables you to control the browser through the command line. Try running this code in the Browser Console's command line (remember that to send multiple lines to the Browser Console, use Shift+Enter): var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab); newTabBrowser.
addEventListener("load", function() { newTabBrowser.contentDocument.body.innerHTML = "<h1>this page has been eaten</h1>"; }, true); newTabBrowser.contentDocument.location.href = "https://mozilla.org/"; It adds a listener to the currently selected tab's load event that will eat the new page, then loads a new page. Note: You can restart the browser with the command Ctrl + Alt + R (Windows, Linux) or Cmd + Alt ...
Access debugging in add-ons - Firefox Developer Tools
We are planning to deprecate the use by Firefox add-ons of the techniques described in this document. Don't write new add-ons that use these techniques. The following items are accessible in the context of chrome://browser/content/debugger.xul (or, in version 23 beta, chrome://browser/content/devtools/debugger.xul): window.
addEventListener("Debugger:EditorLoaded") - called when the read-only script panel loaded. ...
...the use by Firefox add-ons of the techniques described in this document. Don't write new add-ons that use these techniques. The following items are accessible in the context of chrome://browser/content/debugger.xul (or, in version 23 beta, chrome://browser/content/devtools/debugger.xul): window.
addEventListener("Debugger:EditorLoaded") - called when the read-only script panel loaded. ...
Intensive JavaScript - Firefox Developer Tools
Then we need a new file "calculate.j...
...on, false); worker.postMessage({ "multiplier": multiplier, "iterations": iterations }); } The main difference here, compared with the original, is that we need to: create a worker send it a message when we are ready to calculate listen for a message called "done", which indicates that the worker has finished. ...
AbortSignal: abort event - Web APIs
Cancelable No Interface Event Event handler onabort Examples In the following snippets, we create a new AbortController object, and get its AbortSignal (available in the signal property). Later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. ...
...he following snippets, we create a new AbortController object, and get its AbortSignal (available in the signal property). Later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. You can use the abort event in an
addEventListener method: var controller = new AbortController(); var signal = controller.signal; signal.
addEventListener('abort', function() { console.log('Request aborted'); }; Or use the onabort event handler property: var controller = new AbortController(); var signal = controller.signal; signal.onabort = function() { console.log('Request aborted'); }; Specifications Specification Status DOMThe definition of 'abort' in that specification. Living Standard ...
AbortSignal - Web APIs
communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. Properties The AbortSignal interface also inherits properties from its parent interface, EventTarget. AbortSignal.aborted Read only A Boolean that indicates whether the request(s) the signal is communicating with is/are aborted (true) or not (false). Events Listen to this event using
addEventListener() or by assigning an event listener to the oneventname property of this interface. abort Invoked when the DOM request(s) the signal is communicating with is/are aborted. Also available via the onabort property. Methods The AbortSignal interface inherits methods from its parent interface, EventTarget. Examples In the following snippet, we aim to download a video using the Fetch API. We ...
...options object (see {signal}, below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort(), as seen below in the second event listener. var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.
addEventListener('click', fetchVideo); abortBtn.
addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + e.message; }) } Note: When abort() is called, the fetch() promise rejects with an AbortError. Curren...
AbsoluteOrientationSensor - Web APIs
ples Basic Example The following example, which is loosely based on Intel's Orientation Phone demo, instantiates an AbsoluteOrientationSensor with a frequency of 60 times a second. On each reading it uses OrientationSensor.quaternion to rotate a visual model of a phone. ...
...of 60 times a second. On each reading it uses OrientationSensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceFrame: 'device' }; const sensor = new AbsoluteOrientationSensor(options); sensor.
addEventListener('reading', () => { // model is a Three.js object instantiated elsewhere. model.quaternion.fromArray(sensor.quaternion).inverse(); }); sensor.
addEventListener('error', error => { if (event.error.name == 'NotReadableError') { console.log("Sensor is not available."); } }); sensor.start(); Permissions Example Using orientation sensors requires requesting permissions for multiple device sensors. Because the Permissions uses promises, a good way to request permissions is to use Promise.all. const sensor = new AbsoluteOrientationSensor(); Promise.
Ambient Light Events - Web APIs
by changing the exposure necessary to take a picture. Light Events When the light sensor of a device detects a change in the light level, it notifies the browser of that change. When the browser gets such a notification, it fires a DeviceLightEvent event that provides information about the exact light intensity (in lux units). ...
...ty (in lux units). This event can be captured at the window object level by using the
addEventListener method (using the devicelight event name) or by attaching an event handler to the window.ondevicelight property. Once captured, the event object gives access to the light intensity expressed in lux through the DeviceLightEvent.value property. ...
AudioContext.getOutputTimestamp() - Web APIs
of a Performance interface; the time after the document containing the audio context was first rendered Examples In the following code we start to play an audio file after a play button is clicked, and start off a requestAnimationFrame loop running, which constantly outputs the contextTime and performanceTime. You can see full code of this example at output-timestamp (see it live also). ...
...me loop running, which constantly outputs the contextTime and performanceTime. You can see full code of this example at output-timestamp (see it live also). ...
BroadcastChannel: message event - Web APIs
m "Fira Sans", sans-serif; margin-bottom: 1rem; } textarea { padding: .2rem; } label, br { margin: .5rem 0; } button { vertical-align: top; height: 1.5rem; } const channel = new BroadcastChannel('example-channel'); const messageControl = document.querySelector('#message'); const broadcastMessageButton = document.querySelector('#broadcast-message'); broadcastMessageButton.
addEventListener('click', () => { channel.postMessage(messageControl.value); }) Receiver 1 <h1>Receiver 1</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; font-family: "Fira Sans", sans-serif; } h1 { font: 1.6em "Fira Sans", sans-serif; margin-bottom: 1rem; } const channel = new BroadcastChannel('example-channel'); channel.addEventL...
...ventListener('message', (event) => { received.textContent = event.data; }); Receiver 2 <h1>Receiver 2</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; font-family: "Fira Sans", sans-serif; } h1 { font: 1.6em "Fira Sans", sans-serif; margin-bottom: 1rem; } const channel = new BroadcastChannel('example-channel'); channel.
addEventListener('message', (event) => { received.textContent = event.data; }); Result Specifications Specification Status HTML Living Standard Living Standard ...
Cache - Web APIs
torage interface. This is an implementation of the WindowOrWorkerGlobalScope mixin. Note: In Chrome, visit chrome://inspect/#service-workers and click on the "inspect" link below the registered service worker to view logging statements for the various actions the service-worker.js script is performing. var CACHE_VERSION = 1; var CURRENT_CACHES = { font: 'font-cache-v' + CACHE_VERSION }; self.
addEventListener('activate', function(event) { // Delete all caches that aren't named in CURRENT_CACHES. // While there is only one cache in this example, the same logic will handle the case where // there are multiple versioned caches. var expectedCacheNamesSet = new Set(Object.values(CURRENT_CACHES)); event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cach...
...es) { return Promise.all( cacheNames.map(function(cacheName) { if (!expectedCacheNamesSet.has(cacheName)) { // If this cache name isn't present in the set of "expected" cache names, then delete it. console.log('Deleting out of date cache:', cacheName); return caches.delete(cacheName); } }) ); }) ); }); self.
addEventListener('fetch', function(event) { console.log('Handling fetch event for', event.request.url); event.respondWith( caches.open(CURRENT_CACHES.font).then(function(cache) { return cache.match(event.request).then(function(response) { if (response) { // If there is an entry in the cache for event.request, then response will be defined // and we can just return it. No...
CacheStorage - Web APIs
so, serve that. If not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using Cache.put (cache.put(event.request, response.clone()).) If this fails (e.g. because the network is down), return a fallback response. Finally, return whatever the custom response ended up being equal to, using FetchEvent.respondWith. ...
...hen(function(cache) { return cache.addAll([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/bountyHunters.jpg', '/sw-test/gallery/myLittleVader.jpg', '/sw-test/gallery/snowTroopers.jpg' ]); }) ); }); self.
addEventListener('fetch', function(event) { event.respondWith(caches.match(event.request).then(function(response) { // caches.match() always resolves // but in case of success response will have value if (response !== undefined) { return response; } else { return fetch(event.request).then(function (response) { // response may be used only once // we need to save clone...
CanvasRenderingContext2D.addHitRegion() - Web APIs
o control. Defaults to null. role An ARIA role for accessibility tools to determine how to represent this region, if there is no control. Defaults to null. Examples Using the addHitRegion method This example demonstrates the addHitRegion() method. ...
...th.PI, false); ctx.stroke();</textarea> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var textarea = document.getElementById("code"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.
addEventListener("click", function() { textarea.value = code; drawCanvas(); }); edit.
addEventListener("click", function() { textarea.focus(); }); canvas.
addEventListener("mousemove", function(event){ if(event.region) { alert("ouch, my eye :("); } }); textarea.
addEventListener("input", drawCanvas); window.
addEventListener("load", drawCanvas); Specifications Canvas hit regions have been remov...
Manipulating video using canvas - Web APIs
up an event listener so we can detect when the user starts playing the video. var processor; processor.doLoad = function doLoad() { this.video = document.getElementById('video'); this.c1 = document.getElementById('c1'); this.ctx1 = this.c1.getContext('2d'); this.c2 = document.getElementById('c2'); this.ctx2 = this.c2.getContext('2d'); let self = this; this.video.
addEventListener('play', function() { self.width = self.video.videoWidth / 2; self.height = self.video.videoHeight / 2; self.timerCallback(); }, false); }, This code grabs references to the elements in the XHTML document that are of particular interest, namely the video element and the two canvas elements. It also fetches references to the graphics contexts for each of the two c...
...ht = self.video.videoHeight / 2; self.timerCallback(); }, false); }, This code grabs references to the elements in the XHTML document that are of particular interest, namely the video element and the two canvas elements. It also fetches references to the graphics contexts for each of the two canvases. These will be used when we're actually doing the chroma-keying effect. Then
addEventListener() is called to begin watching the video element so that we obtain notification when the user presses the play button on the video. In response to the user beginning playback, this code fetches the width and height of the video, halving each (we will be halving the size of the video when we perform the chroma-keying effect), then calls the timerCallback() method to start watching the video and co...
Client.postMessage() - Web APIs
sfer }]); Parameters message The message to send to the client. This can be any structured-clonable type. transfer Optional A sequence of objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side. Return value undefined. Examples Sending a message from a service worker to a client:
addEventListener('fetch', event => { event.waitUntil(async function() { // Exit early if we don't have access to the client. // Eg, if it's cross-origin. if (!event.clientId) return; // Get the client. const client = await clients.get(event.clientId); // Exit early if we don't get the client. // Eg, if it closed. if (!client) return; // Send a message to the client. cli...
...tId) return; // Get the client. const client = await clients.get(event.clientId); // Exit early if we don't get the client. // Eg, if it closed. if (!client) return; // Send a message to the client. client.postMessage({ msg: "Hey I just got a fetch from you!", url: event.request.url }); }()); }); Receiving that message: navigator.serviceWorker.
addEventListener('message', event => { console.log(event.data.msg, event.data.url); }); Specifications Specification Status Comment Service WorkersThe definition of 'postMessage()' in that specification. Working Draft Initial definition. ...
DataTransfer.clearData() - Web APIs
on to move the element. ...
...rget { border: 1px solid black; } JavaScript window.
addEventListener('DOMContentLoaded', function () { // Select HTML elements var draggable = document.getElementById('source'); var dropable = document.getElementById('target'); var status = document.getElementById('status'); var data = document.getElementById('data'); var dropped = false; // Register event handlers draggable.
addEventListener('dragstart', dragStartHandler); draggable.
addEventListener('dragend', dragEndHandler); dropable.
addEventListener('dragover', dragOverHandler); dropable.
addEventListener('dragleave', dragLeaveHandler); dropable.
addEventListener('drop', dropHandler); function dragStartHandler (event) { status.innerHTML = 'Drag in process'; // Change target element's border to signify drag has st...
DataTransferItem.webkitGetAsEntry() - Web APIs
a recursive call to scanFiles() to process them. Any of them which are files are simply inserted into the list; any which are directories are inserted into the list and a new level of the list's hierarchy is added below, and so forth. Then come the event handlers. ...
...ist's hierarchy is added below, and so forth. Then come the event handlers. First, we prevent the dragover event from being handled by the default handler, so that our drop zone can receive the drop: dropzone.
addEventListener("dragover", function(event) { event.preventDefault(); }, false); The event handler that kicks everything off, of course, is the handler for the drop event: dropzone.
addEventListener("drop", function(event) { let items = event.dataTransfer.items; event.preventDefault(); listing.innerHTML = ""; for (let i=0; i<items.length; i++) { let item = items[i].webkitGetAsEntry(); if (item) { scanFiles(item, listing); } } }, false); This fetches the list of DataTransferItem objects representing the items dropped from event.dataTransfer.items. Then we cal...
DedicatedWorkerGlobalScope: message event - Web APIs
rker receives a message from its parent (i.e. when the parent sends a message using Worker.postMessage()). ...
...No Interface MessageEvent Event handler property onmessage Examples This code creates a new worker and sends it a message using Worker.postMessage(): const worker = new Worker("static/scripts/worker.js"); worker.
addEventListener('message', (event) => { console.log(`Received message from worker: ${event.data}`) }); The worker can listen for this message using
addEventListener(): // inside static/scripts/worker.js self.
addEventListener('message', (event) => { console.log(`Received message from parent: ${event.data}`); }); Alternatively, it could listen using the onmessage event handler property: // static/scripts/worker.js self.onmessage = (event) => { console.log(`Received message from parent: ${event.data}`); }; Specifications Specificatio...
DedicatedWorkerGlobalScope: messageerror event - Web APIs
The messageerror event is fired on a DedicatedWorkerGlobalScope object when it receives a message that can't be deserialized. ...
... The messageerror event is fired on a DedicatedWorkerGlobalScope object when it receives a message that can't be deserialized. ...
Document: keypress event - Web APIs
alue are modifier keys such as Alt, Shift, Ctrl, or Meta. Since this event has been deprecated, you should look to use beforeinput or keydown instead. ...
... Varies: keypress event; launch text composition system; blur and focus events; DOMActivate event; other event Examples
addEventListener keypress example This example logs the KeyboardEvent.code value whenever you press a key. ...
Document: pointercancel event - Web APIs
er started pointer input accidentally. This can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events. The touch-action CSS property prevents the input from continuing. ...
...entally. This can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events. The touch-action CSS property prevents the input from continuing. After the pointercancel event is fired, the browser will also send pointerout followed by pointerleave. ...
Document: pointerdown event - Web APIs
when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer. ...
...om no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer. ...
Document: pointerenter event - Web APIs
The pointerenter event fires when a pointing device is moved into the hit test boundaries of an element or one of its descendants, including as a result of a pointerdown event from a device that does not support hover (see pointerdown). ...
...res when a pointing device is moved into the hit test boundaries of an element or one of its descendants, including as a result of a pointerdown event from a device that does not support hover (see pointerdown). ...
Document: pointerleave event - Web APIs
The pointerleave event is fired when a pointing device is moved out of the hit test boundaries of an element. For pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer. ...
... pointerleave event is fired when a pointing device is moved out of the hit test boundaries of an element. For pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer. ...
Document: pointerlockerror event - Web APIs
The pointerlockerror event is fired when locking the pointer failed (for technical reasons or because the permission was denied). ...
... The pointerlockerror event is fired when locking the pointer failed (for technical reasons or because the permission was denied). ...
Document: pointermove event - Web APIs
The pointermove event is fired when a pointer changes coordinates, and the pointer has not been canceled by a browser touch-action. ...
... The pointermove event is fired when a pointer changes coordinates, and the pointer has not been canceled by a browser touch-action. ...
Document: pointerout event - Web APIs
st boundaries of an element; firing the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer. ...
...iring the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer. ...
Document: pointerover event - Web APIs
The pointerover event is fired when a pointing device is moved into an element's hit test boundaries. ...
... The pointerover event is fired when a pointing device is moved into an element's hit test boundaries. ...
Events and the DOM - Web APIs
interfaces relate to one another. There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft. Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM. Registering event listeners There are 3 ways to register event handlers for a DOM element. EventTarget.
addEventListener // Assuming myButton is a button element myButton.
addEventListener('click', greet, false) function greet(event){ // print and have a look at the event object // always print arguments in case of overlooking any other arguments console.log('greet:', arguments) alert('hello world') } This is the method you should use in modern web pages. Note: Internet Explorer 6-8 didn't suppo...
... overlooking any other arguments console.log('greet:', arguments) alert('hello world') } This is the method you should use in modern web pages. Note: Internet Explorer 6-8 didn't support this method, offering a similar EventTarget.attachEvent API instead. For cross-browser compatibility, use one of the many JavaScript libraries available. More details can be found on the EventTarget.
addEventListener reference page. HTML attribute <button onclick="alert('Hello world!')"> The JavaScript code in the attribute is passed the Event object via the event parameter. The return value is treated in a special way, described in the HTML specification. Warning: This method should be avoided! It inflates the markup, and makes it less readable. Concerns of content/structure and behavior are not well-s...
EffectTiming.fill - Web APIs
on begins and after it ends, and so forth. Here we specify that the animation should take 2000 milliseconds (2 seconds) to complete, should only run once, and that the fill mode should be "none". As defined above, the "none" fill mode means that the element will be rendered in its natural, unaltered condition anytime the animation isn't actively running. ...
...riggering the animation and then animate from the start value. This is the approach used in FLIP animation. elem.style.transform = 'translateY(100px)'; elem.animate({ transform: 'none', offset: 0 }, 200); For some complex effects where animations layer on top of one another, it may be necessary to use a fill mode temporarily to capture the final value of an animation before canceling it. elem.
addEventListener('click', async evt => { const animation = elem.animate( { transform: `translate(${evt.clientX}px, ${evt.clientY}px)` }, { duration: 800, fill: 'forwards' } ); await animation.finished; // commitStyles will record the style up to and including `animation` and // update elem's specified style with the result. animation.commitStyles(); animation.cancel(); }); Specifications ...
Element: compositionend event - Web APIs
ditor completes or cancels the current composition session. For example, this event could be fired after a user finishes entering a Chinese character using a Pinyin IME. ...
... .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } JS const inputElement = document.querySelector('input[type="text"]'); const log = document.querySelector('.event-log-contents'); const clearLog = document.querySelector('.clear-log'); clearLog.
addEventListener('click', () => { log.textContent = ''; }); function handleEvent(event) { log.textContent = log.textContent + `${event.type}: ${event.data}\n`; } inputElement.
addEventListener('compositionstart', handleEvent); inputElement.
addEventListener('compositionupdate', handleEvent); inputElement.
addEventListener('compositionend', handleEvent); Result Specifications Specification ...
Element: compositionstart event - Web APIs
h as an input method editor starts a new composition session. For example, this event could be fired after a user starts entering a Chinese character using a Pinyin IME. ...
... .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } JS const inputElement = document.querySelector('input[type="text"]'); const log = document.querySelector('.event-log-contents'); const clearLog = document.querySelector('.clear-log'); clearLog.
addEventListener('click', () => { log.textContent = ''; }); function handleEvent(event) { log.textContent = log.textContent + `${event.type}: ${event.data}\n`; } inputElement.
addEventListener('compositionstart', handleEvent); inputElement.
addEventListener('compositionupdate', handleEvent); inputElement.
addEventListener('compositionend', handleEvent); Result Specifications Specification ...
Element: compositionupdate event - Web APIs
ontrolled by a text composition system such as an input method editor. For example, this event could be fired while a user enters a Chinese character using a Pinyin IME. ...
... .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } JS const inputElement = document.querySelector('input[type="text"]'); const log = document.querySelector('.event-log-contents'); const clearLog = document.querySelector('.clear-log'); clearLog.
addEventListener('click', () => { log.textContent = ''; }); function handleEvent(event) { log.textContent = log.textContent + `${event.type}: ${event.data}\n`; } inputElement.
addEventListener('compositionstart', handleEvent); inputElement.
addEventListener('compositionupdate', handleEvent); inputElement.
addEventListener('compositionend', handleEvent); Result Specifications Specification ...
Element: focusin event - Web APIs
Document Object Model (DOM) Level 3 Events Specification Obsolete Init...
... Document Object Model (DOM) Level 3 Events Specification Obsolete Initial definition ...
Element: focusout event - Web APIs
Document Object Model (DOM) Level 3 Events Specification Obsolete Init...
... Document Object Model (DOM) Level 3 Events Specification Obsolete Initial definition ...
Element: fullscreenchange event - Web APIs
e, the fullscreenchange handler logs the id of the full-screen element to the console. If document.fullscreenElement is null, the code logs a message that the change is to leave full-screen mode. HTML <h1>fullscreenchange event example</h1> <div id="fullscreen-div"> <button id="toggle-fullscreen">Toggle Fullscreen Mode</button> </div> JavaScript document.getElementById('fullscreen-div').
addEventListener('fullscreenchange', (event) => { // document.fullscreenElement will point to the element that // is in fullscreen mode if there is one. If not, the value // of the property is null. if (document.fullscreenElement) { console.log(`Element: ${document.fullscreenElement.id} entered fullscreen mode.`); } else { console.log('Leaving full-screen mode.'); } }); document.getElementByI...
...vent) => { // document.fullscreenElement will point to the element that // is in fullscreen mode if there is one. If not, the value // of the property is null. if (document.fullscreenElement) { console.log(`Element: ${document.fullscreenElement.id} entered fullscreen mode.`); } else { console.log('Leaving full-screen mode.'); } }); document.getElementById('toggle-fullscreen').
addEventListener('click', (event) => { if (document.fullscreenElement) { // exitFullscreen is only available on the Document object. document.exitFullscreen(); } else { document.getElementById('fullscreen-div').requestFullscreen(); } }); Specifications Specification Status Fullscreen API Living Standard ...
Element.insertAdjacentElement() - Web APIs
SyntaxError The position specified is not a recognised value. TypeError The element specified is not a valid element. Visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> Note: The beforebegin and afterend positions work only if the node is in a tree and has an element parent. ...
... afterend --> Note: The beforebegin and afterend positions work only if the node is in a tree and has an element parent. Example beforeBtn.
addEventListener('click', function() { var tempDiv = document.createElement('div'); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement('beforebegin',tempDiv); } setListener(tempDiv); }); afterBtn.
addEventListener('click', function() { var tempDiv = document.createElement('div'); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement('afterend',tempDiv); } setListener(tempDiv); }); Have a look at our insertAdjacentElement.html demo on Github (see the source code too.) Here we have a sequence of <div> elements inside a container. When one is clicked,...
Element: keydown event - Web APIs
nts are now fired during IME composition, to improve cross-browser compatibility for CJKT users (bug 354358, also see keydown and keyup events are now fired during IME composition for more useful details). To ignore all keydown events that are part of composition, do something like this (229 is a special value set for a keyCode relating to an event that has been processed by an IME): eventTarget.
addEventListener("keydown", event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples
addEventListener keydown example This example logs the KeyboardEvent.code value whenever you press down a key inside the <input> element. <input placeholder="Click here, then press down a key." size="40"> <p id="log"></p> const input = document.querySelector('input'); con...
...| event.keyCode === 229) { return; } // do something }); Examples
addEventListener keydown example This example logs the KeyboardEvent.code value whenever you press down a key inside the <input> element. ...
Element: keypress event - Web APIs
alue are modifier keys such as Alt, Shift, Ctrl, or Meta. Since this event has been deprecated, you should look to use beforeinput or keydown instead. ...
... Examples
addEventListener keypress example This example logs the KeyboardEvent.code value whenever you press a key after focussing the <input> element. ...
Element: keyup event - Web APIs
vents are now fired during IME composition, to improve cross-browser compatibility for CJKT users (bug 354358, also see keydown and keyup events are now fired during IME composition for more useful details). To ignore all keyup events that are part of composition, do something like this (229 is a special value set for a keyCode relating to an event that has been processed by an IME): eventTarget.
addEventListener("keyup", event => { if (event.isComposing || event.keyCode === 229) { return; } // do something }); Examples
addEventListener keyup example This example logs the KeyboardEvent.code value whenever you release a key inside the <input> element. <input placeholder="Click here, then press and release a key." size="40"> <p id="log"></p> const input = document.querySelector('input'); con...
...event.keyCode === 229) { return; } // do something }); Examples
addEventListener keyup example This example logs the KeyboardEvent.code value whenever you release a key inside the <input> element. ...
Element: mouseenter event - Web APIs
t'> <ul id="unorderedList"> <li>No events yet!</li> </ul> </div> CSS Styling the div to make it more visible. ...
...33; } JavaScript var enterEventCount = 0; var leaveEventCount = 0; const mouseTarget = document.getElementById('mouseTarget'); const unorderedList = document.getElementById('unorderedList'); mouseTarget.
addEventListener('mouseenter', e => { mouseTarget.style.border = '5px dotted orange'; enterEventCount++; addListItem('This is mouseenter event ' + enterEventCount + '.'); }); mouseTarget.
addEventListener('mouseleave', e => { mouseTarget.style.border = '1px solid #333'; leaveEventCount++; addListItem('This is mouseleave event ' + leaveEventCount + '.'); }); function addListItem(text) { // Create a new text node using the supplied text var newTextNode = document.createTextNode(text); // Create a new li element var newListItem = document.createElement("li"); // Add the text node t...
Element: mouseleave event - Web APIs
> <ul id="unorderedList"> <li>No events yet!</li> </ul> </div> CSS Styling the <div> to make it more visible. ...
...33; } JavaScript var enterEventCount = 0; var leaveEventCount = 0; const mouseTarget = document.getElementById('mouseTarget'); const unorderedList = document.getElementById('unorderedList'); mouseTarget.
addEventListener('mouseenter', e => { mouseTarget.style.border = '5px dotted orange'; enterEventCount++; addListItem('This is mouseenter event ' + enterEventCount + '.'); }); mouseTarget.
addEventListener('mouseleave', e => { mouseTarget.style.border = '1px solid #333'; leaveEventCount++; addListItem('This is mouseleave event ' + leaveEventCount + '.'); }); function addListItem(text) { // Create a new text node using the supplied text var newTextNode = document.createTextNode(text); // Create a new li element var newListItem = document.createElement("li"); // Add the text node t...
Element: mouseout event - Web APIs
ivered to the individual list items, while mouseleave goes to the overall list, courtesy of the hierarchy of the items and the fact that list items obscure the underlying <ul>. ...
... Working Draft Document...
Element: mouseover event - Web APIs
seEvent Event handler property onmouseover Examples The following example illustrates the difference between mouseover and mouseenter events. ...
... Working Draft Docum...
Element.setCapture() - Web APIs
and holding down on an element. ...
...e Capture Example</title> <style type="text/css"> #myButton { border: solid black 1px; color: black; padding: 2px; box-shadow: black 2px 2px; } </style> <script type="text/javascript"> function init() { var btn = document.getElementById("myButton"); if (btn.setCapture) { btn.
addEventListener("mousedown", mouseDown, false); btn.
addEventListener("mouseup", mouseUp, false); } else { document.getElementById("output").innerHTML = "Sorry, there appears to be no setCapture support on this browser"; } } function mouseDown(e) { e.target.setCapture(); e.target.
addEventListener("mousemove", mouseMoved, false); } function mouseUp(e) { e.target.removeEventListener("mousemove", mouseM...
Element - Web APIs
uch as when your app is running in the background. Element.onfullscreenerror An event handler for the fullscreenerror event, which is sent when an error occurs while attempting to change into full-screen mode. Methods Inherits methods from its parents Node, and its own parent, EventTarget, and implements those of ParentNode, ChildNode, NonDocumentTypeChildNode, and Animatable. EventTarget.
addEventListener() Registers an event handler to a specific event type on the element. Element.attachShadow() Attaches a shadow DOM tree to the specified element and returns a reference to its ShadowRoot. Element.animate() A shortcut method to create and run an animation on an element. Returns the created Animation object instance. Element.closest() Returns the Element which is the closest ancestor of ...
.... Element.removeAttributeNode() Removes the node representation of the named attribute from the current node. Element.setAttributeNode() Sets the node representation of the named attribute from the current node. Element.setAttributeNodeNS() Sets the node representation of the attribute with the specified name and namespace, from the current node. Events Listen to these events using
addEventListener() or by assigning an event listener to the oneventname property of this interface. cancel Fires on a <dialog> when the user instructs the browser that they wish to dismiss the current open dialog. For example, the browser might fire this event when the user presses the Esc key or clicks a "Close dialog" button which is part of the browser's UI. Also available via the oncancel property. erro...
Comparison of Event Targets - Web APIs
For the mouseout event, it holds the node that the mouse moved to. Event type event.target event.relatedTarget mo...
...For the mouseout event, it holds the node that the mouse moved to. Event type event.target event.relatedTarget mouseover the EventTarget which the pointing device entered ...
Event.preventDefault() - Web APIs
t() for a non-cancelable event, such as one dispatched via EventTarget.dispatchEvent(), without specifying cancelable: true has no effect. Syntax event.preventDefault(); Examples Blocking default click handling Toggling a checkbox is the default action of clicking on a checkbox. ...
...ttle bit of CSS for the warning box we'll draw when the user presses an invalid key: .warning { border: 2px solid #f39389; border-radius: 2px; padding: 10px; position: absolute; background-color: #fbd8d4; color: #3b3c40; } JavaScript And here's the JavaScript code that does the job. ...
EventListener - Web APIs
EventListener.handleEvent() A function that is called whenever an event of the specified type occurs. Example HTML <button id="btn">Click here!</button> JavaScript const buttonElement = document.getElementById('btn'); // Add a handler for the 'click' event by providing a callback function. // Whenever the element is clicked, a pop-up with "Element clicked!" will // appear. ...
... a handler for the 'click' event by providing a callback function. // Whenever the element is clicked, a pop-up with "Element clicked!" will // appear. buttonElement.
addEventListener('click', function (event) { alert('Element clicked through function!'); }); // For compatibility, a non-function object with a `handleEvent` property is // treated just the same as a function itself. buttonElement.
addEventListener('click', { handleEvent: function (event) { alert('Element clicked through handleEvent property!'); } }); Result See Also:
addEventListener Specifications Specification Status Comment DOMThe definition of 'EventListener' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Events SpecificationThe definit...
EventTarget - Web APIs
ll="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">EventTarget</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor EventTarget() Creates a new EventTarget object instance. Methods EventTarget.
addEventListener() Registers an event handler of a specific event type on the EventTarget. EventTarget.removeEventListener() Removes an event listener from the EventTarget. EventTarget.dispatchEvent() Dispatches an event to this EventTarget. Additional methods in Mozilla chrome codebase Mozilla includes a couple of extensions for use by JS-implemented event targets to implement onevent properties. See al...
...uple of extensions for use by JS-implemented event targets to implement onevent properties. See also WebIDL bindings. ...
ExtendableMessageEvent - Web APIs
ssociated message channel. Methods Inherits methods from its parent, ExtendableEvent. Examples In the below example a page gets a handle to the ServiceWorker object via ServiceWorkerRegistration.active, and then calls its postMessage() function. ...
...r.serviceWorker.
addEventListener('message', event => { // event is a MessageEvent object console.log(`The service worker sent me a message: ${event.data}`); }); navigator.serviceWorker.ready.then( registration => { registration.active.postMessage("Hi service worker"); }); } The service worker can receive the message by listening to the message event: // in the service worker
addEventListener('message', event => { // event is an ExtendableMessageEvent object console.log(`The client sent me a message: ${event.data}`); event.source.postMessage("Hi client"); }); Specifications Specification Status Comment Service WorkersThe definition of 'ExtendableMessageEvent' in that specification. Working Draft Initial definition. ...
FileReader: abort event - Web APIs
iew = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addListeners(reader) { reader.
addEventListener('loadstart', handleEvent); reader.
addEventListener('load', handleEvent); reader.
addEventListener('loadend', handleEvent); reader.
addEventListener('progress', handleEvent); reader.
addEventListener('error', handleEvent); reader.
addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; i...
... reader.
addEventListener('progress', handleEvent); reader.
addEventListener('error', handleEvent); reader.
addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; if (selectedFile) { addListeners(reader); reader.readAsDataURL(selectedFile); } reader.abort(); } fileInput.
addEventListener('change', handleSelected); Result Specifications Specification Status File API Working Draft ...
FileReader: error event - Web APIs
as not found or not readable). ...
...operty FileReader.onerror Examples const fileInput = document.querySelector('input[type="file"]'); const reader = new FileReader(); function handleSelected(e) { const selectedFile = fileInput.files[0]; if (selectedFile) { reader.
addEventListener('error', () => { console.error(`Error occurred reading file: ${selectedFile.name}`); }); reader.
addEventListener('load', () => { console.error(`File: ${selectedFile.name} read successfully`); }); reader.readAsDataURL(selectedFile); } } fileInput.
addEventListener('change', handleSelected); Specifications Specification Status File API Working Draft ...
FileReader: load event - Web APIs
iew = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addListeners(reader) { reader.
addEventListener('loadstart', handleEvent); reader.
addEventListener('load', handleEvent); reader.
addEventListener('loadend', handleEvent); reader.
addEventListener('progress', handleEvent); reader.
addEventListener('error', handleEvent); reader.
addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; i...
...nd', handleEvent); reader.
addEventListener('progress', handleEvent); reader.
addEventListener('error', handleEvent); reader.
addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; if (selectedFile) { addListeners(reader); reader.readAsDataURL(selectedFile); } } fileInput.
addEventListener('change', handleSelected); Result Specifications Specification Status File API Working Draft ...
FileReader: loadend event - Web APIs
iew = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addListeners(reader) { reader.
addEventListener('loadstart', handleEvent); reader.
addEventListener('load', handleEvent); reader.
addEventListener('loadend', handleEvent); reader.
addEventListener('progress', handleEvent); reader.
addEventListener('error', handleEvent); reader.
addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; i...
...nd', handleEvent); reader.
addEventListener('progress', handleEvent); reader.
addEventListener('error', handleEvent); reader.
addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; if (selectedFile) { addListeners(reader); reader.readAsDataURL(selectedFile); } } fileInput.
addEventListener('change', handleSelected); Result Specifications Specification Status File API Working Draft ...
FileReader: loadstart event - Web APIs
iew = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addListeners(reader) { reader.
addEventListener('loadstart', handleEvent); reader.
addEventListener('load', handleEvent); reader.
addEventListener('loadend', handleEvent); reader.
addEventListener('progress', handleEvent); reader.
addEventListener('error', handleEvent); reader.
addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; i...
...nd', handleEvent); reader.
addEventListener('progress', handleEvent); reader.
addEventListener('error', handleEvent); reader.
addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; if (selectedFile) { addListeners(reader); reader.readAsDataURL(selectedFile); } } fileInput.
addEventListener('change', handleSelected); Result Specifications Specification Status File API Working Draft ...
FileReader: progress event - Web APIs
iew = document.querySelector('img.preview'); const eventLog = document.querySelector('.event-log-contents'); const reader = new FileReader(); function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addListeners(reader) { reader.
addEventListener('loadstart', handleEvent); reader.
addEventListener('load', handleEvent); reader.
addEventListener('loadend', handleEvent); reader.
addEventListener('progress', handleEvent); reader.
addEventListener('error', handleEvent); reader.
addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; i...
...nd', handleEvent); reader.
addEventListener('progress', handleEvent); reader.
addEventListener('error', handleEvent); reader.
addEventListener('abort', handleEvent); } function handleSelected(e) { eventLog.textContent = ''; const selectedFile = fileInput.files[0]; if (selectedFile) { addListeners(reader); reader.readAsDataURL(selectedFile); } } fileInput.
addEventListener('change', handleSelected); Result Specifications Specification Status File API Working Draft ...
FileReader.readAsDataURL() - Web APIs
eader.readAsDataURL(blob); Parameters blob The Blob or File from which to read. ...
...iles()" multiple> <div id="preview"></div> JavaScript function previewFiles() { var preview = document.querySelector('#preview'); var files = document.querySelector('input[type=file]').files; function readAndPreview(file) { // Make sure `file.name` matches our extensions criteria if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { var reader = new FileReader(); reader.
addEventListener("load", function () { var image = new Image(); image.height = 100; image.title = file.name; image.src = this.result; preview.appendChild( image ); }, false); reader.readAsDataURL(file); } } if (files) { [].forEach.call(files, readAndPreview); } } Note: The FileReader() constructor was not supported by Internet Explorer for ve...
FileReader - Web APIs
h time the reading is starting. FileReader.onloadend A handler for the loadend event. This event is triggered each time the reading operation is completed (either in success or failure). FileReader.onprogress A handler for the progress event. This event is triggered while reading a Blob content. As FileReader inherits from EventTarget, all those events can also be listened for by using the
addEventListener method. Methods FileReader.abort() Aborts the read operation. Upon return, the readyState will be DONE. FileReader.readAsArrayBuffer() Starts reading the contents of the specified Blob, once finished, the result attribute contains an ArrayBuffer representing the file's data. FileReader.readAsBinaryString() Starts reading the contents of the specified Blob, once finished, the result att...
...dAsDataURL() Starts reading the contents of the specified Blob, once finished, the result attribute contains a data: URL representing the file's data. FileReader.readAsText() Starts reading the contents of the specified Blob, once finished, the result attribute contains the contents of the file as a text string. An optional encoding name can be specified. Events Listen to these events using
addEventListener() or by assigning an event listener to the oneventname property of this interface. abort Fired when a read has been aborted, for example because the program called FileReader.abort(). Also available via the onabort property. error Fired when the read failed due to an error. Also available via the onerror property. load Fired when a read has completed successfully. Also available via th...
FileSystemDirectoryReader.readEntries() - Web APIs
a recursive call to scanFiles() to process them. Any of them which are files are simply inserted into the list; any which are directories are inserted into the list and a new level of the list's hierarchy is added below, and so forth. Then come the event handlers. ...
...ist's hierarchy is added below, and so forth. Then come the event handlers. First, we prevent the dragover event from being handled by the default handler, so that our drop zone can receive the drop: dropzone.
addEventListener("dragover", function(event) { event.preventDefault(); }, false); The event handler that kicks everything off, of course, is the handler for the drop event: dropzone.
addEventListener("drop", function(event) { let items = event.dataTransfer.items; event.preventDefault(); listing.innerHTML = ""; for (let i=0; i<items.length; i++) { let item = items[i].webkitGetAsEntry(); if (item) { scanFiles(item, listing); } } }, false); This fetches the list of DataTransferItem objects representing the items dropped from event.dataTransfer.items. Then we cal...
FormDataEvent.formData - Web APIs
The formData read only property of the FormDataEvent interface contains the FormData object representing the data contained in the form when the event was fired. Syntax formData = formDataEvent.formData Returns A FormData object. ...
...nt.formData Returns A FormData object. ...
FormDataEvent - Web APIs
mDataEvent object instance. Properties Inherits properties from its parent interface, Event. FormDataEvent.formData Contains the FormData object representing the data contained in the form when the event was fired. Methods Inherits methods from its parent interface, Event. ...
...ethods from its parent interface, Event. ...
GamepadEvent - Web APIs
epad events Window.gamepadconnected and Window.gamepaddisconnected are fired in response to. Constructor GamepadEvent() Returns a new GamepadEvent object. Properties GamepadEvent.gamepad Read only Returns a Gamepad object, providing access to the associated gamepad data for the event fired. Examples The gamepad property being called on a fired Window.gamepadconnected event. ...
...ated gamepad data for the event fired. Examples The gamepad property being called on a fired Window.gamepadconnected event. window.
addEventListener("gamepadconnected", function(e) { console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.", e.gamepad.index, e.gamepad.id, e.gamepad.buttons.length, e.gamepad.axes.length); }); And on a Window.gamepaddisconnected event. window.
addEventListener("gamepaddisconnected", function(e) { console.log("Gamepad disconnected from index %d: %s", e.gamepad.index, e.gamepad.id); }); Specifications Specification Status Comment GamepadThe definition of 'GamepadEvent' in that specification. Working Draft Initial definition Browser compatibility DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid ...
GeolocationCoordinates.longitude - Web APIs
's location and display the resulting coordinates once they're returned. JavaScript The JavaScript code below creates an event listener so that when the user clicks on a button, the location information is retrieved and displayed. ...
...When the user clicks the button, we'll fetch and display the location information. Upon receiving a click event, we call getCurrentPosition() to request the device's current position. This is an asynchronous request, so we provide a callback which receives as in put a GeolocationPosition object describing the determined position. From the GeolocationPosition object, w...
GlobalEventHandlers.onpointerdown - Web APIs
ly pressed. This event can be sent to Window, Document, and Element objects. This is functionally equivalent to the mousedown event when generated due to user activity with a mouse or mouse-compatible device. If the pointerdown event isn't canceled through a call to preventDefault(), most user agents will fire a mousedown event, so that sites not using pointer events will work. You can also use
addEventListener() to add a listener for pointerdown events. Syntax target.onpointerdown = downHandler; var downHandler = target.onpointerdown; Value A Function to handle the pointerdown event for the target Element, Document, or Window. It receives as input the PointerEvent describing the pointerdown event. Example This example demonstrates how to watch for and act upon pointerdown events using onpointer...
...pointerdown events. Syntax target.onpointerdown = downHandler; var downHandler = target.onpointerdown; Value A Function to handle the pointerdown event for the target Element, Document, or Window. It receives as input the PointerEvent describing the pointerdown event. Example This example demonstrates how to watch for and act upon pointerdown events using onpointerdown. You could also use
addEventListener(), of course. JavaScript First, let's look at the JavaScript code that handles the pointerdown event. var targetBox = document.getElementById("target"); targetBox.onpointerdown = handleDown; function handleDown(evt) { var action; switch(evt.pointerType) { case "mouse": action = "clicking"; break; case "pen": action = "tapping"; break; case "touch": ...
HTMLFormElement: formdata event - Web APIs
is happens when the form is submitted, but can also be triggered by the invocation of a FormData() constructor. ...
... GlobalEventHandlers.onformdata Examples // grab reference to form const formElem = document.querySelector('form'); // submit handler formElem.
addEventListener('submit', (e) => { // on form submission, prevent default e.preventDefault(); // construct a FormData object, which fires the formdata event new FormData(formElem); }); // formdata handler to retrieve data formElem.
addEventListener('formdata', (e) => { console.log('formdata fired'); // Get the form data from the event object let data = e.formData; for (var value of data.values()) { console.log(value); } // submit the data via XHR var request = new XMLHttpRequest(); request.open("POST", "/formHandler"); request.send(data); }); The onformdata version would look like this: formElem.onformdata = (e) =>...
HTMLFormElement: reset event - Web APIs
The reset event fires when a <form> is reset. Bubbles Yes (although specified as a simple event that doesn't bubble) Cancelable Yes Interface Event Event handler property GlobalEventHandlers.onreset Examples This example uses EventTarget.
addEventListener() to listen for form resets, and logs the current Event.timeStamp whenever that occurs. ...
...rrent Event.timeStamp whenever that occurs. HTML <form id="form"> <label>Test field: <input type="text"></label> <br><br> <button type="reset">Reset form</button> </form> <p id="log"></p> JavaScript function logReset(event) { log.textContent = `Form reset! Time stamp: ${event.timeStamp}`; } const form = document.getElementById('form'); const log = document.getElementById('log'); form.
addEventListener('reset', logReset); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'reset' in that specification. Working Draft No change HTML 5.2The definition of 'reset' in that specification. Recommendation No change HTML 5.1The definition of 'reset' in that specification. Recommendation Added info t...
HTMLFormElement: submit event - Web APIs
put type="submit">) or presses Enter while editing a field (e.g. <input type="text">) in a form. The event is not sent to the form when calling the form.submit() method directly. Note: Trying to submit a form that does not pass validation triggers an invalid event. In this case, the validation prevents form submission, and thus there is no submit event. Examples This example uses EventTarget.
addEventListener() to listen for form submit, and logs the current Event.timeStamp whenever that occurs, then prevents the default action of submitting the form. HTML <form id="form"> <label>Test field: <input type="text"></label> <br><br> <button type="submit">Submit form</button> </form> <p id="log"></p> JavaScript function logSubmit(event) { log.textContent = `Form Submitted! Time stamp: ${event.ti...
... the form. HTML <form id="form"> <label>Test field: <input type="text"></label> <br><br> <button type="submit">Submit form</button> </form> <p id="log"></p> JavaScript function logSubmit(event) { log.textContent = `Form Submitted! Time stamp: ${event.timeStamp}`; event.preventDefault(); } const form = document.getElementById('form'); const log = document.getElementById('log'); form.
addEventListener('submit', logSubmit); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'submit' in that specification. Working Draft No change HTML 5.2The definition of 'submit' in that specification. Recommendation No change HTML 5.1The definition of 'submit' in that specification. Recommendation No chan...
HTMLInputElement: search event - Web APIs
e is present, after a UA-defined timeout elapses since the most recent keystroke (with new keystrokes resetting the timeout so the firing of the event is debounced). Current UA implementations of <input type="search"> have an additional control to clear the field. Using this control also fires the search event. In that case the value of the <input> element will be the empty string. ...
...strokes resetting the timeout so the firing of the event is debounced). Current UA implementations of <input type="search"> have an additional control to clear the field. Using this control also fires the search event. In that case the value of the <input> element will be the empty string. Examples //
addEventListener version const input = document.querySelector('input[type="search"]'); input.
addEventListener('search', () => { console.log("The term searched for was " + input.value); }) // onsearch version const input = document.querySelector('input[type="search"]'); input.onsearch = () => { console.log("The term searched for was " + input.value); }) Specifications This event is not part of any specification. ...
HTMLMediaElement: canplay event - Web APIs
No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.oncanplay Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's canplay event, then post a message when that event handler has reacted to the event firing. ...
... Element Default Action None Event handler property GlobalEventHandlers.oncanplay Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's canplay event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: canplaythrough event - Web APIs
ancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.oncanplaythrough Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's canplaythrough event, then post a message when that event handler has reacted to the event firing. ...
... Default Action None Event handler property GlobalEventHandlers.oncanplaythrough Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's canplaythrough event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: durationchange event - Web APIs
ancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.ondurationchange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's durationchange event, then post a message when that event handler has reacted to the event firing. ...
... Default Action None Event handler property GlobalEventHandlers.ondurationchange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's durationchange event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: ended event - Web APIs
Element Default Action None Event handler property GlobalEventHandlers.onended Specification HTML5 media This event is also defined in Media Capture and Streams and Web Audio API Examples These examples add an event listener for the HTMLMediaElement's ended event, then post a message when that event handler has reacted to the event firing. ...
... GlobalEventHandlers.onended Specification HTML5 media This event is also defined in Media Capture and Streams and Web Audio API Examples These examples add an event listener for the HTMLMediaElement's ended event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: loadeddata event - Web APIs
None Event handler property GlobalEventHandlers.onloadeddata Specification HTML5 media Note that this event will not fire in mobile/tablet devices if data-saver is on in browser settings. Examples These examples add an event listener for the HTMLMediaElement's loadeddata event, then post a message when that event handler has reacted to the event firing. ...
... Specification HTML5 media Note that this event will not fire in mobile/tablet devices if data-saver is on in browser settings. Examples These examples add an event listener for the HTMLMediaElement's loadeddata event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: playing event - Web APIs
No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onplaying Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's playing event, then post a message when that event handler has reacted to the event firing. ...
... Element Default Action None Event handler property GlobalEventHandlers.onplaying Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's playing event, then post a message when that event handler has reacted to the event firing. Using
addEventListener(): const video = document.querySelector('video'); video.
addEventListener('playing', (event) => { console.log('Video is no longer paused'); }); Using the onplaying event handler property: const video = document.querySelector('video'); video.onplaying = (event) => { console.log('Video is no longer paused.'); }; Specifications Specification Status HTML Living StandardThe definition of 'playing media event' in that specification. Livin...
HTMLMediaElement: ratechange event - Web APIs
Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onratechange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's ratechange event, then post a message when that event handler has reacted to the event firing. ...
...ent Default Action None Event handler property GlobalEventHandlers.onratechange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's ratechange event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: seeked event - Web APIs
No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onseeked Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's seeked event, then post a message when that event handler has reacted to the event firing. ...
... Element Default Action None Event handler property GlobalEventHandlers.onseeked Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's seeked event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: seeking event - Web APIs
No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onseeking Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's seeking event, then post a message when that event handler has reacted to the event firing. ...
... Element Default Action None Event handler property GlobalEventHandlers.onseeking Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's seeking event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: stalled event - Web APIs
No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onstalled Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's stalled event, then post a message when that event handler has reacted to the event firing. ...
... Element Default Action None Event handler property GlobalEventHandlers.onstalled Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's stalled event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: suspend event - Web APIs
No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onsuspend Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's suspend event, then post a message when that event handler has reacted to the event firing. ...
... Element Default Action None Event handler property GlobalEventHandlers.onsuspend Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's suspend event, then post a message when that event handler has reacted to the event firing. ...
HTMLMediaElement: volumechange event - Web APIs
Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onvolumechange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's volumechange event, then post a message when that event handler has reacted to the event firing. ...
... Default Action None Event handler property GlobalEventHandlers.onvolumechange Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's volumechange event, then post a message when that event handler has reacted to the event firing. Using
addEventListener(): const video = document.querySelector('video'); video.
addEventListener('volumechange', (event) => { console.log('The volume changed.'); }); Using the onvolumechange event handler property: const video = document.querySelector('video'); video.onvolumechange = (event) => { console.log('The volume changed.'); }; Specifications Specification Status HTML Living StandardThe definition of 'volumechange media event' in that specification. ...
HTMLMediaElement: waiting event - Web APIs
No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onwaiting Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's waiting event, then post a message when that event handler has reacted to the event firing. ...
... Element Default Action None Event handler property GlobalEventHandlers.onwaiting Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's waiting event, then post a message when that event handler has reacted to the event firing. ...
onMSVideoFormatChanged - Web APIs
r may change in the future. onMSVideoFormatChanged is an event which occurs when the video format changes. This proprietary property is specific to Internet Explorer and Microsoft Edge. ...
... onMSVideoFormatChanged is an event which occurs when the video format changes. This proprietary property is specific to Internet Explorer and Microsoft Edge. ...
onMSVideoFrameStepCompleted - Web APIs
pCompleted is an event which occurs when the video frame has been stepped forward or backward one frame. This proprietary property is specific to Internet Explorer and Microsoft Edge. ...
...s when the video frame has been stepped forward or backward one frame. This proprietary property is specific to Internet Explorer and Microsoft Edge. ...
onMSVideoOptimalLayoutChanged - Web APIs
eoOptimalLayoutChanged is an event which occurs when the msIsLayoutOptimalForPlayback state changes. This proprietary property is specific to Internet Explorer and Microsoft Edge. ...
... which occurs when the msIsLayoutOptimalForPlayback state changes. This proprietary property is specific to Internet Explorer and Microsoft Edge. ...
The HTML DOM API - Web APIs
ate of a form's "submit" button based on whether or not a given field currently has a value. ...
.... With these, we can access the properties and methods that provide information about and grant control over these elements. The HTMLInputElement object for the "Send" button's disabled property is set to true, which disables the "Send" button so it can't be clicked. In addition, the user name input field is made the active focus by calling the focus() method it inherits from HTMLElement. Then
addEventListener() is called to add a handler for the input event to the user name input. This code looks at the length of the current value of the input; if it's zero, then the "Send" button is disabled if it's not already disabled. Otherwise, the code ensures that the button is enabled. With this in place, the "Send" button is always enabled whenever the user name input field has a value, and disabled when it'...
HTML Drag and Drop API - Web APIs
-and-drop functionality to an application. ...
...Each data item is a string of a particular type -- typically a MIME type such as text/html. Each d...
IDBOpenDBRequest: blocked event - Web APIs
The blocked handler is executed when an open connection to a database is blocking a versionchange transaction on the same database. ...
...e.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; DBOpenRequest.onsuccess = (event) => { // Let's try to open the same database with a higher revision version const req2 = indexedDB.open('toDoList', 5); // In this case the onblocked handler will be executed req2.
addEventListener('blocked', () => { console.log('Request was blocked'); }); }; Using the onblocked property: // Open the database const DBOpenRequest = window.indexedDB.open('toDoList', 4); DBOpenRequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('Error creating database'); }; // Create an objectStore for this database var objectStore ...
IDBRequest: success event - Web APIs
The success event is fired when an IDBRequest succeeds. ...
...le' }); // define what data items the objectStore will contain objectStore.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; openRequest.
addEventListener('success', (event) => { console.log('Database opened successfully!'); }); The same example, but using the onsuccess event handler property: // Open the database const openRequest = window.indexedDB.open('toDoList', 4); openRequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('Error creating database'); }; // Create an objectS...
IDBTransaction: complete event - Web APIs
The complete handler is executed when a transaction successfully completed. ...
...nique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; DBOpenRequest.onsuccess = event => { const db = DBOpenRequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); // add a listener for `complete` transaction.
addEventListener('complete', event => { console.log('Transaction was competed'); }); const objectStore = transaction.objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2019 }; const objectStoreRequest = objectStore.add(newItem); }; Using the oncomplete property: // Open the database const DBOpenRequest = window.indexedDB.open(...
Timing element visibility with the Intersection Observer API - Web APIs
another page). adObserver Will hold our IntersectionObserver used to track the intersection between the ads and the <main> element's bounds. refreshIntervalID Used to store the interval ID returned by setInterval(). This interval will be used to trigger our periodic refreshes of the ads' content. ...
...n> element's bounds. refreshIntervalID Used to store the interval ID returned by setInterval(). This interval will be used to trigger our periodic refreshes of the ads' content. ...
Intersection Observer API - Web APIs
0px; } JavaScript Finally, let's take a look at the JavaScript code that uses the Intersection Observer API to make things happen. Setting up First, we need to prepare some variables and install the observer. const numSteps = 20.0; let boxElement; let prevRatio = 0.0; let increasingColor = "rgba(40, 40, 190, ratio)"; let decreasingColor = "rgba(190, 40, 40, ratio)"; // Set things up window.
addEventListener("load", (event) => { boxElement = document.querySelector("#box"); createObserver(); }, false); The constants and variables we set up here are: numSteps A constant which indicates how many thresholds we want to have between a visibility ratio of 0.0 and 1.0. prevRatio This variable will be used to record what the visibility ratio was the last time a threshold was crossed; this will let...
...y to the target element when the visibility ratio is increasing. The word "ratio" in this string will be replaced with the target's current visibility ratio, so that the element not only changes color but also becomes increasingly opaque as it becomes less obscured. decreasingColor Similarly, this is a string defining a color we'll apply when the visibility ratio is decreasing. We call Window.
addEventListener() to start listening for the load event; once the page has finished loading, we get a reference to the element with the ID "box" using querySelector(), then call the createObserver() method we'll create in a moment to handle building and installing the intersection observer. Creating the intersection observer The createObserver() method is called once page load is complete to handle actually cr...
KeyboardEvent - Web APIs
t does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself. Example <!DOCTYPE html> <html> <head> <script> 'use strict'; document.
addEventListener('keydown', (event) => { const keyName = event.key; if (keyName === 'Control') { // do not alert when only Control key is pressed. return; } if (event.ctrlKey) { // Even though event.key is not 'Control' (e.g., 'a' is pressed), // event.ctrlKey may be true if Ctrl key is pressed at the same time. alert(`Combination of ctrlKey + ${keyName}`); } else { alert(`Key ...
...t.key; if (keyName === 'Control') { // do not alert when only Control key is pressed. return; } if (event.ctrlKey) { // Even though event.key is not 'Control' (e.g., 'a' is pressed), // event.ctrlKey may be true if Ctrl key is pressed at the same time. alert(`Combination of ctrlKey + ${keyName}`); } else { alert(`Key pressed ${keyName}`); } }, false); document.
addEventListener('keyup', (event) => { const keyName = event.key; // As the user releases the Ctrl key, the key is no longer active, // so event.ctrlKey is false. if (keyName === 'Control') { alert('Control key was released'); } }, false); </script> </head> <body> </body> </html> Specifications Specification Status Comment UI EventsThe definition of 'KeyboardEvent' ...
MSCandidateWindowShow - Web APIs
Internet Explorer. General info Synchronous No Bubbles No Cancelable No Note Windows 8.1 and Windows 7 IMEs for certain languages on Internet Explorer for the desktop might not support this event. On Internet Explorer in the new Windows UI, this event is supported in Windows 8.1 IMEs of all languages. Syntax Event Property object.oncandidatewindowshow = handler;
addEventListener Method object.
addEventListener("MSCandidateWindowShow", handler, useCapture) Parameters pEvtObj [in] Type: IHTMLEventObj Pointer to an IHTMLEventObj interface for the current event. This event fires after the positioning information of the IME candidate window has been determined. You can obtain the positioning information using the getCandidateWindowClientRect method, and adjust ...
...r will remain valid for the lifetime of the element). Example in IE11, developers can detect the opening of the IME candidate window by listening to MSCandidateWindowShow event, then call getCandidateWindowClientRect() function to find out where the candidate window is and position the suggestion UI away from it: var context = document.getElementById("mySearchBox").msGetInputContext(); context.
addEventListener("MSCandidateWindowShow", candidateWindowShowHandler); function candidateWindowShowHandler(e) { var imeRect = context.getCandidateWindowClientRect(); var suggestionRect = document.getElementById("mySuggestionList").getBoundingClientRect(); // Check if the two rects intersect, and position them away from each other. } When the IME candidate window changes position or closes, it fires MS...
msExtendedCode - Web APIs
, the media element's error event will be fired. The element's error property will then contain an msExtendedCode read-only property with platform-specific error code information. ...
...Code read-only property with platform-specific error code information. msExtendedCode is a read-only proprietary property specific to Internet Explorer and Microsoft Edge. ...
MediaQueryList.matches - Web APIs
tching for the change event to be fired at the MediaQueryList. Syntax var matches = <varm>MediaQueryList.matches; Value A Boolean which is true if the document currently matches the media query list; otherwise, it's false. ...
... to be fired at the MediaQueryList. Syntax var matches = <varm>MediaQueryList.matches; Value A Boolean which is true if the document currently matches the media query list; otherwise, it's false. ...
MediaRecorder: error event - Web APIs
ror event is fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. Bubbles No Cancelable No Interface MediaRecorderErrorEvent Event handler property onerror For details of the all the possible errors see the documentation for the event handler property: onerror. ...
...corderErrorEvent Event handler property onerror For details of the all the possible errors see the documentation for the event handler property: onerror. ...
MediaStreamConstraints.audio - Web APIs
idth: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } JavaScript content let audioElement = document.getElementById("audio"); let logElement = document.getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.getElementById("startButton").
addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => audioElement.srcObject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); Here we see an event handler for a click event which uses getUserMedia() to obtain an audio-only stream with no specific constraints, then attaches the resulting stream to an <audio> element once the s...
...idth: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } JavaScript content let audioElement = document.getElementById("audio"); let logElement = document.getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.getElementById("startButton").
addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ audio: { sampleSize: 8, echoCancellation: true } }).then(stream => audioElement.srcObject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); Here we see an event handler for a click event which calls getUserMedia(), specifying a set of audio constraints requesting that echo cancellation b...
MediaStreamConstraints.video - Web APIs
idth: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } JavaScript content let videoElement = document.getElementById("video"); let logElement = document.getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.getElementById("startButton").
addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ video: true }).then(stream => videoElement.srcObject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); Here we see an event handler for a click event which uses getUserMedia() to obtain a video-only stream with no specific constraints, then attaches the resulting stream to a <video> element once the s...
...idth: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } JavaScript content let videoElement = document.getElementById("video"); let logElement = document.getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.getElementById("startButton").
addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ video: { width: 160, height: 120, frameRate: 15 } }).then(stream => videoElement.srcObject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); Here we see an event handler for a click event which calls getUserMedia(), specifying a set of video constraints that indicate a pr...
MediaStreamTrack: mute event - Web APIs
Track.enabled property, for which there are no events. Bubbles No Cancelable No Interface Event Event handler property onmute Examples In this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for the MediaStreamTrack referenced by musicTrack. ...
... Event handler property onmute Examples In this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for the MediaStreamTrack referenced by musicTrack. musicTrack.
addEventListener("mute", event => { document.getElementById("timeline-widget").style.backgroundColor = "#aaa"; }, false); musicTrack.
addEventListener("unmute", event => { document.getElementById("timeline-widget").style.backgroundColor = "#fff"; }, false); With these event handlers in place, when the track musicTrack enters its muted state, the element with the ID timeline-widget gets its background color changed to #aaa. When the track exits the muted state--detected by the arrival of an unmute event--the background color is restored to wh...
MediaStreamTrack: unmute event - Web APIs
e think of as "muted" (that is, a user-controllable way to silence a track) is actually managed using the MediaStreamTrack.enabled property, for which there are no events. Examples In this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for the MediaStreamTrack stored in the variable musicTrack. ...
...rty, for which there are no events. Examples In this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for the MediaStreamTrack stored in the variable musicTrack. musicTrack.
addEventListener("mute", event => { document.getElementById("timeline-widget").style.backgroundColor = "#aaa"; }, false); musicTrack.
addEventListener("unmute", event => { document.getElementById("timeline-widget").style.backgroundColor = "#fff"; }, false); With these event handlers in place, when the track musicTrack enters its muted state, the element with the ID timeline-widget gets its background color changed to #aaa. When the track exits the muted state--detected by the arrival of an unmuted event--the background color is restored to w...
Recording a media element - Web APIs
t 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. ...
...ideo.webm" whose contents are the recorded video. Lines 17-18 The size and type of the recorded media are output to the log area below the two videos and the download button. Line 20 The catch() for all the Promises outputs the error to the logging area by calling our log() function. Handling the stop button The last bit of code adds a handler for the click event on the stop button using
addEventListener(): stopButton.
addEventListener("click", function() { stop(preview.srcObject); }, false); This simply calls the stop() function we covered earlier. Result When put all together with the rest of the HTML and the CSS not shown above, it looks and works like this: You can take a look at all the code, including the parts hidden above because they aren't critical to the explanation of how the...
MessageEvent - Web APIs
ess it, even if their pages are running inside different windows. The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor. Both scripts contain this: var myWorker = new SharedWorker('worker.js'); Both scripts then access the worker through a MessagePort object created using the SharedWorker.port property. ...
...de the worker we use the SharedWorkerGlobalScope.onconnect handler to connect to the same port discussed above. The ports associated with that worker are accessible in the connect event's ports property -- we then use MessagePort start() method to start the port, and the onmessage handler to deal with messages sent from the main threads. onconnect = function(e) { var port = e.ports[0]; port.
addEventListener('message', function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); }); port.start(); // Required when using
addEventListener. Otherwise called implicitly by onmessage setter. } Specifications Specification Status Comment HTML Living StandardThe definition of 'MessageEvent' in that specification. Living Standa...
MessagePort: messageerror event - Web APIs
he ports to a different browsing context, such as another <iframe>, using code like this: const channel = new MessageChannel(); const myPort = channel.port1; const targetFrame = window.top.frames[1]; const targetOrigin = 'https://example.org'; const messageControl = document.querySelector('#message'); const channelMessageButton = document.querySelector('#channel-message'); channelMessageButton.
addEventListener('click', () => { myPort.postMessage(messageControl.value); }) targetFrame.postMessage('init', targetOrigin, [channel.port2]); The target can receive the port and start listening for messages and message errors on it using code like this: window.
addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.
addEventListener('message', (event) => { received.t...
...ageControl.value); }) targetFrame.postMessage('init', targetOrigin, [channel.port2]); The target can receive the port and start listening for messages and message errors on it using code like this: window.
addEventListener('message', (event) => { const myPort = event.ports[0]; myPort.
addEventListener('message', (event) => { received.textContent = event.data; }); myPort.
addEventListener('messageerror', (event) => { console.error(event.data); }); myPort.start(); }); Note that the listener must call MessagePort.start() before any messages will be delivered to this port. This is only needed when using the
addEventListener() method: if the receiver uses onmessage instead, start() is called implicitly: window.
addEventListener('message', (event) => { const myPor...
MessagePort - Web APIs
to be sent from one port and listening out for them arriving at the other. Note: This feature is available in Web Workers. Methods Inherits methods from its parent, EventTarget postMessage() Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts. start() Starts the sending of messages queued on the port (only needed when using EventTarget.
addEventListener; it is implied when using MessagePort.onmessage.) close() Disconnects the port, so it is no longer active. Event handlers Inherits event handlers from its parent, EventTarget onmessage An EventListener called when MessageEvent of type message is fired on the port--that is, when the port receives a message. onmessageerror An EventListener called when a MessageEvent of type MessageError ...
....port1 and transfer MessageChannel.port2 to the IFrame using the window.postMessage method along with a message. When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph. ...
NavigationPreloadManager - Web APIs
NavigationPreloadManager.setHeaderValue() Sets the value of the Service-Worker-Navigation-Preload header and returns an empty Promise. NavigationPreloadManager.getState() Returns a Promise that resolves to an object with properties indicating whether preload is enabled and the contents of the Service-Worker-Navigation-Preload. ...
...d Enabling Navigation Preloading
addEventListener('activate', event => { event.waitUntil(async function() { if (self.registration.navigationPreload) { // Enable navigation preloads! await self.registration.navigationPreload.enable(); } }()); }); Using a Preloaded Response The following example shows the implementation of a fetch event that uses a preloaded response.
addEventListener('fetch', event => { event.respondWith(async function() { // Respond from the cache if we can const cachedResponse = await caches.match(event.request); if (cachedResponse) return cachedResponse; // Else, use the preloaded response, if it's there const response = await event.preloadResponse; if (response) return response; // Else try the network. return fetch(eve...
Using Navigation Timing - Web APIs
e advantage of being able to provide timing information as perceived by the user rather than data that has no correlation to what the user experiences. Collecting timing information Using the API is as simple as obtaining the Performance object using window.performance and looking up what you need within the object returned. ...
...reload? Was this a navigation or a move forward or backward through history? How many (if any) redirects were required in order to complete the navigation? This information is provided by the Performance.navigation property, which returns a PerformanceNavigation object that includes the needed information. Let's add this information to the example above. ...
Navigator.sendBeacon() - Web APIs
k unloading the document, which slows down the next navigation. There is nothing the next page can do to avoid this, so the new page seems slow, even though it's the previous page's fault. The following example shows theoretical analytics code that attempts to submit data to a server with a synchronous XMLHttpRequest in an unload handler. This results in the next page load to be delayed. window.
addEventListener("unload", function logData() { var xhr = new XMLHttpRequest(); xhr.open("POST", "/log", false); // third parameter of `false` means synchronous xhr.send(analyticsData); }); This is what sendBeacon() replaces. With the sendBeacon() method, the data is transmitted asynchronously when the User Agent has an opportunity to do so, without delaying unload or the next navigation. This solves all ...
...next navigation. This solves all of the problems with submission of analytics data: The data is sent reliably It's sent asynchronously It doesn't impact the loading of the next page In addition, the code is simpler to write than any of the older techniques! The following example shows a theoretical analytics code pattern that submits data to a server using the sendBeacon() method. window.
addEventListener("unload", function logData() { navigator.sendBeacon("/log", analyticsData); }); The beacon sends an HTTP request via the POST method, with all relevant cookies available when called. Specifications Specification Status Comment BeaconThe definition of 'sendBeacon()' in that specification. Candidate Recommendation Initial definition ...
Navigator.onLine - Web APIs
Value online is a boolean true or false. Example View a live example. To check if you are online, query window.navigator.onLine, as in the following example: if (navigator.onLine) { console.log('online'); } else { console.log('offline'); } If the browser doesn't support navigator.onLine the above example will always come out as false/undefined. ...
...navigator.onLine, as in the following example: if (navigator.onLine) { console.log('online'); } else { console.log('offline'); } If the browser doesn't support navigator.onLine the above example will always come out as false/undefined. To see changes in the network state, use
addEventListener to listen for the events on window.online and window.offline, as in the following example: window.
addEventListener('offline', function(e) { console.log('offline'); }); window.
addEventListener('online', function(e) { console.log('online'); }); Specifications Specification Status Comment HTML Living StandardThe definition of 'navigator.onLine' in that specification. Living Standard Initial definition ...
Notification.close() - Web APIs
user already read the notification on the webpage in the case of a messaging app or the following song is already playing in a music app). Syntax Notification.close(); Parameters None. Returns Void. Examples In the following snippet, we have a simple function that when called creates an options object and then a new notification. ...
...reates an options object and then a new notification. At the end of the function, it also calls close() inside a
addEventListener() function to remove the notification when the relevant content has been read on the webpage. function spawnNotification(theBody, theIcon, theTitle) { var options = { body: theBody, icon: theIcon }; var n = new Notification(theTitle,options); document.
addEventListener('visibilitychange', function() { if (document.visibilityState === 'visible') { // The tab has become visible so clear the now-stale Notification. n.close(); } }); } Specifications Specification Status Comment Notifications API Living Standard Living standard ...
OrientationSensor - Web APIs
mples Basic Example The following example, which is loosely based on Intel's Orientation Phone demo, instantiates an AbsoluteOrientationSensor with a frequency of 60 times a second. On each reading it uses OrientationSensor.quaternion to rotate a visual model of a phone. ...
... of 60 times a second. On each reading it uses OrientationSensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceFrame: 'device' }; const sensor = new AbsoluteOrientationSensor(options); sensor.
addEventListener('reading', () => { // model is a Three.js object instantiated elsewhere. model.quaternion.fromArray(sensor.quaternion).inverse(); }); sensor.
addEventListener('error', error => { if (event.error.name == 'NotReadableError') { console.log("Sensor is not available."); } }); sensor.start(); Permissions Example Using orientation sensors requires requsting permissions for multiple device sensors. Becuase the Permissions uses promises, a good way to request permissions is to use Promise.all. const sensor = new AbsoluteOrientationSensor(); Promise.a...
ParentNode.replaceChildren() - Web APIs
are transferring to in another constant. It then calls replaceChildren() on the list to transfer the options to, using the spread operator to pass in all the options contained in both constants. ...
...ntById('yes'); const noBtn = document.getElementById('to-no'); const yesBtn = document.getElementById('to-yes'); yesBtn.
addEventListener('click', () => { const selectedTransferOptions = document.querySelectorAll('#no option:checked'); const existingYesOptions = document.querySelectorAll('#yes option'); yesSelect.replaceChildren(...selectedTransferOptions, ...existingYesOptions); }); noBtn.
addEventListener('click', () => { const selectedTransferOptions = document.querySelectorAll('#yes option:checked'); const existingNoOptions = document.querySelectorAll('#no option'); noSelect.replaceChildren(...selectedTransferOptions, ...existingNoOptions); }); The end result looks like this: Specification Specification Status Comment DOMThe definition of 'ParentNode.replaceChi...
PaymentRequest.onshippingaddresschange - Web APIs
}); PaymentRequest.onshippingaddresschange = function(shippingAddressChangeEvent) { ... }; Examples The shippingaddresschange event is triggered by a user-agent controlled interaction. If the address stored by the user agent changes at any time during a payment process, the event is triggered. ...
...ayment process, the event is triggered. To make sure an updated address is included when sending payment information to the server, you should add event listeners for a PaymentRequest object after instantiation, but before the call to show(). // Initialization of PaymentRequest arguments are excerpted for clarity. var payment = new PaymentRequest(supportedInstruments, details, options); request.
addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { updateDetails(details, request.shippingAddress, resolve); })); }); payment.show().then(function(paymentResponse) { // Processing of paymentResponse exerpted for the same of clarity. }).catch(function(err) { console.error("Uh oh, something bad happened", err.message); }); Specifications ...
PaymentRequest.onshippingoptionchange - Web APIs
}); PaymentRequest.onshippingoptionchange = function(shippingOptionChangeEvent) { ... }; Examples The shippingoptionchange event is triggered by a user-agent controlled interaction. If the option stored by the user agent changes at any time during a payment process, the event is triggered. ...
... To make sure an updated option is included when sending payment information to the server, you should add event listeners for a PaymentRequest object after instantiation, but before the call to show(). // Initialization of PaymentRequest arguments are excerpted for clarity. ...
PaymentRequest: paymentmethodchange event - Web APIs
y account, a paymentmethodchange event is fired to let you know about the change. Bubbles No Cancelable No Interface PaymentMethodChangeEvent Event handler property onpaymentmethodchange Examples Let's take a look at an example. This code creates a new PaymentRequest, adds a handler for the paymentmethodchange event by calling the request's
addEventListener(), then calls show() to present the payment interface to the user. The code assumes the existence of a method detailsForShipping(), which returns a PaymentDetailsUpdate object containing the shipping options for the ground shipping method, in the form found in the PaymentShippingOption dictionary. By doing so, the payment form defaults to the ground shipping method. const options = { requestS...
...h returns a PaymentDetailsUpdate object containing the shipping options for the ground shipping method, in the form found in the PaymentShippingOption dictionary. By doing so, the payment form defaults to the ground shipping method. ...
Proximity Events - Web APIs
nts but will never fire them. Proximity Events When the device proximity sensor detects a change between the device and an object, it notifies the browser of that change. When the browser gets such a notification, it fires a DeviceProximityEvent for any change, and a UserProximityEvent event in the case of a more rough change. This event can be captured at the window object level by using the
addEventListener method (using the deviceproximity or userproximity event name) or by attaching an event handler to the window.ondeviceproximity or window.onuserproximity properties. Once captured, the event object gives access to different kinds of information: The DeviceProximityEvent event provides an exact match for the distance between the device and the object through its value property. It also provide...
...device and the object through its value property. It also provides the closest and farthest distance the device is able to detect something through its min and max properties. The UserProximityEvent event provides a rough approximation of the distance, expressed through a boolean. The UserProximityEvent.near property is true if the object is close or false if the object is far. Example window.
addEventListener('userproximity', function(event) { if (event.near) { // let's power off the screen navigator.mozPower.screenEnabled = false; } else { // Otherwise, let's power on the screen navigator.mozPower.screenEnabled = true; } }); Specifications Specification Status Comment Proximity SensorThe definition of 'Proximity Events' in that specification. Wor...
PushEvent.data - Web APIs
The data read-only property of the PushEvent interface returns a reference to a PushMessageData object containing data sent to the PushSubscription. Syntax var myPushData = PushEvent.data; Value A PushMessageData object. Examples The following example takes data from a PushEvent and displays it on all of the service workers' clients. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated...
PushEvent - Web APIs
Properties Inherits properties from its parent, ExtendableEvent. Additional properties: PushEvent.data Read only Returns a reference to a PushMessageData object containing data sent to the PushSubscription. Methods Inherits methods from its parent, ExtendableEvent. Examples The following example takes data from a PushEvent and displays it on all of the service worker's clients. ...
... Working Draft Initial definition. Browser Compatibility The compatibility table on this page is gene...
RTCDTMFSender: tonechange event - Web APIs
ent Event handler property ontonechange To determine what tone started playing, or if a tone stopped playing, check the value of the event's tone property. Examples This example establishes a handler for the tonechange event which updates an element to display the currently playing tone in its content, or, if all tones have played, the string "<none>". ...
...rty ontonechange To determine what tone started playing, or if a tone stopped playing, check the value of the event's tone property. Examples This example establishes a handler for the tonechange event which updates an element to display the currently playing tone in its content, or, if all tones have played, the string "<none>". ...
RTCError - Web APIs
r isn't an SDP syntax error. sentAlert Read only If errorDetail is dtls-failure, this property is an unsigned long integer indicating the fatal DTLS error that was sent out by this device. If null, no DTLS error was transmitted. All RTCError objects have their name set to OperationError. Examples In this example, a handler is established for an RTCDataChannel's error event. ...
...error--, a message string is constructed to present the error message and the line number within the SDP at which the error occurred. This message is then displayed using a function called showMyAlertMessage(), which stands in for whatever output mechanism this code might use. Any other error is treated as terminal, causing a terminateMyConnection() function to be called. The above example uses
addEventListener() to add the handler for error events. You can also use the RTCDataChannel object's onerror event handler property, like this: dataChannel.onerror = (event) => { let error = event.error; /* and so forth */ }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCError' in that specification. Ca...
RTCErrorEvent.error - Web APIs
or isn't an SDP syntax error. sentAlert Read only If errorDetail is dtls-failure, this property is an unsigned long integer indicating the fatal DTLS error that was sent out by this device. If null, no DTLS error was transmitted. All RTCError objects have their name set to OperationError. Examples In this example, a handler is established for an RTCDataChannel's error event. ...
...error--, a message string is constructed to present the error message and the line number within the SDP at which the error occurred. This message is then displayed using a function called showMyAlertMessage(), which stands in for whatever output mechanism this code might use. Any other error is treated as terminal, causing a terminateMyConnection() function to be called. The above example uses
addEventListener() to add the handler for error events. You can also use the RTCDataChannel object's onerror event handler property, like this: dataChannel.onerror = (event) => { let error = event.error; /* and so forth */ }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCErrorEvent.error' in that specifica...
RTCIceTransport: gatheringstatechange event - Web APIs
overall state of the connection including every RTCIceTransport used by every RTCRtpSender and every RTCRtpReceiver on the entire connection. In contrast, gatheringstatechange represents changes to the candidate gathering state for a single transport. Examples This example creates a handler for gatheringstatechange events on each RTCRtpSender associated with a given RTCPeerConnection. ...
...atheringstatechange represents changes to the candidate gathering state for a single transport. Examples This example creates a handler for gatheringstatechange events on each RTCRtpSender associated with a given RTCPeerConnection. ...
RTCPeerConnection: addstream event - Web APIs
et up. pc is an RTCPeerConnection. ...
...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. You can also use the
addEventListener() method to set an event listener: pc.
addEventListener("addstream", ev => doAddStream(ev.stream), false); ...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
= new RTCPeerConnection(); // The following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ICE. ...
... Candidate Recommendation Initial specification. ...
RTCPeerConnection: connectionstatechange event - Web APIs
*/ } }, false); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'connectionstatechange' in that specification. Candidate Recommendation Initial specification. ...
...*/ } }, false); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'connectionstatechange' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection: iceconnectionstatechange event - Web APIs
layer makes this determination upon receiving the end-of-candidates signal, which is provided by caling addIceCandidate() with a candidate whose candidate property is an empty string (""), or by setting the RTCPeerConnection property canTrickleIceCandidates to false. ...
...connectionstatechange property or by using
addEventListener() on the RTCPeerConnection. In this example, a handler for iceconnectionstatechange is set up to update a call state indicator by using the value of iceConnectionState to create a string which corresponds to the name of a CSS class that we can assign to the status indicator to cause it to reflect the current state of the connection. ...
RTCPeerConnection: negotiationneeded event - Web APIs
t dispatched to the RTCPeerConnection when media is first added to the connection. This starts the process of ICE negotiation by instructing your code to begin exchanging ICE candidates through the signaling server. See Signaling transaction flow in Signaling and video calling for a description of the signaling process that begins with a negotiationneeded event. ...
... ICE candidates through the signaling server. See Signaling transaction flow in Signaling and video calling for a description of the signaling process that begins with a negotiationneeded event. Examples In this example, we use
addEventListener() to create an event handler for negotiationneeded. Its role is to create an SDP offer and send it through the signaling channel to the remote peer. ...
RTCTrackEvent - Web APIs
nt's receiver property). In addition, the MediaStreamTrack specified by the receiver's track is the same one specified by the event's track, and the track has been added to any associated remote MediaStream objects. You can add a track event listener to be notified when the new track is available so that you can, for example, attach its media to a <video> element, using either RTCPeerConnection.
addEventListener() or the ontrack event handler property. Note: It may be helpful to keep in mind that you receive the track event when a new inbound track has been added to your connection, and you call addTrack() to add a track to the far end of the connection, thereby triggering a track event on the remote peer. Example This simple example creates an event listener for the track event which sets the srcOb...
...d track has been added to your connection, and you call addTrack() to add a track to the far end of the connection, thereby triggering a track event on the remote peer. Example This simple example creates an event listener for the track event which sets the srcObject of the <video> element with the ID videobox to the first stream in the list passed in the event's streams array. peerConnection.
addEventListener("track", e => { let videoElement = document.getElementById("videobox"); videoElement.srcObject = e.streams[0]; }, false); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCTrackEvent' in that specification. Candidate Recommendation Initial specification. ...
RelativeOrientationSensor - Web APIs
ientation Phone demo, instantiates an RelativeOrientationSensor with a frequency of 60 times a second. Note that the Intel demo this is based on uses the AbsoluteOreintationSensor. On each reading it uses OrientationSensor.quaternion to rotate a visual model of a phone. ...
...uteOreintationSensor. On each reading it uses OrientationSensor.quaternion to rotate a visual model of a phone. const options = { frequency: 60, referenceFrame: 'device' }; const sensor = new RelativeOrientationSensor(options); sensor.
addEventListener('reading', () => { // model is a Three.js object instantiated elsewhere. model.quaternion.fromArray(sensor.quaternion).inverse(); }); sensor.
addEventListener('error', error => { if (event.error.name == 'NotReadableError') { console.log("Sensor is not available."); } }); sensor.start(); Permissions Example Using orientation sensors requires requsting permissions for multiple device sensors. Becuase the Permissions uses promises, a good way to request permissions is to use Promise.all. const sensor = new RelativeOrientationSensor(); Promise.a...
ResizeObserver - Web APIs
ll not change in response to the <div>'s width changing. ...
... Editor's Draft Initial definition. ...
SVGAnimationElement: endEvent event - Web APIs
s" repeatCount="indefinite" /> </circle> </svg> <hr> <button>Stop animation</button> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgElem = document.querySelector('svg'); let animateElem = document.querySelector('animateMotion'); let list = document.querySelector('ul'); let btn = document.querySelector('button'); animateElem.
addEventListener('beginEvent', () => { let listItem = document.createElement('li'); listItem.textContent = 'beginEvent fired'; list.appendChild(listItem); }) animateElem.
addEventListener('endEvent', () => { let listItem = document.createElement('li'); listItem.textContent = 'endEvent fired'; list.appendChild(listItem); }) animateElem.
addEventListener('repeatEvent', (e) => { let listItem = document...
...', () => { let listItem = document.createElement('li'); listItem.textContent = 'endEvent fired'; list.appendChild(listItem); }) animateElem.
addEventListener('repeatEvent', (e) => { let listItem = document.createElement('li'); let msg = 'repeatEvent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listItem.textContent = msg; list.appendChild(listItem); }) btn.
addEventListener('click', () => { btn.disabled = true; animateElem.setAttribute('repeatCount', '1'); }) Event handler property equivalent Note that you can also create an event listener for the end event using the onend event handler property: animateElem.onend = () => { console.log('endEvent fired'); } Specifications Specification Status Comment Scalable Vector Graphics (SVG)...
Screen Wake Lock API - Web APIs
atusElem.textContent = `${err.name}, ${err.message}`; } } Releasing wake lock The following example shows how to release the previously acquired wake lock. wakeLock.release() .then(() => { wakeLock = null; }); Listening for wake lock release This example updates the UI if the wake lock has been released for any reason (such as navigating away from the active window/tab). ...
...wake lock has been released for any reason (such as navigating away from the active window/tab). wakeLock.
addEventListener('release', () => { // the wake lock has been released statusElem.textContent = 'Wake Lock has been released'; }); Reacquiring a wake lock The following code reacquires the wake lock should the visibility of the document change and the wake lock is released. document.
addEventListener('visibilitychange', () => { if (wakeLock !== null && document.visibilityState === 'visible') { wakeLock = await navigator.wakeLock.request('screen'); } }); Putting it all together You can find the complete code on github here. The demo uses a button to acquire a wake lock and also release it, which in turn updates the UI. The UI also updates if the wake lock is released automatically fo...
Selection.containsNode() - Web APIs
sNode() only returns true when the entire node is part of the selection. If not specified, the default value false is used. Example Check for selection This snippet checks whether anything inside the body element is selected. console.log(window.getSelection().containsNode(document.body, true)); Find the hidden word In this example, a message appears when you select the secret word. ...
...the secret word. It uses
addEventListener() to check for selectionchange events. HTML <p>Can you find the secret word?</p> <p>Hmm, where <span id="secret" style="color:transparent">SECRET</span> could it be?</p> <p id="win" hidden>You found it!</p> JavaScript const secret = document.getElementById('secret'); const win = document.getElementById('win'); // Listen for selection changes document.
addEventListener('selectionchange', () => { const selection = window.getSelection(); const found = selection.containsNode(secret); win.toggleAttribute('hidden', !found); }); Result Specifications Specification Status Comment Selection APIThe definition of 'Selection.containsNode()' in that specification. Working Draft Current ...
ServiceWorker.onstatechange - Web APIs
} ) Examples This code snippet is from the service worker registration-events sample (live demo). The code listens for any change in the ServiceWorker.state and returns its value. ...
...For example: navigator.serviceWorker.register(..).then(function(swr) { swr.installing.state == "installing" swr.installing.onstatechange = function() { swr.installing == null; // At this point, swr.waiting OR swr.active might be true. T...
ServiceWorkerContainer.startMessages() - Web APIs
rolling service worker to the page (using Client.postMessage()) are queued while the page is loading, and get dispatched once the page's HTML document has been loaded and parsed (i.e. after the DOMContentLoaded event fires). It's possible to start dispatching these messages earlier by calling ServiceWorkerContainer.startMessages(), for example if you've invoked a message handler using EventTarget.
addEventListener() before the page has finished loading, but want to start processing the messages right away. Note: The messages start being sent automatically when setting the handler directly using ServiceWorkerContainer.onmessage. In this you don't need startMessages(). Syntax serviceWorkerContainer.startMessages(); Parameters None. Return value undefined. Examples if('serviceWorker' in navigator) ...
...r directly using ServiceWorkerContainer.onmessage. In this you don't need startMessages(). Syntax serviceWorkerContainer.startMessages(); Parameters None. Return value undefined. Examples if('serviceWorker' in navigator) { navigator.serviceWorker .register('/sw.js') .then(function() { console.log('Service Worker Registered'); }); } // ... navigator.serviceWorker.
addEventListener('message', (e) => { // ... }); navigator.serviceWorker.startMessages(); Specifications Specification Status Comment Service WorkersThe definition of 'ServiceWorkerContainer: startMessages()' in that specification. Working Draft Initial definition. ...
ServiceWorkerGlobalScope: message event - Web APIs
Interface ExtendableMessageEvent Event handler property onmessage Examples In the below example a page gets a handle to the ServiceWorker object via ServiceWorkerRegistration.active, and then calls its postMessage() function. ...
...r.serviceWorker.
addEventListener('message', event => { // event is a MessageEvent object console.log(`The service worker sent me a message: ${event.data}`); }); navigator.serviceWorker.ready.then( registration => { registration.active.postMessage("Hi service worker"); }); } The service worker can receive the message by listening to the message event: // in the service worker
addEventListener('message', event => { // event is an ExtendableMessageEvent object console.log(`The client sent me a message: ${event.data}`); event.source.postMessage("Hi client"); }); Specifications Specification Status Service WorkersThe definition of 'message' in that specification. Working Draft ...
ServiceWorkerGlobalScope: notificationclick event - Web APIs
The notificationclick event is fired to indicate that a system notification spawned by ServiceWorkerRegistration.showNotification() has been clicked. ...
... The notificationclick event is fired to indicate that a system notification spawned by ServiceWorkerRegistration.showNotification() has been clicked. ...
SharedWorker - Web APIs
ess it, even if their pages are running inside different windows. The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor. Both scripts contain this: var myWorker = new SharedWorker('worker.js'); Both scripts then access the worker through a MessagePort object created using the SharedWorker.port property. ...
...de the worker we use the SharedWorkerGlobalScope.onconnect handler to connect to the same port discussed above. The ports associated with that worker are accessible in the connect event's ports property -- we then use MessagePort start() method to start the port, and the onmessage handler to deal with messages sent from the main threads. onconnect = function(e) { var port = e.ports[0]; port.
addEventListener('message', function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); }); port.start(); // Required when using
addEventListener. Otherwise called implicitly by onmessage setter. } Specifications Specification Status Comment HTML Living StandardThe definition of 'SharedWorker' in that specification. Living Standa...
SharedWorkerGlobalScope: connect event - Web APIs
ssage() method can be used to send messages back to the main thread using the worker. ...
...worker. self.onconnect = function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); } port.start(); } For a complete running example, see our Basic shared worker example (run shared worker.)
addEventListener equivalent You could also set up an event handler using the
addEventListener() method: self.
addEventListener('connect', function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); } }); Specifications Specification Status HTML Living StandardThe definition of 'connect event' in that specification. Living Standard ...
SpeechRecognition: error event - Web APIs
The error event of the Web Speech API SpeechRecognition object is fired when a speech recognition error occurs. ...
... Web Speech API SpeechRecognition object is fired when a speech recognition error occurs. ...
SpeechRecognition: nomatch event - Web APIs
API is fired when the speech recognition service returns a final result with no significant recognition. This may involve some degree of recognition, which doesn't meet or exceed the confidence threshold. ...
... involve some degree of recognition, which doesn't meet or exceed the confidence threshold. Bubbles No Cancelable No Interface SpeechRecognitionEvent Event handler property onnomatch Examples You can use the nomatch event in an
addEventListener method: var recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.
addEventListener('nomatch', function() { console.log('Speech not recognized'); }); Or use the onnomatch event handler property: recognition.onnomatch = function() { console.log('Speech not recognized'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech recognition events' in that specification. Draft ...
SpeechRecognition: result event - Web APIs
the speech recognition service returns a result -- a word or phrase has been positively recognized and this has been communicated back to the app Bubbles No Cancelable No Interface SpeechRecognitionEvent Event handler property onresult Examples This code is excerpted from our Speech color changer example. ...
...n communicated back to the app Bubbles No Cancelable No Interface SpeechRecognitionEvent Event handler property onresult Examples This code is excerpted from our Speech color changer example. ...
SpeechRecognition: soundend event - Web APIs
The soundend event of the Web Speech API is fired when any sound -- recognisable speech or not -- has stopped being detected. ...
...f the Web Speech API is fired when any sound -- recognisable speech or not -- has stopped being detected. Bubbles No Cancelable No Interface Event Event handler property onsoundend Examples You can use the soundend event in an
addEventListener method: var recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.
addEventListener('soundend', function(event) { console.log('Sound has stopped being received'); }); Or use the onsoundend event handler property: recognition.onsoundend = function(event) { console.log('Sound has stopped being received'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech recognition events' in that specification. Draft ...
SpeechRecognition: speechend event - Web APIs
The speechend event of the Web Speech API is fired when speech recognized by the speech recognition service has stopped being detected. ...
...Speech API is fired when speech recognized by the speech recognition service has stopped being detected. Bubbles No Cancelable No Interface Event Event handler property onspeechend Examples You can use the speechend event in an
addEventListener method: var recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.
addEventListener('speechend', function() { console.log('Speech has stopped being detected'); }); Or use the onspeechend event handler property: recognition.onspeechend = function() { console.log('Speech has stopped being detected'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech recognition events' in that specification. Draft ...
SpeechRecognition: speechstart event - Web APIs
The speechstart event of the Web Speech API is fired when sound recognized by the speech recognition service as speech has been detected. ...
...h API is fired when sound recognized by the speech recognition service as speech has been detected. Bubbles No Cancelable No Interface Event Event handler property onspeechstart Examples You can use the speechstart event in an
addEventListener method: var recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.
addEventListener('speechstart', function() { console.log('Speech has been detected'); }); Or use the onspeechstart event handler property: recognition.onspeechstart = function() { console.log('Speech has been detected'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech recognition events' in that specification. Draft ...
SpeechRecognition: start event - Web APIs
The start event of the Web Speech API SpeechRecognition object is fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition. ...
...gun listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition. Bubbles No Cancelable No Interface Event Event handler property onstart Examples You can use the start event in an
addEventListener method: var recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.
addEventListener('start', function() { console.log('Speech recognition service has started'); }); Or use the onstart event handler property: recognition.onstart = function() { console.log('Speech recognition service has started'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech recognition events' in that specification. Draft ...
SpeechSynthesis: voiceschanged event - Web APIs
ld be returned by the SpeechSynthesis.getVoices() method has changed (when the voiceschanged event fires.) Bubbles No Cancelable No Interface Event Event handler property onvoiceschanged Examples This could be used to repopulate a list of voices that the user can choose between when the event fires. ...
...(when the voiceschanged event fires.) Bubbles No Cancelable No Interface Event Event handler property onvoiceschanged Examples This could be used to repopulate a list of voices that the user can choose between when the event fires. ...
SpeechSynthesisUtterance: boundary event - Web APIs
The boundary event of the Web Speech API is fired when the spoken utterance reaches a word or sentence boundary. ...
... The boundary event of the Web Speech API is fired when the spoken utterance reaches a word or sentence boundary. ...
SpeechSynthesisUtterance: end event - Web APIs
The end event of the Web Speech API SpeechSynthesisUtterance object is fired when the utterance has finished being spoken. ...
... The end event of the Web Speech API SpeechSynthesisUtterance object is fired when the utterance has finished being spoken. ...
SpeechSynthesisUtterance: error event - Web APIs
The error event of the Web Speech API SpeechSynthesisUtterance object is fired when an error occurs that prevents the utterance from being succesfully spoken. ...
... The error event of the Web Speech API SpeechSynthesisUtterance object is fired when an error occurs that prevents the utterance from being succesfully spoken. ...
SubtleCrypto.deriveKey() - Web APIs
y(alicesKeyPair.privateKey, bobsKeyPair.publicKey); // Bob generates the same secret key using his private key and Alice's public key. let bobsSecretKey = await deriveSecretKey(bobsKeyPair.privateKey, alicesKeyPair.publicKey); // Alice can then use her copy of the secret key to encrypt a message to Bob. ...
...icesKeyPair.publicKey); // Alice can then use her copy of the secret key to encrypt a message to Bob. let encryptButton = document.querySelector(".ecdh .encrypt-button"); encryptButton.
addEventListener("click", () => { encrypt(alicesSecretKey); }); // Bob can use his copy to decrypt the message. let decryptButton = document.querySelector(".ecdh .decrypt-button"); decryptButton.
addEventListener("click", () => { decrypt(bobsSecretKey); }); } PBKDF2 In this example we ask the user for a password, then use it to derive an AES key using PBKDF2, then use the AES key to encrypt a message. See the complete code on GitHub. /* Get some key material to use as input to the deriveKey method. The key material is a password supplied by the user. */ function getKeyMaterial() { let password ...
Using Touch Events - Web APIs
) method in the touch event handlers. For more information about the interaction between mouse and touch events, see Supporting both TouchEvent and MouseEvent. Basic steps This section contains a basic usage of using the above interfaces. See the Touch Events Overview for a more detailed example. Register an event handler for each touch event type. // Register touch event handlers someElement.
addEventListener('touchstart', process_touchstart, false); someElement.
addEventListener('touchmove', process_touchmove, false); someElement.
addEventListener('touchcancel', process_touchcancel, false); someElement.
addEventListener('touchend', process_touchend, false); Process an event in an event handler, implementing the application's gesture semantics. // touchstart handler function process_touchstart(ev) { ...
...ion process_touchstart(ev) { // Use the event's data to call out to the appropriate gesture handlers switch (ev.touches.length) { case 1: handle_one_touch(ev); break; case 2: handle_two_touches(ev); break; case 3: handle_three_touches(ev); break; default: gesture_not_supported(ev); break; } } Access the attributes of a touch point. // Create touchstart handler someElement.
addEventListener('touchstart', function(ev) { // Iterate through the touch points that were activated // for this element and process each event 'target' for (var i=0; i < ev.targetTouches.length; i++) { process_target(ev.targetTouches[i].target); } }, false); Prevent the browser from processing emulated mouse events. // touchmove handler function process_touchmove(ev) { // Set call preventDefaul...
WebGLRenderingContext.makeXRCompatible() - Web APIs
VR mode button. This is important, which we'll explore shortly. ...
...handles starting up graphics, switching to VR mode, and so forth looks like this: const outputCanvas = document.querySelector(".output-canvas"); const gl = outputCanvas.getContext("webgl"); let xrSession = null; let usingXR = false; let currentScene = "scene1"; let glStartButton; let xrStartButton; window.
addEventListener("load", (event) => { loadSceneResources(currentScene); glStartButton.
addEventListener("click", handleStartButtonClick); xrStartButton.
addEventListener("click", handleStartButtonClick); }); outputCanvas.
addEventListener("webglcontextlost", (event) => { /* The context has been lost but can be restored */ event.canceled = true; }); /* When the GL context is reconnected, reload the resources for the current scene. */ outputCanvas.
addEventListener("webglcontextrestored", (ev...
Clearing by clicking - Web APIs
The event handler removes // itself, because it only needs to run once. window.removeEventListener(evt.type, setupWebGL, false); // Adding the same click event handler to both canvas and // button. var canvas = document.querySelector("#canvas-view"); var button = document.querySelector("#color-switcher...
...tion setupWebGL (evt) { "use strict" // Cleaning after ourselves. The event handler removes // itself, because it only needs to run once. window.removeEventListener(evt.type, setupWebGL, false); // Adding the same click event handler to both canvas and // button. var canvas = document.querySelector("#canvas-view"); var button = document.querySelector("#color-switcher"); canvas.
addEventListener("click", switchColor, false); button.
addEventListener("click", switchColor, false); // A variable to hold the WebGLRenderingContext. var gl; // The click event handler. function switchColor () { // Referring to the externally defined gl variable. // If undefined, try to obtain the WebGLRenderingContext. // If failed, alert user of failure. // Otherwise, initialize the ...
Color masking - Web APIs
height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : inline-block; font-family : serif; font-size : inherit; font-weight : 900; color : white; margin : auto; padding : 0.6em 1.2em; } #red-toggle { background-color : red; } #green-toggle { background-color : green; } #blue-toggle { background-color : blue; } window.
addEventListener("load", function setupAnimation (evt) { "use strict" window.removeEventListener(evt.type, setupAnimation, false); var canvas = document.querySelector("canvas"); var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { document.querySelector("p").innerHTML = "Failed to get WebGL context." + "Your browser or device may not support W...
... browser or device may not support WebGL."; return; } gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); var timer = setInterval(drawAnimation, 1000); var mask = [true, true, true]; var redtoggle = document.querySelector("#red-toggle"), greentoggle = document.querySelector("#green-toggle"), bluetoggle = document.querySelector("#blue-toggle"); redtoggle.
addEventListener("click", setColorMask, false); greentoggle.
addEventListener("click", setColorMask, false); bluetoggle.
addEventListener("click", setColorMask, false); function setColorMask(evt) { var index = evt.target === greentoggle && 1 || evt.target === bluetoggle && 2 || 0; mask[index] = !mask[index]; if (mask[index] === true) evt.target.innerHTML="On"; else ...
Simple color animation - Web APIs
var timer; // Click event handlers. var button = document.querySelector("#animation-onoff"); var verb = document.querySelector("strong"); function startAnimation(evt) { button.removeEventListener(evt.type, ...
...vt) { "use strict" window.removeEventListener(evt.type, setupAnimation, false); // A variable to hold a timer that drives the animation. var timer; // Click event handlers. var button = document.querySelector("#animation-onoff"); var verb = document.querySelector("strong"); function startAnimation(evt) { button.removeEventListener(evt.type, startAnimation, false); button.
addEventListener("click", stopAnimation, false); verb.innerHTML="stop"; // Setup animation loop by redrawing every second. timer = setInterval(drawAnimation, 1000); // Give immediate feedback to user after clicking, by // drawing one animation frame. drawAnimation(); } function stopAnimation(evt) { button.removeEventListener(evt.type, stopAnimation, false); button.addEventListe...
Animating textures in WebGL - Web APIs
We set it to autoplay, mute th...
...We set it to autoplay, mute the sound, and loop the video. We then set up two events to make sure the video is playing and the time ...
Using DTMF with WebRTC - Web APIs
udio but not video. dialButton and logElement These variables will be used to store references to the dial button and the <div> into which logging information will be written. They'll get set up when the page is first loaded. See Initialization below. ...
... will be written. They'll get set up when the page is first loaded. See Initialization below. Initialization When the page loads, we do some basic setup: we fetch references to the dial button and the log output box elements, and we use
addEventListener() to add an event listener to the dial button so that clicking it calls the connectAndDial() function to begin the connection process. window.
addEventListener("load", function() { logElement = document.querySelector(".log"); dialButton = document.querySelector("#dial"); dialButton.
addEventListener("click", connectAndDial, false); }); Starting the connection process When the dial button is clicked, connectAndDial() is called. This starts building the WebRTC connection in preparation for sending the DTMF codes. function connectAndDial() { ca...
Using WebRTC data channels - Web APIs
ndle the negotiations for you, causing the remote peer to create a data channel and linking the two together across the network. The RTCDataChannel object is returned immediately by createDataChannel(); you can tell when the connection has been made successfully by watching for the open event to be sent to the RTCDataChannel. let dataChannel = pc.createDataChannel("MyApp Channel"); dataChannel.
addEventListener("open", (event) => { beginTransmission(dataChannel); }); Manual negotiation To manually negotiate the data channel connection, you need to first create a new RTCDataChannel object using the createDataChannel() method on the RTCPeerConnection, specifying in the options a negotiated property set to true. This signals to the peer connection to not attempt to negotiate the channel on your behalf...
...behalf. Then negotiate the connection out-of-band, using a web server or other means. This process should signal to the remote peer that it should create its own RTCDataChannel with the negotiated property also set to true, using the same id. This will link the two objects across the RTCPeerConnection. let dataChannel = pc.createDataChannel("MyApp Channel", { negotiated: true }); dataChannel.
addEventListener("open", (event) => { beginTransmission(dataChannel); }); requestRemoteChannel(dataChannel.id); In this code snippet, the channel is created with negotiated set to true, then a function called requestRemoteChannel() is used to trigger negotiation, to create a remote channel with the same ID as the local channel. Doing this lets you create data channels with each peer using different propertie...
WebSocket - Web APIs
n the connection is opened. WebSocket.protocol Read only The sub-protocol selected by the server. WebSocket.readyState Read only The current state of the connection. WebSocket.url Read only The absolute URL of the WebSocket. Methods WebSocket.close([code[, reason]]) Closes the connection. WebSocket.send(data) Enqueues data to be transmitted. Events Listen to these events using
addEventListener() or by assigning an event listener to the oneventname property of this interface. close Fired when a connection with a WebSocket is closed. Also available via the onclose property error Fired when a connection with a WebSocket has been closed because of an error, such as when some data couldn't be sent. Also available via the onerror property. message Fired when data is received throug...
... some data couldn't be sent. Also available via the onerror property. message Fired when data is received through a WebSocket. Also available via the onmessage property. open Fired when a connection with a WebSocket is opened. Also available via the onopen property. Examples // Create WebSocket connection. const socket = new WebSocket('ws://localhost:8080'); // Connection opened socket.
addEventListener('open', function (event) { socket.send('Hello Server!'); }); // Listen for messages socket.
addEventListener('message', function (event) { console.log('Message from server ', event.data); }); Specifications Specification Status HTML Living StandardThe definition of 'WebSocket' in that specification. Living Standard ...
Web Audio API best practices - Web APIs
create an audio context (either offline or online) it is created with a state, which can be suspended, running, or closed. When working with an AudioContext, if you create the audio context from inside a click event the state should automatically be set to running. Here is a simple example of creating the context from inside a click event: const button = document.querySelector('button'); button.
addEventListener('click', function() { const audioCtx = new AudioContext(); }, false); If however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction. We can use the same click event example here, test for the state of the context and start it, if it is suspended, using the resume() method. const audioCtx = new AudioCon...
..., false); If however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction. We can use the same click event example here, test for the state of the context and start it, if it is suspended, using the resume() method. const audioCtx = new AudioContext(); const button = document.querySelector('button'); button.
addEventListener('click', function() { // check if context is in suspended state (autoplay policy) if (audioCtx.state === 'suspended') { audioCtx.resume(); } }, false); You might instead be working with an OfflineAudioContext, in which case you can resume the suspended audio context with the startRendering() method. User control If your website or application contains sound, you should a...
Using IIR filters - Web APIs
ufferSource(); soundSource.buffer = audioBuffer; soundSource.connect(audioContext.destination); soundSource.start(); return soundSource; } This function is called when the play button is pressed. The play button HTML looks like this: <button class="button-play" role="switch" data-playing="false" aria-pressed="false">Play</button> And the click event listener starts like so: playButton.
addEventListener('click', function() { if (this.dataset.playing === 'false') { srcNode = playSourceNode(audioCtx, sample); ... }, false); The toggle that turns the IIR filter on and off is set up in the similar way. First, the HTML: <button class="button-filter" role="switch" data-filteron="false" aria-pressed="false" aria-describedby="label" disabled></button> The filter button's click han...
...ioCtx, sample); ... }, false); The toggle that turns the IIR filter on and off is set up in the similar way. First, the HTML: <button class="button-filter" role="switch" data-filteron="false" aria-pressed="false" aria-describedby="label" disabled></button> The filter button's click handler then connects the IIRFilter up to the graph, between the source and the detination: filterButton.
addEventListener('click', function() { if (this.dataset.filteron === 'false') { srcNode.disconnect(audioCtx.destination); srcNode.connect(iirfilter).connect(audioCtx.destination); ... }, false); Frequency response We only have one method available on IIRFilterNode instances, getFrequencyResponse(), this allows us to see what is happening to the frequencies of the audio being passed i...
Window: afterprint event - Web APIs
The afterprint event is fired after the associated document has started printing or the print preview has been closed. ...
... The afterprint event is fired after the associated document has started printing or the print preview has been closed. ...
Window: appinstalled event - Web APIs
The appinstalled event of the Web Manifest API is fired when the browser has successfully installed a page as an application. ...
... The appinstalled event of the Web Manifest API is fired when the browser has successfully installed a page as an application. ...
Window: beforeprint event - Web APIs
The beforeprint event is fired when the associated document is about to be printed or previewed for printing. ...
... The beforeprint event is fired when the associated document is about to be printed or previewed for printing. ...
Window: blur event - Web APIs
The blur event fires when an element has lost focus. The opposite of blur is focus. Bubbles No Cancelable No Interface FocusEvent Event handler property onblur Sync / Async Sync Composed Yes Examples Live example This example changes the appearance of a document when it loses focus. It uses
addEventListener() to monitor focus and blur events. HTML <p id="log">Click on this document to give it focus.</p> CSS .paused { background: #ddd; color: #555; } JavaScript function pause() { document.body.classList.add('paused'); log.textContent = 'FOCUS LOST!'; } function play() { document.body.classList.remove('paused'); log.textContent = 'This document has focus. Click outside the document to lose focus.'; } cons...
...cument to give it focus.</p> CSS .paused { background: #ddd; color: #555; } JavaScript function pause() { document.body.classList.add('paused'); log.textContent = 'FOCUS LOST!'; } function play() { document.body.classList.remove('paused'); log.textContent = 'This document has focus. Click outside the document to lose focus.'; } const log = document.getElementById('log'); window.
addEventListener('blur', pause); window.
addEventListener('focus', play); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Document Object Model (DOM) Level 3 Events Specification Obsolete Initial definition ...
Window: focus event - Web APIs
The focus event fires when an element has received focus. The opposite of focus is blur. Bubbles No Cancelable No Interface FocusEvent Event handler property onfocus Sync / Async Sync Composed Yes Examples Live example This example changes the appearance of a document when it loses focus. It uses
addEventListener() to monitor focus and blur events. HTML <p id="log">Click on this document to give it focus.</p> CSS .paused { background: #ddd; color: #555; } JavaScript function pause() { document.body.classList.add('paused'); log.textContent = 'FOCUS LOST!'; } function play() { document.body.classList.remove('paused'); log.textContent = 'This document has focus. Click outside the document to lose focu...
...cument to give it focus.</p> CSS .paused { background: #ddd; color: #555; } JavaScript function pause() { document.body.classList.add('paused'); log.textContent = 'FOCUS LOST!'; } function play() { document.body.classList.remove('paused'); log.textContent = 'This document has focus. Click outside the document to lose focus.'; } const log = document.getElementById('log'); window.
addEventListener('blur', pause); window.
addEventListener('focus', play); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Document Object Model (DOM) Level 3 Events Specification Obsolete Initial definition ...
Window: hashchange event - Web APIs
The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol). ...
... The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol). ...
Window: load event - Web APIs
cluding all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. ...
...plate-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } JS const log = document.querySelector('.event-log-contents'); const reload = document.querySelector('#reload'); reload.
addEventListener('click', () => { log.textContent =''; window.setTimeout(() => { window.location.reload(true); }, 200); }); window.
addEventListener('load', (event) => { log.textContent = log.textContent + 'load\n'; }); document.
addEventListener('readystatechange', (event) => { log.textContent = log.textContent + `readystate: ${document.readyState}\n`; }); document.
addEventListener('DOMConte...
Window: messageerror event - Web APIs
The messageerror event is fired on a Window object when it receives a message that can't be deserialized. ...
... The messageerror event is fired on a Window object when it receives a message that can't be deserialized. ...
Window.ondragdrop - Web APIs
b: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. Removed in Firefox 50, and never implemented in any other browser. Use the modern standard HTML5 drag and drop feature instead. Summary An event handler for drag and drop events sent to the window. Syntax window.ondragdrop = funcRef; window.
addEventListener("dragdrop", funcRef, useCapturing); funcRef The event handler function to be registered. The window.ondragdrop property and the ondragdrop attribute are not implemented in Gecko (bug 112288), you have to use
addEventListener. See
addEventListener for details. Example Fire an alert on dragdrop In this example, an event listener is added to the window (the event target). If, from an exte...
...on dragdrop In this example, an event listener is added to the window (the event target). If, from an external source, a tab, a link, marked text or a file is dragged and dropped onto this window, the alert is fired. Note how event.stopPropagation(); prevents the browser from loading the dropped tab, link or file. <html> <head><title>dragdroptest</title> <script type="text/javascript"> window.
addEventListener("dragdrop", testfunc, false); function testfunc(event) { alert("dragdrop!"); event.stopPropagation(); } </script> </head> <body> I am bodytext </body> </html> Specification Not part of specification. ...
Window: unhandledrejection event - Web APIs
The event includes two useful pieces of information: promise The actual Promise which was rejected with no handler available to deal with the rejection. reason The reason that would have been passed into the rejection handler if one had existed. See catch() for details. Basic error logging This example simply logs information about the unhandled promise rejection to the console. ...
...as Node.js) report unhandled promise rejections to the console by default. You can prevent that from happening by adding a handler for unhandledrejection events that--in addition to any other tasks you wish to perform--calls preventDefault() to cancel the event, preventing it from bubbling up to be handled by the runtime's logging code. This works because unhandledrejection is cancelable. window.
addEventListener('unhandledrejection', function (event) { // ...your code here to handle the unhandled rejection... // Prevent the default handling (such as outputting the // error to the console) event.preventDefault(); }); Specifications Specification Status Comment HTML Living StandardThe definition of 'unhandledrejection' in that specification. Living Standard In...
Window - Web APIs
tes a function after the browser has finished other heavy tasks Window.setResizable() Toggles a user's ability to resize a window. Window.sizeToContent() Sizes the window according to its content. Window.stop() This method stops window loading. Window.updateCommands() Updates the state of commands of the current chrome window (UI). Methods implemented from elsewhere EventTarget.
addEventListener() Register an event handler to a specific event type on the window. EventTarget.dispatchEvent() Used to trigger an event. WindowOrWorkerGlobalScope.atob() Decodes a string of data which has been encoded using base-64 encoding. WindowOrWorkerGlobalScope.btoa() Creates a base-64 encoded ASCII string from a string of binary data. WindowOrWorkerGlobalScope.clearInterval() Cancels the repeate...
...ndowEventHandlers.onstorage Called when there is a change in session storage or local storage. See storage event GlobalEventHandlers.onsubmit Called when a form is submitted WindowEventHandlers.onunhandledrejection An event handler for unhandled Promise rejection events. WindowEventHandlers.onunload Called when the user navigates away from the page. Events Listen to these events using
addEventListener() or by assigning an event listener to the oneventname property of this interface. error Fired when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid. Also available via the onerror property. languagechange Fired at the global scope object when the user's preferred language changes. Also available via the ...
Worker: message event - Web APIs
ge event is fired on a Worker object when the worker's parent receives a message from its worker (i.e. when the worker sends a message using DedicatedWorkerGlobalScope.postMessage()). ...
...m its worker (i.e. when the worker sends a message using DedicatedWorkerGlobalScope.postMessage()). ...
Synchronous and asynchronous requests - Web APIs
e flag. When fetch with keepalive isn't available, you can consider using the navigator.sendBeacon() API, which can support these use cases while typically delivering a good UX. The following example shows theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unloading of the page to be delayed. window.
addEventListener('unload', logData, false); function logData() { var client = new XMLHttpRequest(); client.open("POST", "/log", false); // third parameter indicates sync xhr. :( client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); client.send(analyticsData); } Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had...
... client.send(analyticsData); } Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. The following example shows a theoretical analytics code pattern that submits data to a server by using the sendBeacon() method. window.
addEventListener('unload', logData, false); function logData() { navigator.sendBeacon("/log", analyticsData); } ...
XMLHttpRequest: abort event - Web APIs
} JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.
addEventListener('loadstart', handleEvent); xhr.
addEventListener('load', handleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("...
...dleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.
addEventListener('click', () => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort(); }); Result Specifications Specification Status ...
XMLHttpRequest: error event - Web APIs
} JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.
addEventListener('loadstart', handleEvent); xhr.
addEventListener('load', handleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("...
...dleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.
addEventListener('click', () => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort(); }); Result Specifications Specification Status ...
XMLHttpRequest: load event - Web APIs
} JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.
addEventListener('loadstart', handleEvent); xhr.
addEventListener('load', handleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("...
...dleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.
addEventListener('click', () => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort(); }); Result Specifications Specification Status ...
XMLHttpRequest: loadend event - Web APIs
} JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.
addEventListener('loadstart', handleEvent); xhr.
addEventListener('load', handleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("...
...dleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.
addEventListener('click', () => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort(); }); Result Specifications Specification Status ...
XMLHttpRequest: loadstart event - Web APIs
} JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.
addEventListener('loadstart', handleEvent); xhr.
addEventListener('load', handleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("...
...dleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.
addEventListener('click', () => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort(); }); Result Specifications Specification Status ...
XMLHttpRequest: progress event - Web APIs
} JS const xhrButtonSuccess = document.querySelector('.xhr.success'); const xhrButtonError = document.querySelector('.xhr.error'); const xhrButtonAbort = document.querySelector('.xhr.abort'); const log = document.querySelector('.event-log'); function handleEvent(e) { log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.
addEventListener('loadstart', handleEvent); xhr.
addEventListener('load', handleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("...
...dleEvent); xhr.
addEventListener('loadend', handleEvent); xhr.
addEventListener('progress', handleEvent); xhr.
addEventListener('error', handleEvent); xhr.
addEventListener('abort', handleEvent); } function runXHR(url) { log.textContent = ''; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg'); }); xhrButtonError.
addEventListener('click', () => { runXHR('https://somewhere.org/i-dont-exist'); }); xhrButtonAbort.
addEventListener('click', () => { runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg').abort(); }); Result Specifications Specification Status ...
XRReferenceSpace: reset event - Web APIs
evice is able to regain tracking within the same tracking area. Nor will be be fired at an unbounded reference space as it makes small adjustments to its native origin over time to maintain the space's stability in the vicinity of the user; only large discontinuities will trigger a reset. Examples To add a handler for the reset event, you can use either of two approaches. ...
... same tracking area. Nor will be be fired at an unbounded reference space as it makes small adjustments to its native origin over time to maintain the space's stability in the vicinity of the user; only large discontinuities will trigger a reset. Examples To add a handler for the reset event, you can use either of two approaches. First, you can use the
addEventListener() method: viewerRefSpace.
addEventListener("reset", (event) => { /* perform reset related tasks */ }); The second option is to set the XRReferenceSpace object's onreset event handler property: viewerRefSpace.onreset = (event) => { /* perform reset related tasks */ }; Specifications Specification Status Comment WebXR Device APIThe definition of 'reset event' in that specification. Working Draft Initi...
XRSession: end event - Web APIs
the WebXR session has ended, either because the web application has chosen to stop the session, or because the user agent terminated the session. ...
...se the web application has chosen to stop the session, or because the user agent terminated the session. Bubbles No Cancelable No Interface XRSessionEvent Event handler XRSession.onend Example To be informed when a WebXR session comes to an end, you can add a handler to your XRSession instance using
addEventListener(), like this: XRSession.
addEventListener("end", function(event) { /* the session has shut down */ }); Alternatively, you can use the XRSession.onend event handler property to establish a handler for the end event: XRSession.onend = function(event) { /* the session has shut down */ } Specifications Specification Status Comment WebXR Device APIThe definition of 'end event' in that specification. Work...
XRSession: select event - Web APIs
eo tracking system or handheld controller with an accelerometer. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onselect For details on how the selectstart, select, and selectend events work, and how you should react to them, see Primary actions in Inputs and input sources. ...
...lectstart, select, and selectend events work, and how you should react to them, see Primary actions in Inputs and input sources. Examples The following example uses
addEventListener() to set up a handler for the select event. The handler fetches the pose representing the target ray for tracked-pointer inputs and sends the pose's transform to a function called myHandleSelectWithRay(). ...
XRSession: squeeze event - Web APIs
system or handheld controller with an accelerometer. Bubbles Yes Cancelable No Interface XRInputSourceEvent Event handler property onsqueeze For details on how the squeezestart, squeeze, and squeezeend events work, and how you should react to them, see Primary squeeze actions in Inputs and input sources. Examples The following example uses
addEventListener() to set up a handler for the squeeze event. The handler fetches the pose representing the target ray for tracked-pointer inputs and sends the pose's transform to a function called myHandleSqueezeWithRay(). This code treats the squeeze as an instantaneous action that doesn't involve tracking an ongoing activity. If you need to track a squeeze action that isn't instantaneous, listen for the squee...
... target ray for tracked-pointer inputs and sends the pose's transform to a function called myHandleSqueezeWithRay(). This code treats the squeeze as an instantaneous action that doesn't involve tracking an ongoing activity. If you need to track a squeeze action that isn't instantaneous, listen for the squeezestart and squeezeend events to sense when the squeeze action begins and ends. ...
XRSession: visibilitychange event - Web APIs
lityState property to determine the new visibility state. Bubbles Yes Cancelable No Interface XRSessionEvent Event handler property onvisibilitychange When the XRSession receives this event, the visibility state has already been changed. ...
...e XRSessionEvent Event handler property onvisibilitychange When the XRSession receives this event, the visibility state has already been changed. ...
XRSystem: requestSession() - Web APIs
n for a number of reasons, which are covered in more detail in Permissions and security in WebXR Device API. Examples Creating an immersive VR session The following example calls requestSession() requesting an "immersive-vr" session. If the Promise resolves, it sets up a session and initiates the animation loop. navigator.xr.requestSession("immersive-vr") .then((xrSession) => { xrSession.
addEventListener('end', onXRSessionEnded); // Do necessary session setup here. // Begin the session's animation loop. xrSession.requestAnimationFrame(onXRAnimationFrame); }).catch(function(error) { // "immersive-vr" sessions are not supported console.warn("'immersive-vr' isn't supported, or an error occurred activating VR!"); }); Verifying WebXR support and using a button to start VR mode The followin...
...sion option before enabling controls for entering XR. Adding controls is a necessary step because entering XR requires a user action. Finally, the onButtonClicked() method calls requestSession() using the same session option passed to isSessionSupported(). ...
Using the link role - Accessibility
ARIA attributes used link Related ARIA techniques button role Additional resources ARIA Best Practices - Link ...
... ARIA attributes used link Related ARIA techniques button role Additional resources ARIA Best Practices - Link Role: http://www.w3.org/TR/wai-aria-practices/#lin...
ARIA: grid role - Accessibility
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, p...
...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, p...
Coordinate systems - CSS: Cascading Style Sheets
coordinates in the given coordinate system. For example, if the value of type is "page", then idX is "pageX" and idY is "pageY". Handling the mouse events setCoords() is called by the event handler for the various mouse events, named update(); this is shown below. ...
...le, if the value of type is "page", then idX is "pageX" and idY is "pageY". Handling the mouse events setCoords() is called by the event handler for the various mouse events, named update(); this is shown below. function update(e) { setCoords(e, "offset"); setCoords(e, "client"); setCoords(e, "page"); setCoords(e, "screen"); } inner.
addEventListener("mouseenter", update, false); inner.
addEventListener("mousemove", update, false); inner.
addEventListener("mouseleave", update, false); The event handler is in the update() method. It simply calls setCoords() once for each coordinate system, passing in the event that occurred. Our main code sets up the event handlers on the inner box by calling
addEventListener() for each of the types mouseenter, mousemove, and mouseleave. HTML The HTML for our ...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
estAnimationFrame() a second time! This time, the callback is run before the next repaint, which is after the style recomputation has occurred. This callback adds the "changing" class back onto the box, so that the repaint will start the animation once again. Of course, we also need to add an event handler to our "Run" button so it'll actually do something: document.querySelector(".runButton").
addEventListener("click", play, false); Result Stopping an animation Simply removing the animation-name applied to an element will make it jump or cut to its next state. If instead you'd like the animation to complete and then come to a stop you have to try a different approach. The main tricks are: Make your animation as self-contained as possible. This means you should not rely on animation-direction: a...
...animation-iteration-count: infinite; } .stopped { animation-name: none; } @keyframes slidein { 0% { margin-left: 0%; } 50% { margin-left: 50%; } 100% { margin-left: 0%; } } <h1 id="watchme">Click me to stop</h1> let watchme = document.getElementById('watchme') watchme.className = 'slidein' const listener = (e) => { watchme.className = 'slidein stopped' } watchme.
addEventListener('click', () => watchme.
addEventListener('animationiteration', listener, false) ) Demo https://jsfiddle.net/morenoh149/5ty5a4oy/ ...
align-content - CSS: Cascading Style Sheets
Working Draft Adds the [ first | last...
... Working Draft Adds the [ first | last ]? baseline, start, end, left, right, unsafe | safe values. CSS Flexible Box Layout ModuleThe defi...
align-items - CSS: Cascading Style Sheets
Working Draft Update to latest syntax def...
... Working Draft Update to latest syntax definitions. CSS Flexible Box Layout ModuleThe definition of 'align-items' in that specification. ...
place-content - CSS: Cascading Style Sheets
"safe">safe</option> <option value="unsafe">unsafe</option> </select><code>;</code> var update = function () { document.getElementById("container").style.placeContent = document.getElementById("alignContentAlignment").value + " " + document.getElementById("justifyContentAlignment").value; } var alignContentAlignment = document.getElementById("alignContentAlignment"); alignContentAlignment.
addEventListener("change", update); var justifyContentAlignment = document.getElementById("justifyContentAlignment"); justifyContentAlignment.
addEventListener("change", update); var writingM = document.getElementById("writingMode"); writingM.
addEventListener("change", function (evt) { document.getElementById("container").style.writingMode = evt.target.value; }); var direction = document.getElementById("dire...
...; var justifyContentAlignment = document.getElementById("justifyContentAlignment"); justifyContentAlignment.
addEventListener("change", update); var writingM = document.getElementById("writingMode"); writingM.
addEventListener("change", function (evt) { document.getElementById("container").style.writingMode = evt.target.value; }); var direction = document.getElementById("direction"); direction.
addEventListener("change", function (evt) { document.getElementById("container").style.direction = evt.target.value; }); CSS #container { display: flex; height:240px; width: 240px; flex-wrap: wrap; background-color: #8c8c8c; writing-mode: horizontal-tb; /* Can be changed in the live sample */ direction: ltr; /* Can be changed in the live sample */ place-content: flex-end center; /* Can be c...
will-change - CSS: Cascading Style Sheets
ation typediscrete Formal syntax auto | <animateable-feature>#where <animateable-feature> = scroll-position | contents | <custom-ident> Examples Via script This is an example showing how to apply the will-change property through scripting, which is probably what you should be doing in most cases. ...
...teable-feature>#where <animateable-feature> = scroll-position | contents | <custom-ident> Examples Via script This is an example showing how to apply the will-change property through scripting, which is probably what you should be doing in most cases. ...
Adding captions and subtitles to HTML5 video - Developer guides
l) { var listItem = document.createElement('li'); var button = listItem.appendChild(document.createElement('button')); button.setAttribute('id', id); button.className = 'subtitles-button'; if (lang.length > 0) button.setAttribute('lang', lang); button.value = label; button.setAttribute('data-state', 'inactive'); button.appendChild(document.createTextNode(label)); button.
addEventListener('click', function(e) { // Set all buttons to inactive subtitleMenuButtons.map(function(v, i, a) { subtitleMenuButtons[i].setAttribute('data-state', 'inactive'); }); // Find the language to activate var lang = this.getAttribute('lang'); for (var i = 0; i < video.textTracks.length; i++) { // For the 'subtitles-off' button, the first condition wi...
...the button to toggle the relevant subtitle set on or off. This is done by simply setting the required subtlte's mode attribute to showing, and setting the others to hidden. Once the menu is built, it is then inserted into the DOM at the bottom of the videoContainer. ...
Mutation events - Developer guides
}, false); The event object is passed to the listener in a MutationEvent (see its definition in the specification) for most events, and MutationNameEvent for DOMAttributeNameChanged and DOMElementNameChanged. ...
...}, false); The event object is passed to the listener in a MutationEvent (see its definition in the specification) for most events, and MutationNameEvent for DOMAttributeNameChanged and DOMElementNameChanged. ...
Using device orientation with 3D transforms - Developer guides
e screen coordinate system is inverted, such that translateY(100px) moves an element 100px down, so the rotateY value should be -gamma Finally, the order of the three different rotations is very important to accurately convert an orientation to a 3D rotation: rotateZ, then rotateX and then rotateY. Here's a simple code snippet to sum it up: var elem = document.getElementById("view3d"); window.
addEventListener("deviceorientation", function(e) { // remember to use vendor-prefixed transform property elem.style.transform = "rotateZ(" + ( e.alpha - 180 ) + "deg) " + "rotateX(" + e.beta + "deg) " + "rotateY(" + ( -e.gamma ) + "deg)"; }); Orientation compensation Compensating the orientation of the device can be useful to create parallax effects or augmented reality. This is achieved by in...
...ateZ(" + ( e.alpha - 180 ) + "deg) " + "rotateX(" + e.beta + "deg) " + "rotateY(" + ( -e.gamma ) + "deg)"; }); Orientation compensation Compensating the orientation of the device can be useful to create parallax effects or augmented reality. ...
User input and controls - Developer guides
and apps, and locking them out of your functionality is a bad idea. The following is a set of recommendations and best practices for using such tools in Open Web Apps. Decide what input mechanism you're using Keyboard Keyboard input can be controlled by your app. For example if you want to add controls when any key gets pressed, you need to add an event listener on the window object: window.
addEventListener("keydown", handleKeyDown, true); window.
addEventListener("keyup", handleKeyUp, true); where handleKeyDown and handleKeyUp are the functions implementing the controls about the keydown and keyup events. Note: Have a look at the Events reference and KeyboardEvent guide to find out more about keyboard events. Mouse The events occurring when the user interacts with a pointing device such as a m...
...en devices, it's a good practice to take into consideration the different capabilities in terms of screen resolution and user input. Touch events can help you implement interactive elements and common interaction gestures on touchscreen devices. If you want to use touch events, you need to add event listeners and specify handler functions, which will be called when the event gets fired: element.
addEventListener("touchstart", handleStart, false);? element.
addEventListener("touchcancel", handleCancel, false);? element.
addEventListener("touchend", handleEnd, false);? element.
addEventListener("touchmove", handleMove, false); where element is the DOM element you want to register the touch events on. Note: For further information about what you can do with touch events, please read our touch events guide. ...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
> </menu> <output aria-live="polite"></output> JavaScript var updateButton = document.getElementById('updateDetails'); var favDialog = document.getElementById('favDialog'); var outputBox = document.querySelector('output'); var selectEl = document.querySelector('select'); var confirmBtn = document.getElementById('confirmBtn'); // "Update details" button opens the <dialog> modally updateButton.
addEventListener('click', function onOpen() { if (typeof favDialog.showModal === "function") { favDialog.showModal(); } else { alert("The <dialog> API is not supported by this browser"); } }); // "Favorite animal" input sets the value of the submit button selectEl.
addEventListener('change', function onSelect(e) { confirmBtn.value = selectEl.value; }); // "Confirm" button of form triggers "close" o...
... Living Standard HTML 5.2The definition of '<dialog>' in that specification. Recommendation Init...
this - JavaScript
d. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead because it gets executed, but it can be eliminated with no outside effects.) As a DOM event handler When a function is used as an event handler, its this is set to the element on which the listener is placed (some browsers do not follow this convention for listeners added dynamically with methods other than
addEventListener()). // When called as a listener, turns the related element blue function bluify(e) { // Always true console.log(this === e.currentTarget); // true when currentTarget and target are the same object console.log(this === e.target); this.style.backgroundColor = '#A5D9F3'; } // Get a list of every element in the document var elements = document.getElementsByTagName('*'); // Add bluify as...
...Note however that only the outer code has its this set this way: <button onclick="alert((function() { return...
Add to Home screen - Progressive web apps (PWAs)
y: none initially: let deferredPrompt; const addBtn = document.querySelector('.add-button'); addBtn.style.display = 'none'; We hide the button initially because the PWA will not be available for install until it follows the A2HS criteria. When this happens, supporting browsers will fire a beforeinstallprompt event. ...
...an then use a handler like the one below to handle the installation: window.
addEventListener('beforeinstallprompt', (e) => { // Prevent Chrome 67 and earlier from automatically showing the prompt e.preventDefault(); // Stash the event so it can be triggered later. ...
Progressive web app structure - Progressive web apps (PWAs)
'http:///\'></a>','-'); content += entry; }; document.getElementById('content').innerHTML = content; Next, it registers a service worker: if('serviceWorker' in navigator) { navigator.serviceWorker.register('/pwa-examples/js13kpwa/sw.js'); }; The next code block requests permission for notifications when a button is clicked: var button = document.getElementById("notifications"); button.
addEventListener('click', function(e) { Notification.requestPermission().then(function(result) { if(result === 'granted') { randomNotification(); } }); }); The last block creates notifications that display a randomly-selected item from the games list: function randomNotification() { var randomItem = Math.floor(Math.random()*games.length); var notifTitle = games[random...
...on-192.png', '/pwa-examples/js13kpwa/icons/icon-256.png', '/pwa-examples/js13kpwa/icons/icon-512.png' ]; var gamesImages = []; for(var i=0; i<games.length; i++) { gamesImages.push('data/img/'+games[i].slug+'.jpg'); } var contentToCache = appShellFiles.concat(gamesImages); The next block installs the service worker, which then actually caches all the files contained in the above list: self.
addEventListener('install', function(e) { console.log('[Service Worker] Install'); e.waitUntil( caches.open(cacheName).then(function(cache) { console.log('[Service Worker] Caching all: app shell and content'); return cache.addAll(contentToCache); }) ); }); Last of all, the service worker fetches content from the cache if it is available there, providing offline functionality: self.addE...
Communicating using "port" - Archive of obsolete content
irectly: instead, each time a content script is attached to a page, the worker associated with the page is supplied to the page-mod in its onAttach function. By supplying a target for this function in the page-mod's constructor you can register to receive messages from the content script, and take a reference to the worker so as to emit messages to the content script. ...
Porting the Library Detector - Archive of obsolete content
d two additional content scripts: one in the widget's context, which listens for icon mouseover events and sends a message to main.js containing the name of the corresponding library: function setLibraryInfo(element) { self.port.emit('setLibraryInfo', element.target.title); } var elements = document.getElementsByTagName('img'); for (var i = 0; i < elements.length; i++) { elements[i].
addEventListener('mouseover', setLibraryInfo, false); } one in the panel, which updates the panel's content with the library information: self.on("message", function(libraryInfo) { window.document.body.innerHTML = libraryInfo; }); Finally main.js relays the library information from the widget to the panel: widget.port.on('setLibraryInfo', function(libraryInfo) { widget.panel.postMessage(libraryInfo);...
frame/hidden-frame - Archive of obsolete content
rs a frame, unloading any content that was loaded in it. The following code creates a hidden frame, loads a web page into it, and then logs its title: var hiddenFrames = require("sdk/frame/hidden-frame"); let hiddenFrame = hiddenFrames.add(hiddenFrames.HiddenFrame({ onReady: function() { this.element.contentWindow.location = "http://www.mozilla.org/"; let self = this; this.element.
addEventListener("DOMContentLoaded", function() { console.log(self.element.contentDocument.title); }, true, true); } })); See the panel module for a real-world example of usage of this module. Globals Constructors HiddenFrame(options) Creates a hidden frame. Parameters options : object Required options: Name Type onReady function,array Functions to cal...
remote/parent - Archive of obsolete content
{ frame.content.location += "#" + ref; }); // main.js const { frames, remoteRequire } = require("sdk/remote/parent"); remoteRequire("./remote.js", module); frames.port.emit("changeLocation", "foo"); Tab information This shows sending a message when a tab loads; this is similar to how the sdk/tabs module currently works. ...
Implementing the widget - Archive of obsolete content
t script and its two icons. Inside the data subdirectory create another subdirectory widget. We'll keep the widget's files here. This hierarchy isn't mandatory; you could just keep them all under data. But it seems tidier this way. The widget's content script The widget's content script just listens for left- and right- mouse clicks and posts the corresponding message to the add-on code: this.
addEventListener('click', function(event) { if(event.button == 0 && event.shiftKey == false) self.port.emit('left-click'); if(event.button == 2 || (event.button == 0 && event.shiftKey == true)) self.port.emit('right-click'); event.preventDefault(); }, true); Save this in your data/widget directory as widget.js. The widget's icons You can copy the widget's icons from here: Or, if you're feel...
Display a Popup - Archive of obsolete content
mplementation we'll just log the text to the console. text_entry.port.on("text-entered", function (text) { console.log(text); text_entry.hide(); }); The content script "get-text.js" looks like this: // When the user hits return, send the "text-entered" // message to main.js. // The message payload is the contents of the edit box. var textArea = document.getElementById("edit-box"); textArea.
addEventListener('keyup', function onkeyup(event) { if (event.keyCode == 13) { // Remove the newline. text = textArea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textArea.value = ''; } }, false); // Listen for the "show" event being sent from the // main add-on code. It means that the panel's about // to be shown. // // Set the focus to the text area so the user c...
Canvas code snippets - Archive of obsolete content
pe.load = function() { var windowWidth = window.innerWidth - 25; var iframe; iframe = document.createElement('iframe'); iframe.id = 'test-iframe'; iframe.height = '10px'; iframe.width = windowWidth + 'px'; iframe.style.visibility = 'hidden'; iframe.src = this.url; // Here is where the magic happens... ...
ContextMenus - Archive of obsolete content
ce, so the event handler should check to make sure that the target of the contextmenu event is what is desired. To cancel a context menu event, you can use the preventDefault method of the event object. function checkContextMenu(event) { if (event.target.localName == "textbox") event.preventDefault(); } function init() { var container = document.getElementById("container"); container.
addEventListener("contextmenu", checkContextMenu, true); } The 'checkContextMenu' function checks to see if the textbox was the target of the context menu and, if so, cancels the event using the preventDefault method. This has the effect of disabling the context menu. The event listener is attached using the
addEventListener method within the 'init' function. This might be called while initializing a window dur...
Extensions - Archive of obsolete content
have added be shown or hidden based on the context, you can use an event handler that listens for the popupshowing event. For instance, if an image was context clicked, you may wish to hide the menu item you have added if the operation it performed wouldn't apply to images. function init() { var contextMenu = document.getElementById("contentAreaContextMenu"); if (contextMenu) contextMenu.
addEventListener("popupshowing", ThumbnailsShowHideItems, false); } function ThumbnailsShowHideItems(event) { var show = document.getElementById("thumbnail-show"); show.hidden = (document.popupNode.localName != "IMG"); } The init function should be called within the handler for the load event so that the popupshowing event handler is hooked up before it would be opened by the user. In this example, the Thu...
PopupKeys - Archive of obsolete content
. The menu key listener described above captures key events on the document. Thus, a key listener added to a <menupopup> will not receive any key events. Instead, you must add a capturing key listener to the document or window if you want to listen for keys pressed within a menu. Note that the last argument here is true to listen for events during the capturing phase of event propagation: window.
addEventListener("keypress", someAction, true); However, the default listener provides all the suitable responses to keys, so there shouldn't be a need to handle keys yourself. While a menu is open, the focus remains where it was before the menu was open. For example, focusing a textbox and opening the textbox's context menu keeps the focus within the textbox. However, the capturing listener ensures that no key ...
textbox (Toolkit autocomplete) - Archive of obsolete content
ets the value of the timeout attribute. type Type: string Set to the value autocomplete to have an autocomplete textbox. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
Textbox (XPFE autocomplete) - Archive of obsolete content
ts and sets the value of the type attribute. userAction Type: string Gets and sets the value of the userAction attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
ill not work. This is the code to create and add it in. let button = doc.createElement("toolbarbutton"); button.setAttribute("id", BUTTON_ID); button.setAttribute("label", "Replace Bookmark"); button.setAttribute("class", "toolbarbutton-1 chromeclass-toolbar-additional"); button.setAttribute("tooltiptext", "Replace an existing bookmark"); button.style.listStyleImage = "url(" + icon + ")"; button.
addEventListener("command", main.action, false); toolbox.palette.appendChild(button); This code is thanks to dgutov and is seen in full context at his repository here at GitHub: dgutov / bmreplace / bootstrap.js. Watch for a snippet that you can copy and paste into Scratchpad, and then run on Gists@GitHub here: _ff-addon-snippet-AddToolbarButtonToPalette.js . It is based on the code from the repo above. Here a...
XUL Questions and Answers - Archive of obsolete content
t updates preferences explicitly, via nsIPrefBranch interface. Can a XUL template be used for RSS? You should be able to use a XUL template to display feeds, although you may have to write the feed data to an RDF datasource first. Specifying window.onload function To specify a function to run when the window is loaded,add the following code between the script tags in the XUL file: window.
addEventListener("load", function(e) { startup(); }, false); Similarly, for onunload use the code: window.
addEventListener("unload", function(e) { shutdown(); }, false); Is there an event which is called when the Firefox browser is initialized? An event is initiated when the application starts up and when the profile is changed. For more information please look at the following link: nsExtensionManager.js ...
action - Archive of obsolete content
lign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
arrowscrollbox - Archive of obsolete content
scroll forward that many lines, or a negative value to scroll backward that many lines. scrollByPixels( pixels ) Return type: no return value Scrolls the contents of the arrowscrollbox by a certain number of pixels. Use a positive value as the pixels argument to scroll forward that many pixels, or a negative value to scroll backward that many pixels. ...
assign - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
bbox - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
binding - Archive of obsolete content
align, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
bindings - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
box - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
broadcaster - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
broadcasterset - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
browser - Archive of obsolete content
the document. Most of its methods are callable directly on the element itself, such as goBack and goForward. It also contains the load constants used by reloadWithFlags and loadURIWithFlags. webProgress Type: nsIWebProgress This read-only property contains an nsIWebProgress object which is used to monitor the progress of a document loading. ...
button - Archive of obsolete content
open Type: boolean Gets and sets the value of the open attribute. orient Type: string Gets and sets the value of the orient attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. type Type: string Gets and sets the value of the type attribute. ...
caption - Archive of obsolete content
crop Type: string Gets and sets the value of the crop attribute. image Type: image URL Gets and sets the value of the image attribute. label Type: string Gets and sets the value of the label attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
checkbox - Archive of obsolete content
attribute. disabled Type: boolean Gets and sets the value of the disabled attribute. src Type: URL Gets and sets the value of the src attribute. label Type: string Gets and sets the value of the label attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
colorpicker - Archive of obsolete content
Gets and sets the value of the disabled attribute. open Type: boolean Returns true if the popup for a button-type colorpicker is open. Set this property to true to open the popup or false to close the popup. tabIndex Type: integer Gets and sets the value of the tabindex attribute. ...
column - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
columns - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
command - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
commandset - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
conditions - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
content - Archive of obsolete content
r elements. uri Type: ? Used to specify the variable name for the content. When a rule is evaluated, it scans through each resource in the RDF datasource looking for a match. Each resource is placed in the variable specified in the uri attribute in turn. Then, the other rules are evaluated for a match. This attribute should always be present. ...
datepicker - Archive of obsolete content
e from 01 to 12. Set this property to change the selected date. year Type: integer The currently selected year from 1 to 9999. Set this property to change the selected year. yearLeadingZero Type: boolean A read only value indicating whether a leading zero should be displayed before the year when it is less than 1000. ...
deck - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
description - Archive of obsolete content
e of the disabled attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
dialog - Archive of obsolete content
th the buttonlabelextra2 attribute. defaultButton Type: string Normally this attribute should not be set, but if it is, it specifies the default button in the dialog. Typically, this means that the button will be activated when the Enter key is pressed. This should be set to one of the same values as those for the buttons attribute. ...
dialogheader - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
dropmarker - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
editor - Archive of obsolete content
gument. getHTMLEditor( window ) Return type: nsIHTMLEditor Returns the HTML editing interface for the editor which contains methods for manipulating an HTML document. Pass the editor's contentWindow as the argument. makeEditable( editortype, waitForLoad ) Return type: no return value This function enables editing for an editor. Specify text or html as the editortype. ...
grid - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
grippy - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
groupbox - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
hbox - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
iframe - Archive of obsolete content
contains the nsIDocShell object for the document. webNavigation Type: nsIWebNavigation This read-only property contains the nsIWebNavigation object for the document. Most of its methods are callable directly on the element itself, such as goBack and goForward. It also contains the load constants used by reloadWithFlags and loadURIWithFlags. ...
image - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
key - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
keyset - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
label - Archive of obsolete content
value of the crop attribute. disabled Type: boolean Gets and sets the value of the disabled attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
listbox - Archive of obsolete content
the suppressonselect attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
listcell - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
listcol - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
listcols - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
listhead - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
listheader - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
listitem - Archive of obsolete content
eparator elements in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
member - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
menu - Archive of obsolete content
false if it is not. This property is read only. This property is available for menuitem and menuseparator elements in Firefox 3. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
menubar - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
menuitem - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
menulist - Archive of obsolete content
operty, or changed by the user. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
menupopup - Archive of obsolete content
t has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. triggerNode Type: nsIDOMNode This read-only property holds the DOM node that generated the event triggering the opening of the popup. The value is null if the popup isn't open. ...
menuseparator - Archive of obsolete content
arator elements in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
notification - Archive of obsolete content
the value of the priority attribute. type Type: string Gets and sets the value of the type attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
notificationbox - Archive of obsolete content
allNotifications Type: nodeList NodeList of all notifications. This property is read-only. notificationsHidden Type: boolean Indicating whether the notification area should be hidden. Events AlertActive Type: Event Fired when a notification element is shown. AlertClose Type: Event Fired when a notification element is closed. ...
observes - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
page - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
panel - Archive of obsolete content
ossible: closed: The popup is closed and not visible. open: The popup is open and visible on screen. showing: A request has been made to open the popup, but it has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. ...
param - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
popupset - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
preference - Archive of obsolete content
alls onsynctopreference. boolean isElementEditable(in DOMElement element) Returns true, if the given element is "editable" (see below). void setElementValue(in DOMElement element); Initializes the supplied element from the value stored in the preference. This function calls onsyncfrompreference. void updateElements(); Update all elements that observe this preference. ...
preferences - Archive of obsolete content
changed (non-bubbling) event to the specified preference element. Also executes code specified in onchanged attribute of the element. See also the description of change event of <preference>. void observe(in nsISupports aSubject, in string aTopic, in wstring aData); nsIObserver method used internally to react to changes to preferences listed as children of this element. ...
prefpane - Archive of obsolete content
ist in a way that should cause the preference's value to change. (1) an example of a widget that has state changes tracked for it includes the checkbox element, whose state is tracked automatically when the "command" event fires. void writePreferences(in boolean flushToDisk); Writes all changes in this pane to preferences, optionally flushes to disk. ...
prefwindow - Archive of obsolete content
s valid to do that.) lastSelected Type: string Set this to the id of the last selected pane. It will be opened by default the next time the preferences dialog is opened. preferencePanes Type: DOM NodeList Holds a list of all the prefpane elements in the window. type Type: string Gets and sets the value of the type attribute. ...
progressmeter - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
query - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
queryset - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
radio - Archive of obsolete content
arator elements in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
radiogroup - Archive of obsolete content
erty, or changed by the user. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
resizer - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
richlistbox - Archive of obsolete content
e suppressonselect attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
richlistitem - Archive of obsolete content
arator elements in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
row - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
rows - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
rule - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
scale - Archive of obsolete content
the pageincrement attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
script - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
scrollbar - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
scrollbox - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
scrollcorner - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
separator - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
spacer - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
spinbuttons - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
splitter - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
stack - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
statusbar - Archive of obsolete content
align, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
<statusbarpanel> - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
stringbundle - Archive of obsolete content
supplied array. Alternatively, numbered indices of the format %n$S (e.g. %1$S, %2$S, etc.) can be used to specify the position of the corresponding parameter explicitly. If you need to handle substitutions involving plurals, take a look at Localization and Plurals. getString( key ) Return type: string Returns the string with the given key name from the string bundle. ...
stringbundleset - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
tab - Archive of obsolete content
arator elements in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
tabbox - Archive of obsolete content
Type: tab element A reference to the currently selected tab, which will always be one of the tab elements in the tabs element. Assign a value to this property to modify the currently selected tab. tabs Type: tabs element The tabs element contained within the tabbox. tabpanels Type: tabpanels element The tabpanels element contained within the tabbox. ...
tabbrowser - Archive of obsolete content
the document. Most of its methods are callable directly on the element itself, such as goBack and goForward. It also contains the load constants used by reloadWithFlags and loadURIWithFlags. webProgress Type: nsIWebProgress This read-only property contains an nsIWebProgress object which is used to monitor the progress of a document loading. ...
tabpanel - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
tabpanels - Archive of obsolete content
index to this property. By assigning -1 to this property, all items will be deselected. Returns -1 if no items are selected selectedPanel Type: element Holds a reference to the currently selected panel within a <tabbox> element. Assigning a value to this property will modify the selected panel. A select event will be sent when the selected panel is changed. ...
tabs - Archive of obsolete content
ement that contains the tabs. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the contents, as visible to the user, are read and set using the Textbox.value and Menulist.value syntax. ...
template - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
textbox - Archive of obsolete content
setSelectionRange( start, end ) Return type: no return value Sets the selected portion of the textbox, where the start argument is the index of the first character to select and the end argument is the index of the character after the selection. Set both arguments to the same value to move the cursor to the corresponding position without selecting text. ...
textnode - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
timepicker - Archive of obsolete content
Type: boolean A read only value indicating whether a leading zero should be displayed before the second when it is less than 10. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string The currently entered time of the form HH:MM:SS. Set this property to change the time. ...
titlebar - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
toolbar - Archive of obsolete content
it is mainly for the use of the customize dialog. The id should match an element in the toolbar's toolbarpalette. Some special ids may also be used to create special spacing items: separator: A separator, which is drawn as a vertical bar. spacer: A non-flexible space. spring: A flexible space. The method returns the DOM element for the created item. ...
toolbarbutton - Archive of obsolete content
open Type: boolean Gets and sets the value of the open attribute. orient Type: string Gets and sets the value of the orient attribute. tabIndex Type: integer Gets and sets the value of the tabindex attribute. type Type: string Gets and sets the value of the type attribute. ...
toolbargrippy - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
toolbaritem - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
toolbarpalette - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
toolbarseparator - Archive of obsolete content
align, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
toolbarset - Archive of obsolete content
align, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
toolbarspacer - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
toolbarspring - Archive of obsolete content
align, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
toolbox - Archive of obsolete content
lToolbars Type: array of elements An array of external toolbars; that is, toolbar elements that should be considered to be members of this toolbox, even if they are not actually children of the toolbox. palette Firefox only Type: element The toolbarpalette within the toolbox. toolbarset Firefox only Type: element The toolbarset within the toolbox. ...
tooltip - Archive of obsolete content
possible: closed: The popup is closed and not visible. open: The popup is open and visible on screen. showing: A request has been made to open the popup, but it has not yet been shown. This state will occur during the popupshowing event. hiding: The popup is about to be hidden. This state will occur during the popuphiding event. ...
tree - Archive of obsolete content
played. You can assign an object which implements nsITreeView to this property. Trees built from RDF or those which use treeitems directly will already have a view. Functions available in the view allow one to retrieve the data within the cells, and determine which rows are nested within others. For a complete list of view functions, see the nsITreeView interface. ...
treecell - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
treechildren - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
treecol - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
treecols - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
treeitem - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
treerow - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
treeseparator - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
triple - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
vbox - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
where - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
window - Archive of obsolete content
ign, , allowEvents, , boxObject, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
wizard - Archive of obsolete content
rent than pageIndex, because pages are not necessarily navigated in order. title Type: string The title that appears at the top of the wizard. This is overridden by the label attribute on the individual pages. wizardPages Type: DOM NodeList of wizardpage elements This property holds the list of wizardpage elements in the wizard. ...
wizardpage - Archive of obsolete content
Object, builder, , , , className, , , , , collapsed, contextMenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxHeight, maxWidth, menu, minHeight, minWidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width Methods Inherited Methods
addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEvent(), doCommand, focus, getAttribute(), getAttributeNode(), getAttributeNodeNS(), getAttributeNS(), getBoundingClientRect(), getClientRects(), getElementsByAttribute, getElementsByAttributeNS, getElementsByClassName(), getElementsByTagName(), getElementsByTagNameNS(), getFeature, getUserData, hasAttribute(), hasAttrib...
Building XULRunner with Python - Archive of obsolete content
ptions.showInConsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); HTML <script> tags specify that Python is used withtype="application/x-python" attribute. DOM scripting is pretty much as with Java Script. For example def onLoad(): btnTest = document.getElementById("btnTest") btnTest.
addEventListener('command', onTest, False) def onTest(): window.alert('Button activated') window.
addEventListener('load', onLoad, False) One possible gotcha is that the default python path used to find modules that areimported explicitly includes the xulrunner executable directory and the directory that is current when XULRunner launches. However it does not include any path related to the XUL application...
MacFAQ - Archive of obsolete content
uments[0] .QueryInterface(Components.interfaces.nsICommandLine); for (var i = 0; i < cmdLine.length; ++i) { debug(cmdLine.getArgument(i)) } } catch(ex) { debug(window.arguments[0]) // Do something with window.arguments[0] //nsPreferences.setUnicharPref("myXUL.cmdLineValue", window.arguments[0]) } window.
addEventListener("load", checkOtherWindows , false); } ]]></script> </window> ...
Scratchpad - Archive of obsolete content
box, as shown below: The icon next to each suggestion indicates the type, and the currently highlighted suggestion gets a popup with more information. ? and ? cycle through the suggestions and Enter or Tab select the highlighted choice. Inline documentation To show the inline documentation popup, press Ctrl + Shift + Space when the cursor is on an identifier. For example, if you type document.
addEventListener, then press Ctrl + Shift + Space, you'll see a popup that shows a summary of the function's syntax and a short description: The "[docs]" link takes you to the MDN documentation for the symbol. Executing Once you've written your code, select the code you want to run. If you don't select anything, all the code in the window will be run. Then choose the way you want the code to run using the butt...
-ms-filter - Archive of obsolete content
filterFrom.filters.item(0).Transition=12; imageFrom.style.visibility = "hidden"; filterTo.style.visibility = ""; filterFrom.filters.item(0).play(14); } </script> </body> Gradient progid:DXImageTransform.Microsoft.Gradient( <properties> ) where <properties> = [...
HTMLVideoElement.videoHeight - Web APIs
AVE_NOTHING, a resize event will be sent to the <video> element. This can happen when the element switches from displaying the poster frame to displaying video content, or when the displayed video track changes. Example This example creates a handler for the resize event that resizes the <video> element to match the intrinsic size of its contents. let v = document.getElementById("myVideo"); v.
addEventListener("resize", ev => { let w = v.videoWidth; let h = v.videoHeight; if (w && h) { v.style.width = w; v.style.height = h; } }, false); Note that this only applies the change if both the videoWidth and the videoHeight are non-zero. This avoids applying invalid changes when there's no true information available yet for dimensions. Specifications Specification Status Co...
HTMLVideoElement.videoWidth - Web APIs
AVE_NOTHING, a resize event will be sent to the <video> element. This can happen when the element switches from displaying the poster frame to displaying video content, or when the displayed video track changes. Example This example creates a handler for the resize event that resizes the <video> element to match the intrinsic size of its contents. let v = document.getElementById("myVideo"); v.
addEventListener("resize", ev => { let w = v.videoWidth; let h = v.videoHeight; if (w && h) { v.style.width = w; v.style.height = h; } }, false); Note that this only applies the change if both the videoWidth and the videoHeight are non-zero. This avoids applying invalid changes when there's no true information available yet for dimensions. Specifications Specification Status Co...
HTMLVideoElement - Web APIs
ancestor HTMLElement. HTMLVideoElement.getVideoPlaybackQuality() Returns a VideoPlaybackQuality object that contains the current playback metrics. This information includes things like the number of dropped or corrupted frames, as well as the total number of frames. Events Inherits methods from its parent, HTMLMediaElement, and from its ancestor HTMLElement. Listen to these events using
addEventListener() or by assigning an event listener to the oneventname property of this interface. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLVideoElement' in that specification. Living Standard ...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
[url] = data; this.data = data; this.dispatchEvent(new Event("load")); }); } }; The problem introduced here is that by using a task in one branch of the if...else statement (in the case in which the image is available in the cache) but having promises involved in the else clause, we have a situation in which the order of operations can vary; for example, as seen below. element.
addEventListener("load", () => console.log("Loaded data")); console.log("Fetching data..."); element.getData(); console.log("Data fetched"); Executing this code twice in a row gives the results shown in the table below: Results when data isn't cached (left) vs. when it is found in the cache Data isn't cached Data is cached Fetching data Data fetched Loaded data Fetch...
HashChangeEvent.newURL - Web APIs
The newURL read-only property of the HashChangeEvent interface returns the new URL to which the window is navigating. Syntax let newEventUrl = event.newURL; Value A DOMString. Example window.
addEventListener('hashchange', function(event) { console.log('Hash changed to ' + event.newURL); }); Specifications Specification Status Comment HTML Living StandardThe definition of 'HashChangeEvent: newURL' in that specification. Living Standard ...
HashChangeEvent.oldURL - Web APIs
The oldURL read-only property of the HashChangeEvent interface returns the previous URL from which the window was navigated. Syntax let oldEventUrl = event.oldURL; Value A DOMString. Example window.
addEventListener('hashchange', function(event) { console.log('Hash changed from ' + event.oldURL); }); Specifications Specification Status Comment HTML Living StandardThe definition of 'HashChangeEvent: oldURL' in that specification. Living Standard ...
HashChangeEvent - Web APIs
ng. HashChangeEvent.oldURL Read only The previous URL from which the window was navigated. Methods This interface has no methods of its own, but inherits the methods of its parent, Event. Examples Syntax options for a hash change You can listen for the hashchange event using any of the following options: window.onhashchange = funcRef; or <body onhashchange="funcRef();"> or window.
addEventListener("hashchange", funcRef, false); Basic example function locationHashChanged() { if (location.hash === '#somecoolfeature') { somecoolfeature(); } } window.
addEventListener('hashchange', locationHashChanged); Polyfill There are several fallback scripts listed on the Modernizr GitHub page. Basically, those scripts check the location.hash at a regular interval. Here is a version that ...
History.back() - Web APIs
s page, this method call does nothing. This method is asynchronous. Add a listener for the popstate event in order to determine when the navigation has completed. Syntax history.back() Examples The following short example causes a button on the page to navigate back one entry in the session history. HTML <button id="go-back">Go back!</button> JavaScript document.getElementById('go-back').
addEventListener('click', () => { history.back(); }); Specifications Specification Status Comment HTML Living StandardThe definition of 'History.back()' in that specification. Living Standard No change from HTML5. HTML5The definition of 'History.back()' in that specification. Recommendation Initial definition. Browser Compatibility The compatibility table o...
History.forward() - Web APIs
the same effect as calling history.go(1). This method is asynchronous. Add a listener for the popstate event in order to determine when the navigation has completed. Syntax history.forward() Examples The following examples create a button that moves forward one step in the session history. HTML <button id='go-forward'>Go Forward!</button> JavaScript document.getElementById('go-forward').
addEventListener('click', e => { window.history.forward(); }) Specifications Specification Status Comment HTML Living StandardThe definition of 'History' in that specification. Living Standard No change from HTML5. HTML5The definition of 'History' in that specification. Recommendation Initial definition. Browser Compatibility The compatibility table on this...
IDBDatabase: abort event - Web APIs
objectStore.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const db = dBOpenRequest.result; db.
addEventListener('abort', () => { console.log('Transaction aborted'); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); // abort the transaction transaction.abort(); }; The same example, but assigning the event handler to the onabort property: // Open the database const dBOpenRequest = window.indexedDB.open('toDoLis...
IDBDatabase: close event - Web APIs
objectStore.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const db = dBOpenRequest.result; db.
addEventListener('close', () => { console.log('Database connection closed'); }); }; The same example, using the onclose property instead of
addEventListener(): // Open the database const dBOpenRequest = window.indexedDB.open('toDoList', 4); dBOpenRequest.onupgradeneeded = (event) => { const db = event.target.result; // Create an objectStore for this database const objectStore = db.createObjectSt...
IDBDatabase: error event - Web APIs
', { unique: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.onsuccess = (event) => { const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2020 }; const db = dBOpenRequest.result; db.
addEventListener('error', () => { console.log(`Error adding new item: ${newItem.taskTitle}`); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['toDoList'], 'readwrite'); const objectStore = transaction.objectStore('toDoList'); const objectStoreRequest = objectStore.add(newItem); }; The same example, using the onerror property instead of addEve...
IDBDatabase: versionchange event - Web APIs
' }); // define what data items the objectStore will contain objectStore.createIndex('hours', 'hours', { unique: false }); objectStore.createIndex('minutes', 'minutes', { unique: false }); objectStore.createIndex('day', 'day', { unique: false }); objectStore.createIndex('month', 'month', { unique: false }); objectStore.createIndex('year', 'year', { unique: false }); }; dBOpenRequest.
addEventListener('success', event => { const db = event.target.result; db.
addEventListener('versionchange', event => { console.log('The version of this database has changed'); }); }); The same example, using the onversionchange event handler property: // Open the database const dBOpenRequest = window.indexedDB.open('Nonexistent', 4); dBOpenRequest.onupgradeneeded = event => { const db = event.targ...
IDBDatabase - Web APIs
. IDBDatabase.deleteObjectStore() Destroys the object store with the given name in the connected database, along with any indexes that reference it. IDBDatabase.transaction() Immediately returns a transaction object (IDBTransaction) containing the IDBTransaction.objectStore method, which you can use to access your object store. Runs in a separate thread. Events Listen to these events using
addEventListener() or by assigning an event listener to the oneventname property of this interface. abort Fired when when a transaction is aborted and bubbles up to the connection object. Also available via the onabort property. close Fired when the database connection is unexpectedly closed. Also available via the onclose property. error Fired when a request returns an error and the event bubbles up to t...
IDBOpenDBRequest: upgradeneeded event - Web APIs
ersion number higher than its current version. Bubbles No Cancelable No Interface Event Event handler onupgradeneeded Examples This example opens a database and handles the upgradeneeded event by making any necessary updates to the object store. ...
Notifications API - Web APIs
epts and usage On supported platforms, showing a system notification generally involves two things. First, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initialises, using the Notification.requestPermission() method. This should be done in response to a user gesture, such as clicking a button, for example: btn.
addEventListener('click', function() { let promise = Notification.requestPermission(); // wait for permission }) This is not only best practice -- you should not be spamming users with notifications they didn't agree to -- but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example. This will spawn ...
OfflineAudioContext: complete event - Web APIs
lable No Default action None Interface OfflineAudioCompletionEvent Event handler property OfflineAudioContext.oncomplete Examples When processing is complete, you might want to use the oncomplete handler the prompt the user that the audio can now be played, and enable the play button: let offlineAudioCtx = new OfflineAudioContext(); offlineAudioCtx.
addEventListener('complete', () => { console.log('Offline audio processing now complete'); showModalDialog('Song processed and ready to play'); playBtn.disabled = false; }) You can also set up the event handler using the OfflineAudioContext.oncomplete property: let offlineAudioCtx = new OfflineAudioContext(); offlineAudioCtx.oncomplete = function() { console.log('Offline audio processing now complete')...
OfflineAudioContext - Web APIs
Deprecated methods OfflineAudioContext.resume() Resumes the progression of time in an audio context that has previously been suspended. Note: The resume() method is still available -- it is now defined on the BaseAudioContext interface (see BaseAudioContext.resume()) and thus can be accessed by both the AudioContext and OfflineAudioContext interfaces. Events Listen to these events using
addEventListener() or by assigning an event listener to the oneventname property of this interface: complete Fired when the rendering of an offline audio context is complete. Also available using the oncomplete event handler property. Examples In this simple example, we declare both an AudioContext and an OfflineAudioContext object. We use the AudioContext to load an audio track via XHR (AudioContext.deco...
PageTransitionEvent.persisted - Web APIs
The persisted read-only property indicates if a webpage is loading from a cache. Syntax window.
addEventListener('pageshow', function(event) { if (event.persisted) { console.log('Page was loaded from cache.'); } }); Value A Boolean. Specifications Specification Status Comment HTML Living StandardThe definition of 'PageTransitionEvent: persisted' in that specification. Living Standard Initial definition ...
PageTransitionEvent - Web APIs
or="middle" alignment-baseline="middle">PageTransitionEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface also inherits properties from its parent, Event. PageTransitionEvent.persisted Read only Indicates if the document is loading from a cache. Example HTML <!DOCTYPE html> <html> <body> </body> </html> JavaScript window.
addEventListener('pageshow', myFunction); function myFunction(event) { if (event.persisted) { alert("The page was cached by the browser"); } else { alert("The page was NOT cached by the browser"); } } Specifications Specification Status Comment HTML Living StandardThe definition of 'PageTransitionEvent' in that specification. Living Standard Initial definition ...
PaymentRequest: merchantvalidation event - Web APIs
an event handler is established for the merchantvalidation event. It uses the fetch() to send a request to its own server with an argument of the payment method's validation URL, obtained from the event's validationURL property. The merchant server should access the validation URL in accordance with the payment method documention. Typically, a client should not access the validation URL. ...
PaymentRequest.onpaymentmethodchange - Web APIs
onpaymentmethodchange is invoked when the paymentmethodchange is fired, indicating that the user has changed payment methods within a given payment handler. For example, when using Apple Pay, the user can swipe to select different credit cards, debit cards, and so forth. Each time the user does so, this event is fired. This event may not be fired by all payment handlers. Syntax PaymentRequest.
addEventListener('paymentmethodchange', paymentMethodChangeEvent => { ... }); PaymentRequest.onpaymentmethodchange = function(paymentMethodChangeEvent) { ... }; Value An event handler function which is to be called whenever the paymentmethodchange event is fired at the PaymentRequest, indicating that the user has changed payment methods within the same payment handler. The paymentmethodchange event is trigger...
PaymentRequest.shippingAddress - Web APIs
e cost of shipping varies by geography. When the PaymentRequest.onshippingaddresschange is called, updateDetails() is called to update the details of the PaymentRequest, using shippingAddress to set the correct shipping cost. // Initialization of PaymentRequest arguments are excerpted for the sake of // brevity. var payment = new PaymentRequest(supportedInstruments, details, options); payment.
addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { updateDetails(details, request.shippingAddress, resolve); })); }); payment.show().then(function(paymentResponse) { // Processing of paymentResponse exerpted for brevity. }).catch(function(err) { console.error("Uh oh, something bad happened", err.message); }); function updateDetails(details, s...
PaymentRequest: shippingaddresschange event - Web APIs
ly in order to prevent identifying the user without their consent (since if they choose to have you ship products to them, you'll need their address). Example In this example, a handler for the shippingaddresschange event is set up to validate that the address meets requirements set by the web application. const paymentRequest = new PaymentRequest(methodData, details, options); paymentRequest.
addEventListener("shippingaddresschange", event => { let detailsUpdate = checkAddress(paymentRequest.shippingAddress); event.updateWith(detailsUpate); }, false); const checkAddress = theAddress => { let detailsUpdate = {}; // Check the address, return a PaymentDetailsUpdate object // with any changes or errors. return detailsUpdate; }; You can also establish a handler for shippingaddresschange us...
PaymentRequest: shippingoptionchange event - Web APIs
a handler for the shippingoptionchange event. The code recalculates the total charge for the payment based on the selected shipping option. For example, if there are three options (such as "Free ground shipping", "2-day air", and "Next day"), each time the user chooses one of those options, this event handler is called to recalculate the total based on the changed shipping option. paymentRequest.
addEventListener("shippingoptionchange", event => { const value = calculateNewTotal(paymentRequest.shippingOption); const total = { currency: "EUR", label: "Total due", value, }; event.updateWith({ total }); }, false); After caling a custom function, calculateNewTotal(), to compute the updated total based on the newly-selected shipping option as specified by the shippingOption. The revised t...
PaymentResponse.retry() - Web APIs
romise = fixField(response, "payerdetailchange", payerValidator); promisesToFixThings.push(promise); } await Promise.all([response.retry(errors), ...promisesToFixThings]); await recursiveValidate(request, response); } function fixField(requestOrResponse, event, validator) { return new Promise(resolve => { // Browser keeps calling this until promise resolves. ...
PaymentResponse.shippingAddress - Web APIs
xample below, the cost of shipping varies by geography. When the PaymentRequest.onshippingaddresschange is called, updateDetails() is called to update the details of the PaymentRequest, using shippingAddress to set the correct shipping cost. // Initialization of PaymentRequest arguments are excerpted for brevity. var payment = new PaymentRequest(supportedInstruments, details, options); request.
addEventListener('shippingaddresschange', function(evt) { evt.updateWith(new Promise(function(resolve) { updateDetails(details, request.shippingAddress, resolve); })); }); payment.show().then(function(paymentResponse) { // Processing of paymentResponse exerpted for the same of brevity. }).catch(function(err) { console.error("Uh oh, something bad happened", err.message); }); function updateDetails(de...
PaymentResponse.shippingOption - Web APIs
Syntax var shippingOption = PaymentRequest.shippingOption; Example In the example below, the PaymentRequest.onshippingaoptionchange event is called. It calls updateDetails() to toggle the shipping method between "standard" and "express". // Initialization of PaymentRequest arguments are excerpted for brevity. var payment = new PaymentRequest(supportedInstruments, details, options); request.
addEventListener('shippingoptionchange', function(evt) { evt.updateWith(new Promise(function(resolve, reject) { updateDetails(details, request.shippingOption, resolve, reject); })); }); payment.show().then(function(paymentResponse) { // Processing of paymentResponse exerpted for the same of brevity. }).catch(function(err) { console.error("Uh oh, something bad happened", err.message); }); function up...
PaymentResponse - Web APIs
ignal to the user exactly what is wrong with the payment response so they can try to correct any issues. PaymentResponse.complete() Secure context Notifies the user agent that the user interaction is over. This causes any remaining user interface to be closed. This method should only be called after the Promise returned by the PaymentRequest.show() method. Events Listen to this event using
addEventListener() or by assigning an event listener to the oneventname property of this interface. payerdetailchange Secure context Fired during a retry when the user makes changes to their personal information while filling out a payment request form. Allows the developer to revalidate any requested user data (e.g., the phone number or the email address) if it changes. Also available via the onpayerdetailc...
Performance: resourcetimingbufferfull event - Web APIs
ion on the onresourcetimingbufferfull property. function buffer_full(event) { console.log("WARNING: Resource Timing Buffer is FULL!"); performance.setResourceTimingBufferSize(200); } function init() { // Set a callback if the resource buffer becomes filled performance.onresourcetimingbufferfull = buffer_full; } <body onload="init()"> Note that you could also set up the handler using the
addEventListener() function: performance.
addEventListener('resourcetimingbufferfull', buffer_full); Specifications Specification Status Comment Resource Timing Level 1The definition of 'onresourcetimingbufferfull' in that specification. Candidate Recommendation Initial definition. ...
TextTrackList: removeTrack event - Web APIs
The removetrack event is fired when a track is removed from a TextTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onremovetrack Examples Using
addEventListener(): const mediaElement = document.querySelector('video, audio'); mediaElement.textTracks.
addEventListener('removetrack', (event) => { console.log(`Text track: ${event.track.label} removed`); }); Using the onremovetrack event handler property: const mediaElement = document.querySelector('video, audio'); mediaElement.textTracks.onremovetrack = (event) => { console.log(`Text track: ${event.track.label} removed`); }; Specifications Specification Status HTML Living StandardThe definition of 'removetrack' in that specification. Livi...
Touch.clientX - Web APIs
the element or out of the element and then releases contact with the surface. When the touchend event handler is invoked, the changes in the Touch.clientX and Touch.clientY coordinates, from the starting touch point to the ending touch point, are calculated. // Register touchstart and touchend listeners for element 'source' var src = document.getElementById("source"); var clientX, clientY; src.
addEventListener('touchstart', function(e) { // Cache the client X/Y coordinates clientX = e.touches[0].clientX; clientY = e.touches[0].clientY; }, false); src.
addEventListener('touchend', function(e) { var deltaX, deltaY; // Compute the change in X and Y coordinates. // The first touch point in the changedTouches // list is the touch point that was just removed from the surface. deltaX = e.chan...
Touch.clientY - Web APIs
the element or out of the element and then releases contact with the surface. When the touchend event handler is invoked, the changes in the Touch.clientX and Touch.clientY coordinates, from the starting touch point to the ending touch point, are calculated. // Register touchstart and touchend listeners for element 'source' var src = document.getElementById("source"); var clientX, clientY; src.
addEventListener('touchstart', function(e) { // Cache the client X/Y coordinates clientX = e.touches[0].clientX; clientY = e.touches[0].clientY; }, false); src.
addEventListener('touchend', function(e) { var deltaX, deltaY; // Compute the change in X and Y coordinates. // The first touch point in the changedTouches // list is the touch point that was just removed from the surface. deltaX = e.chan...
Touch.force - Web APIs
is a relative value of pressure applied, in the range 0.0 to 1.0, where 0.0 is no pressure, and 1.0 is the highest level of pressure the touch device is capable of sensing. In following code snippet, the touchstart event handler iterrates through the targetTouches list and logs the force value of each touch point but the code could invoke different processing depending on the value. someElement.
addEventListener('touchstart', function(e) { // Iterate through the list of touch points and log each touch // point's force. for (var i=0; i < e.targetTouches.length; i++) { // Add code to "switch" based on the force value. For example // minimum pressure vs. maximum pressure could result in // different handling of the user's input. console.log("targetTouches[" + i + "].force = " + ...
Touch.identifier - Web APIs
The Touch.identifier returns a value uniquely identifying this point of contact with the touch surface. This value remains consistent for every event involving this finger's (or stylus's) movement on the surface until it is lifted off the surface. Syntax touchItem.identifier; Return value A long that represents the unique ID of the Touch object. Example someElement.
addEventListener('touchmove', function(e) { // Iterate through the list of touch points that changed // since the last event and print each touch point's identifier. for (var i=0; i < e.changedTouches.length; i++) { console.log("changedTouches[" + i + "].identifier = " + e.changedTouches[i].identifier); } }, false); Specifications Specification Status Comment Touch Events - Level 2 Draft No c...
Touch.pageX - Web APIs
es one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface. When the touchmove event handler is invoked, each touch point's Touch.pageX and Touch.pageY coordinates are accessed via the event's TouchEvent.changedTouches list. // Register a touchmove listeners for the 'source' element var src = document.getElementById("source"); src.
addEventListener('touchmove', function(e) { // Iterate through the touch points that have moved and log each // of the pageX/Y coordinates. The unit of each coordinate is CSS pixels. var i; for (i=0; i < e.changedTouches.length; i++) { console.log("touchpoint[" + i + "].pageX = " + e.changedTouches[i].pageX); console.log("touchpoint[" + i + "].pageY = " + e.changedTouches[i].pageY); } }, false);...
Touch.pageY - Web APIs
es one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface. When the touchmove event handler is invoked, each touch point's Touch.pageX and Touch.pageY coordinates are accessed via the event's TouchEvent.changedTouches list. // Register a touchmove listeners for the 'source' element var src = document.getElementById("source"); src.
addEventListener('touchmove', function(e) { // Iterate through the touch points that have moved and log each // of the pageX/Y coordinates. The unit of each coordinate is CSS pixels. var i; for (i=0; i < e.changedTouches.length; i++) { console.log("touchpoint[" + i + "].pageX = " + e.changedTouches[i].pageX); console.log("touchpoint[" + i + "].pageY = " + e.changedTouches[i].pageY); } }, false);...
Touch.radiusX - Web APIs
he following simple code snippet, registers a single handler for the touchstart, touchmove and touchend events. When the src element is touched, the element's width and height will be calculate based on the touch point's radiusX and radiusY values and the element will then be rotated using the touch point's rotationAngle. <div id="src"> ... </div> var src = document.getElementById("src"); src.
addEventListener('touchstart', rotate); src.
addEventListener('touchmove', rotate); src.
addEventListener('touchend', rotate); function rotate (e) { var touch = e.changedTouches.item(0); // Turn off default event handling e.preventDefault(); // Rotate element 'src'. src.style.width = touch.radiusX * 2 + 'px'; src.style.height = touch.radiusY * 2 + 'px'; src.style.transform = "rotate(" + touch.rotat...
Touch.screenX - Web APIs
n following simple code snippet, we assume the user initiates multiple touch contacts on an element with an id of source and then releases contacts with the surface. When the touchstart event handler is invoked, each touch point's Touch.screenX and Touch.screenY coordinates are accessed. // Register a touchstart listeners for the 'source' element var src = document.getElementById("source"); src.
addEventListener('touchstart', function(e) { // Iterate through the touch points and log each screenX/Y coordinate. // The unit of each coordinate is CSS pixels. var i; for (i=0; i < e.touches.length; i++) { console.log("touchpoint[" + i + "].screenX = " + e.touches[i].screenX); console.log("touchpoint[" + i + "].screenY = " + e.touches[i].screenY); } }, false); Specifications Speci...
Touch.target - Web APIs
the surface. In following simple code snippet, we assume the user initiates one or more touch contacts on the source element. When the touchstart event handler for this element is invoked, each touch point's Touch.target property is accessed via the event's TouchEvent.targetTouches list. // Register a touchmove listener for the 'source' element var src = document.getElementById("source"); src.
addEventListener('touchstart', function(e) { // Iterate through the touch points that were activiated // for this element. for (var i=0; i < e.targetTouches.length; i++) { console.log("touchpoint[" + i + "].target = " + e.targetTouches[i].target); } }, false); Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. Touch E...
TouchEvent.altKey - Web APIs
Return value altEnabled true if the alt key is enabled for this event; and false if the alt is not enabled. Example This example illustrates how to access the TouchEvent key modifier properties: TouchEvent.altKey, TouchEvent.ctrlKey, TouchEvent.metaKey and TouchEvent.shiftKey. In following code snippet, the touchstart event handler logs the state of the event's modifier keys. someElement.
addEventListener('touchstart', function(e) { // Log the state of this event's modifier keys console.log("altKey = " + e.altKey); console.log("ctrlKey = " + e.ctrlKey); console.log("metaKey = " + e.metaKey); console.log("shiftKey = " + e.shiftKey); }, false); Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. Touch ...
TouchEvent.changedTouches - Web APIs
tes the TouchEvent object's TouchEvent.changedTouches property. The TouchEvent.changedTouches property is a TouchList object that contains one Touch object for each touch point which contributed to the event. In following code snippet, the touchmove event handler iterates through the changedTouches list and prints the identifier of each touch point that changed since the last event. someElement.
addEventListener('touchmove', function(e) { // Iterate through the list of touch points that changed // since the last event and print each touch point's identifier. for (var i=0; i < e.changedTouches.length; i++) { console.log("changedTouches[" + i + "].identifier = " + e.changedTouches[i].identifier); } }, false); Specifications Specification Status Comment Touch Eve...
TouchEvent.touches - Web APIs
hEvent.touches property is a TouchList object and containing a list of Touch objects for every point of contact currently touching the surface. In following code snippet, the touchstart event handler checks the length of the TouchEvent.touches list to determine the number of touch points that were activated and then invokes different handlers depending on the number of touch points. someElement.
addEventListener('touchstart', function(e) { // Invoke the appropriate handler depending on the // number of touch points. switch (e.touches.length) { case 1: handle_one_touch(e); break; case 2: handle_two_touches(e); break; case 3: handle_three_touches(e); break; default: console.log("Not supported"); break; } }, false); Specifications Specification Status Comme...
TouchEvent - Web APIs
An event of some kind occurred that canceled the touch; this might happen if a modal alert pops up during the interaction. The touch point has left the document window and moved into the browser's UI area, a plug-in, or other external content. The user has placed more touch points on the screen than can be supported, in which case the earliest Touch in the TouchList gets canceled. Using with
addEventListener() and preventDefault() It's important to note that in many cases, both touch and mouse events get sent (in order to let non-touch-specific code still interact with the user). If you use touch events, you should call preventDefault() to keep the mouse event from being sent as well. The exception to this is Chrome, starting with version 56 (desktop, Chrome for android, and android webview), where...
TouchList.item() - Web APIs
. The index is a number in the range of 0 to one less than the length of the TouchList. Return value touchPoint The requested Touch object from the TouchList. Returns null if the index is not less than the length of the list. Example This code example illustrates the use of the TouchList interface's item method and the length property. ...