Search completed in 1.22 seconds.
1395 results for "addeventlistener":
Your results are loading. Please wait...
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
Web › API › Index
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
Mozilla › Gecko › Chrome › API › Browser API › Using
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
Web › HTML › Element › input › button
. ...
... 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...
CanvasPattern.setTransform() - Web APIs
Liv...
... Living Standard ...
... Living Standard ...
... Living Standard ...
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
Web › API › Element › innerHTML
<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
Web › API › KeyboardEvent › key
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
Web › CSS › animation
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
Web › HTML › Element › a
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
Web › HTML › Element › input › color
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 ...
Document: wheel event - Web APIs
Working Draft ...
... Working Draft ...
... Working Draft ...
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. ...
Element: wheel event - Web APIs
Working Draft ...
... Working Draft ...
... Working Draft ...
Event.eventPhase - Web APIs
Web › API › Event › eventPhase
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
Web › API › Event › type
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
Web › API › MessagePort › 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. 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
Web › HTML › Element › input › checkbox
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
Web › SVG › Scripting
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. ...
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
Take note that when using an extension to create an overlay on the browser ...
...Take note that when using an extension to create an overlay on the browser window, any global variables and functions defined within JavaScript that get...
Appendix F: Monitoring DOM changes - Archive of obsolete content
Content code //...
...Bindings are at...
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
Archive › Mozilla › XUL › Index
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. ...
Animation.pause() - Web APIs
Web › API › Animation › pause
Working Draft ...
... Working Draft ...
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
Web › API › Cache
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: pointerlockchange event - Web APIs
The pointerlockchange event is fired when the pointer is locked/unlocked. ...
... The pointerlockchange event is fired when the pointer is locked/unlocked. ...
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. ...
Document: pointerup event - Web APIs
The pointerup event is fired when a pointer is no longer active. ...
... The pointerup event is fired when a pointer is no longer active. ...
DocumentOrShadowRoot.activeElement - Web APIs
Living Standard ...
... Living Standard ...
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
Web › API › EffectTiming › fill
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.scrollWidth - Web APIs
Working Draft Initial definition...
... Working Draft Initial definition ...
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
Web › API › Element
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.defaultPrevented - Web APIs
Living Standard ...
... Living Standard ...
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": ...
HTMLCanvasElement.mozGetAsFile() - Web APIs
L using the readAsDataURL() method. Then a new <img> element is created using the new data URL. ...
... ...
HTMLDialogElement: cancel event - Web APIs
nt handler oncancel Examples Live example HTML <dialog class="example-dialog"> <button class="close" type="reset">Close</button> </dialog> <button class="open-dialog">Open dialog</button> <div class="result"></div> CSS button, div { margin: .5rem; } JS const result = document.querySelector('.result'); const dialog = document.querySelector('.example-dialog'); dialog.addEventListener('cancel', (event) => { result.textContent = 'dialog was canceled'; }); const openDialog = document.querySelector('.open-dialog'); openDialog.addEventListener('click', () => { if (typeof dialog.showModal === 'function') { dialog.showModal(); result.textContent = ''; } else { result.textContent = 'The dialog API is not supported by this browser'; } }); const closeButton ...
... Living Standard ...
HTMLDialogElement.close() - Web APIs
Specifica...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'close()' in that specification. Living Standard HTML 5...
HTMLDialogElement: close event - Web APIs
ler property onclose Examples Live example HTML <dialog class="example-dialog"> <button class="close" type="reset">Close</button> </dialog> <button class="open-dialog">Open dialog</button> <div class="result"></div> CSS button, div { margin: .5rem; } JS const result = document.querySelector('.result'); const dialog = document.querySelector('.example-dialog'); dialog.addEventListener('close', (event) => { result.textContent = 'dialog was closed'; }); const openDialog = document.querySelector('.open-dialog'); openDialog.addEventListener('click', () => { if (typeof dialog.showModal === 'function') { dialog.showModal(); result.textContent = ''; } else { result.textContent = 'The dialog API is not supported by this browser'; } }); const closeButton =...
... Living Standard ...
HTMLDialogElement.open - Web APIs
Specifica...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'open' in that specification. Living Standard HTML 5.1T...
HTMLDialogElement.showModal() - Web APIs
Specifica...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'showModal()' in that specification. Living Standard HTM...
HTMLDialogElement - Web APIs
Specifica...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLDialogElement' in that specification. Living Standard ...
HTMLElement: change event - Web APIs
Try entering something into the field below, and then click somewhere else to trigger the event. HTML <input placehol...
...ment For some elements, including <input type="text">, the change event doesn't fire until the control loses focus. Try entering something into the field below, and then click somewhere else to trigger the event. HTML <input placeholder="Enter some text" name="name"/> <p id="log"></p> JavaScript const input = document.querySelector('input'); const log = document.getElementById('log'); input.addEventListener('change', updateValue); function updateValue(e) { log.textContent = e.target.value; } Result Specifications Specification Status HTML Living StandardThe definition of 'change' in that specification. Living Standard ...
HTMLElement: 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. After the pointercancel event is fired, the browser will also send pointerout followed by pointerleave. ...
...e, 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. ...
HTMLElement: 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. ...
... 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. ...
HTMLElement: 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). ...
...o 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). ...
HTMLElement: 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. ...
...nting 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. ...
HTMLElement: pointermove event - Web APIs
Cancelable Yes Interface PointerEvent Event handler property onpointermove Usage notes The event, which is of type PointerEvent, provides all the information you need to know about the user's interaction with the pointing device, including the position, movement distance, button states, and much more. ...
...ent handler property onpointermove Usage notes The event, which is of type PointerEvent, provides all the information you need to know about the user's interaction with the pointing device, including the position, movement distance, button states, and much more. ...
HTMLElement: 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. ...
...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. ...
HTMLElement: 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. ...
HTMLElement: pointerup event - Web APIs
The pointerup event is fired when a pointer is no longer active. ...
... The pointerup event is fired when a pointer is no longer active. ...
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...
Ajax navigation example - Web APIs
...
... ...
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. ...
MediaSource.readyState - Web APIs
A DOMString. ...
... Recommendation Initial definition. ...
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
Web › API › PushEvent › data
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
Web › API › PushEvent
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
Web › API › RTCError
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: icegatheringstatechange event - Web APIs
is finished. Examples This example creates a handler for icegatheringstatechange events. ...
...echange events. ...
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
Web › API › WebSocket
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
Web › API › Window › blur event
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
Web › API › Window › load event
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
Web › API › Window › ondragdrop
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
Web › API › Window
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
Web › HTML › Element › dialog
> </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...
textLength - SVG: Scalable Vector Graphics
. ...
...These events will be sent any time the slider's value changes, even if the user hasn't stopped moving it, so we can responsively adjust the text width. ...
<script> - SVG: Scalable Vector Graphics
Web › SVG › Element › script
scripts to an SVG document. ...
... Value type: <string>; Default value: ?; Animatable: yes href The URL to the script to load. ...
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 &lt; 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... ...
Customizing the download progress bar - Archive of obsolete content
Now your new progress bar image will only be used for the downloads with your special attribute. ...
Drag & Drop - Archive of obsolete content
Dropping files onto an XUL application It's possible to setup drag and drop events to handle dropping files from external applications or OS file managers onto your XUL-based application. First, you need to hook up the basic drag event handlers: elem.addEventListener("dragover", _dragOver, true); elem.addEventListener("dragdrop", _dragDrop, true); Here, elem could be a window or an XUL element. Next, setup the handlers so that files can be dropped on the application: function _dragOver(aEvent) { var dragService = Components.classes["@mozilla.org/widget/dragservice;1"].getService(Components.interfaces.nsIDragService); var dragSession = dragService.getCurrentSession(); var supported = dragSession.isDataFlavorSupported("text/x-moz-url"); if (!supported) supported = dragSession.
HTML in XUL for rich tooltips - Archive of obsolete content
Our enhanced XUL tooltip is an element that is written ahead of time, and it contains an HTML div element whose type attribute lowers its privileges to being that content element, although it is an element of chrome. This is recommended for security reasons, especially if remote...
Windows - Archive of obsolete content
d only setting the startPos if the element matches some criteria. Example var startPos = null; function mouseDown(event) { startPos = [event.clientX, event.clientY]; } function mouseMove(event) { if (startPos) { var newX = event.screenX - startPos[0]; var newY = event.screenY - startPos[1]; window.moveTo(newX, newY); } } function mouseUp(event) { startPos = null; } window.addEventListener("mousedown", mouseDown, false); window.addEventListener("mouseup", mouseUp, false); window.addEventListener("mousemove", mouseMove, false); XUL Titlebar Element XUL Applications can take advantage of the titlebar element to achieve a similar result without extra JavaScript code. Re-using and focusing named windows While specifying the name parameter to window.open or window.openDialog will p...
How to convert an overlay extension to restartless - Archive of obsolete content
Also make sure to only unload your own JSM files to avoid accidentally breaking things horribly. For tearing down and cleaning up on a per-window b...
Inline options - Archive of obsolete content
); this.style.backgroundColor='red';"> If labels on other toolbar buttons are visible (like by using add-on "Classic Theme Restorer") then show label on throbber toolbar button </setting> NOTE In order for the oninputchanged to execute, the setting MUST have a pref attribute, otherwise the oninputchanged will not trigger. Some discussion on the subject at StackOverflow: How to use addEventListener on inputChanged of inline options Display notifications If you want to use the settings UI for anything more than storing preferences, then you will probably need to initialize them when they first appear. You can't do this until your options XUL has been loaded into the Add-on Manager window, so you should listen for the addon-options-displayed notification to initialize your settings. For exa...
Listening to events in Firefox extensions - Archive of obsolete content
hat application and extension authors can use to receive notifications from <xul:browser> and <xul:tabbrowser> elements to hear about changes relating to loads of the content contained within them. Simple DOM events Registering for a DOM event is done using with code such as the following: function callback(evt) { // Do your processing here. Check evt.target for the target of the event. } b.addEventListener("event", callback, false) Where b is the browser or tabbrowser you wish to watch for events from. Keep in mind that the events may come from any frame within the browser or, for a tabbrowser, any of the browsers within it. Some of the more interesting DOM events you may wish to monitor are listed here: Event Description DOMLinkAdded Dispatched when a new HTML <link> el...
Offering a context menu for form controls - Archive of obsolete content
menus on form controls. <overlay id="formcontrolcontextmenu-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://formcontrolcontextmenu/content/overlay.js"/> </overlay> Change the right-click behavior The overlaid code is responsible for adjusting the behavior of right-clicking on form controls. ...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
> Listing 10: The oncommand event handler Because the Gecko engine implements DOM Level 2 event handlers, you can define dynamic event listeners such as the one in Listing 11. var item = document.getElementById('menu-item-custom'); function handleCommandEvent(aEvent) { alert('OK'); item.removeEventListener('command', handleCommandEvent, false); item.parentNode.removeChild(item); } item.addEventListener('command', handleCommandEvent, false); Listing 11: Additions and deletions using a dynamic event listener Special menu items Much like input elements in HTML, menuitem elements can operate like checkboxes and radio buttons by setting their type attributes. checkbox Adding type="checkbox" to a menuitem element will check that when it is selected, and uncheck it if it is selected again. For a...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
py necessary files to the profile folder, like the initial DB the add-on will use for storage. A few others require cleanup code to be run after the add-on is uninstalled. This appendix covers these cases with simple code that should work for most add-ons. Install Scripts Just like with a regular initialization function, we want a load event handler: // rest of overlay code goes here. window.addEventListener( "load", function() { XulSchoolChrome.BrowserOverlay.init(); }, false); Then all we need is some persistent flag that ensures that the first run code is only run once. The best approach in this case is to use a preference, as explained in the Handling Preferences section. So, if we were to use FUEL, we can do the following in the init function: init : function() { let firstRunPref = "exte...
JavaScript Object Management - Archive of obsolete content
ements in the window without the user noticing the changes. /** * Controls the browser overlay for the Hello World extension. */ <Namespace>.BrowserOverlay = { /** * Initializes this object. */ init : function(aEvent) { this._stringBundle = document.getElementById("xulschoolhello-string-bundle"); // you can make changes to the window DOM here. } // more stuff }; window.addEventListener( "load", function() { <Namespace>.BrowserOverlay.init(); }, false); There are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening new windows, alerts or dialogs. The window has to finish loading before it can do any of these things. They are bad UI practices anyway and you should avoid them. If you really need to do something lik...
Observer Notifications - Archive of obsolete content
The notification topic. * @param aData The additional string associated with the notification. */ observe : function(aSubject, aTopic, aData) { if (aTopic == "xulschoolhello-test-topic") { aSubject.QueryInterface(Ci.nsISupportsString); window.alert("Subject: " + aSubject.data); // => "This is a test" window.alert("Data: " + aData); // => "Hello" } } } window.addEventListener( "load", function() { XULSchoolChrome.BrowserOverlay.init(); }, false); window.addEventListener( "unload", function() { XULSchoolChrome.BrowserOverlay.uninit(); }, false); In the observe method the notification topic is verified because you can have one observer listening to several topics. You may notice that we explicitly set the interface of the aSubject object to nsISupportsString usin...
Session store API - Archive of obsolete content
In this example, nsIConsoleService is used to display a message to the console. This event is sent just before a tab is restored. An event of type SSTabRestored fires each time a tab has finished restoring. It's worth n...
Adding preferences to an extension - Archive of obsolete content
See Method binding for detailed explanation. Once we have the symbol in the local variable symbol, we use that to construct the URL and the string to display in the status bar panel. Installing the event listeners The only thing left to do is to install the event listeners needed to run the startup() and shutdown() routines automatically when the browser window is loaded and unloaded. window.addEventListener("load", function(e) { StockWatcher.startup(); }, false); window.addEventListener("unload", function(e) { StockWatcher.shutdown(); }, false); Design the preference dialog Now that we've written all the code, we need to build the XUL file for the options dialog. <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <prefwindow id="stockwatcher2-prefs" title...
Creating a dynamic status bar extension - Archive of obsolete content
ite the JavaScript code The work of fetching the stock quote and updating the status bar panel's display is handled by the JavaScript code in the file stockwatcher.js. Unlike our previous sample, this one is implemented as an object. We do this because in future samples in this series, we're going to be doing things that are easier to do if our extension is implemented that way. We use the window.addEventListener() DOM function to tell Firefox to call the StockWatcher.startup() function when a new browser window is opened: window.addEventListener("load", function(e) { StockWatcher.startup(); }, false); Our new extension has two primary functions: startup() and refreshInformation(). The refreshInformation() function contains another function, called infoReceived(). The following sections will examine thes...
DOMSubtreeModified - Archive of obsolete content
This event has been deprecated in favor of the Mutation Observer API This event can cause infinite loops if you decide to change the DOM inside the event handler, hence it has been disabled in a number of browsers (see DOMAttrModified and DOMSubtreeModified events are no longer fired when style attribute is changed via CSSOM for example). document.body.addEventListener('DOMSubtreeModified', function () { document.title = 'DOM Changed at ' + new Date(); }, false); ...
MozOrientation - Archive of obsolete content
ified DeviceOrientationEvent. To normalize between the two you can do something like this: function orientationhandler(evt){ // For FF3.6+ if (!evt.gamma && !evt.beta) { evt.gamma = -(evt.x * (180 / Math.PI)); evt.beta = -(evt.y * (180 / Math.PI)); } // use evt.gamma, evt.beta, and evt.alpha // according to dev.w3.org/geo/api/spec-source-orientation } window.addEventListener('deviceorientation', orientationhandler, false); window.addEventListener('MozOrientation', orientationhandler, false); Example window.addEventListener("MozOrientation", doFunc, true); The example below simply displays the raw accelerometer data in the browser window as the events arrive. Notes This event is only dispatched if an accelerometer i...
chargingchange - Archive of obsolete content
boolean The system's battery charging status. Returns true if the battery is charging, if the state of the system's battery is not determinable, or if no battery is attached to the system. Returns false if the battery is discharging. ...
chargingtimechange - Archive of obsolete content
time in seconds until the system's battery is fully charged. Returns 0 if the battery is fully charged. Returns positive infinity, if the battery is discharging or if the implementation is unable to report the remaining charging time. Read only. ...
dischargingtimechange - Archive of obsolete content
ischarged and the system is about to be suspended. Returns positive infinity if the battery is charging, if the implementation is unable to report the remaining discharging time, or if there is no battery attached to the system. Read only. ...
levelchange - Archive of obsolete content
ng level scaled from 0 to 1.0. Returns 0 if the battery is empty and the system is about to suspend. ...
Visualizing an audio spectrum - Archive of obsolete content
Rect(0,0, canvas.width, canvas.height); for (var i = 0; i < fft.spectrum.length; i++ ) { // multiply spectrum by a zoom value magnitude = fft.spectrum[i] * 4000; // Draw rectangle bars for each frequency bin ctx.fillRect(i * 4, canvas.height, 3, -magnitude); } } var audio = document.getElementById('audio-element'); audio.addEventListener('MozAudioAvailable', audioAvailable, false); audio.addEventListener('loadedmetadata', loadedMetadata, false); // FFT from dsp.js, see below var FFT = function(bufferSize, sampleRate) { this.bufferSize = bufferSize; this.sampleRate = sampleRate; this.spectrum = new Float32Array(bufferSize/2); this.real = new Float32Array(bufferSize...
Automated testing tips and tricks - Archive of obsolete content
ith chrome privileges using a chrome doc - see sbtests.xul in http://people.mozilla.com/~davel/scripts/ for an example firefox-bin -P sbtestprofile -chrome chrome://sbtests/content/ above code calls the quit function in quit.js to exit after test is finished How to detect content onload event from chrome use the DOMContentLoaded event chromeWindow.addEventListener('DOMContentLoaded',callbackFunction,false); ...
jspage - Archive of obsolete content
(this.getElementsByTagName(l.tagName)).contains(l);}return(this.contains)?(this!=l&&this.contains(l)):!!(this.compareDocumentPosition(l)&16); },match:function(l){return(!l||(l==this)||(Element.get(this,"tag")==l));}});Native.implement([Element,Window,Document],{addListener:function(o,n){if(o=="unload"){var l=n,m=this; n=function(){m.removeListener("unload",n);l();};}else{h[this.uid]=this;}if(this.addEventListener){this.addEventListener(o,n,false);}else{this.attachEvent("on"+o,n); }return this;},removeListener:function(m,l){if(this.removeEventListener){this.removeEventListener(m,l,false);}else{this.detachEvent("on"+m,l);}return this; },retrieve:function(m,l){var o=c(this.uid),n=o[m];if(l!=undefined&&n==undefined){n=o[m]=l;}return $pick(n);},store:function(m,l){var n=c(this.uid);n[m]=l; return this;},elimin...
PyDOM - Archive of obsolete content
children. This means that if you set the script-type to Python for the window, Python is the default script type for all child elements in the window. XUL Use a script-type attribute on your elements. For example, <window script-type="application/x-python" .../> HTML <meta http-equiv="Content-Script-Type" content="application/x-python" /> should work (but possibly doesn't - see bug 100924). But addEventListener within a <script type="application/x-python"> block does. Almost Python code can not be secured - so it will only run from trusted sources. This means you can only have Python code in chrome. Content loaded from anywhere other than a chrome:// URL can not host Python. It should be obvious why you don't want to run http://evil.com/something_evil.py in your browser! Inside chrome, you can use Pytho...
reserved - Archive of obsolete content
gh it can't override them. In future releases, it won't receive them. See bug 1173061 for details. ...
Dynamically modifying XUL-based user interface - Archive of obsolete content
e interfaces that are used in any interaction of a script and a document. If you have ever written a script that interacts with a XUL (or HTML) document, you have already used DOM calls. The most well known DOM method is probably document.getElementById(), which returns an element, given its id. You may also have used other calls, such as element.setAttribute(), or, if you wrote an extension, the addEventListener() method. All of these are defined in DOM. There are also DOM methods that create, move, or delete elements from a document. They will be demonstrated in a later section. Right now, let's learn what a document is. What is a document? A document is a data structure which is manipulated through DOM APIs. A logical structure of every document is a tree, with nodes being elements, attributes, proce...
close - Archive of obsolete content
Property Type Description target Read only EventTarget The event target (the topmost target in the DOM tree). ...
findbar - Archive of obsolete content
ist, , , , ref, resource, , , , , statusText, style, ,, tooltip, tooltipText, top, width browser Type: browser element Lets you set and get the browser in which the findbar is located. findMode Type: integer Read only. The find mode in use. ...
Methods - Archive of obsolete content
sProgressListener removeTransientNotifications replaceGroup reset rewind scrollByIndex scrollByPixels scrollToIndex select selectAll selectItem selectItemRange selectTabAtIndex setSelectionRange showPane showPopup sizeTo startEditing stop stopEditing swapDocShells syncSessions timedSelect toggleItemSelection Related DOM element methods DOM:element.addEventListener DOM:element.appendChild DOM:element.compareDocumentPosition DOM:element.dispatchEvent DOM:element.getAttribute DOM:element.getAttributeNode DOM:element.getAttributeNodeNS DOM:element.getAttributeNS DOM:element.getElementsByTagName DOM:element.getElementsByTagNameNS DOM:element.getFeature FIXME: brokenLink DOM:element.getUserData DOM:element.hasAttribute DOM:element.hasAt...
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
Archive › Mozilla › XUL › bbox
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
Archive › Mozilla › XUL › box
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
Archive › Mozilla › XUL › deck
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
Archive › Mozilla › XUL › grid
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
Archive › Mozilla › XUL › hbox
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
Archive › Mozilla › XUL › image
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
Archive › Mozilla › XUL › key
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
Archive › Mozilla › XUL › label
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
Archive › Mozilla › XUL › menu
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
Archive › Mozilla › XUL › page
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
Archive › Mozilla › XUL › panel
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
Archive › Mozilla › XUL › param
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
Archive › Mozilla › XUL › query
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
Archive › Mozilla › XUL › radio
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
Archive › Mozilla › XUL › row
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
Archive › Mozilla › XUL › rows
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
Archive › Mozilla › XUL › rule
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
Archive › Mozilla › XUL › scale
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
Archive › Mozilla › XUL › stack
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
Archive › Mozilla › XUL › tab
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
Archive › Mozilla › XUL › tabs
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
Archive › Mozilla › XUL › tree
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
Archive › Mozilla › XUL › vbox
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
Archive › Mozilla › XUL › where
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...
CommandLine - Archive of obsolete content
// Because we haven't yet registered a CommandLineObserver when the application is // launched the first time, we simulate a notification here. ...
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> = [...
Expression closures - Archive of obsolete content
hing similar to a typical Lambda notation. ...
Window: devicelight event - Archive of obsolete content
Property Type Description value Read only Double (float) The sensor data for ambient light in Lux. min Read only Double (float) The minimum value in the range the sensor detects (if available, 0 otherwise). max Read only Double (float) The maximum value in the range the sensor detects (if available, 0 otherwise). Examples window.addEventListener('devicelight', function(event) { console.log(event.value); }); Specifications Specification Status Comment Ambient Light SensorThe definition of 'Ambient Light Events' in that specification. Candidate Recommendation Removed from specification ...
Displaying a graphic with audio samples - Archive of obsolete content
{ // multiply spectrum by a zoom value magnitude = signal[i] * 1000; // Draw rectangle bars for each frequency bin ctx.fillRect(i * 4, canvas.height, 3, -magnitude); } ctx.drawImage(document.getElementById('mozlogo'),0,0, canvas.width, canvas.height); } var audio = document.getElementById('audio-element'); audio.addEventListener('MozAudioAvailable', audioAvailable, false); audio.addEventListener('loadedmetadata', loadedMetadata, false); </script> </body> </html> ...
Desktop mouse and keyboard controls - Game development
vaScript. The good thing about using Phaser is that it offers helper variables and functions for easier and faster development, but it's totally up to you which approach you chose. Pure JavaScript approach Let's think about implementing pure JavaScript keyboard/mouse controls in the game first to see how it would work. First, we'd need an event listener to listen for the pressed keys: document.addEventListener('keydown', keyDownHandler, false); document.addEventListener('keyup', keyUpHandler, false); Whenever any key is pressed down, we're executing the keyDownHandler function, and when press finishes we're executing the keyUpHandler function, so we know when it's no longer pressed. To do that we'll hold the information on whether the keys we are interested in are pressed or not: var rightPressed = f...
Implementing controls using the Gamepad API - Game development
-Down','DPad-Left','DPad-Right', 'Start','Back','Axis-Left','Axis-Right', 'LB','RB','Power','A','B','X','Y', ], This can be different for other types of gamepads like the PS3 controller (or a no-name, generic one), so you have to be careful and not just assume the button you're expecting will be the same button you'll actually get. Next, we set up two event listeners to get the data: window.addEventListener("gamepadconnected", gamepadAPI.connect); window.addEventListener("gamepaddisconnected", gamepadAPI.disconnect); Due to security policy, you have to interact with the controller first while the page is visible for the event to fire. If the API worked without any interaction from the user it could be used to fingerprint them without their knowledge. Both functions are fairly simple: connect: fun...
Mouse controls - Game development
y finished, so let's work on polishing it up. We have already added keyboard controls, but we could easily add mouse controls too. Listening for mouse movement Listening for mouse movement is even easier than listening for key presses: all we need is the listener for the mousemove event. Add the following line in the same place as the other event listeners, just below the keyup event: document.addEventListener("mousemove", mouseMoveHandler, false); Anchoring the paddle movement to the mouse movement We can update the paddle position based on the pointer coordinates -- the following handler function will do exactly that. Add the following function to your code, below the previous line you added: function mouseMoveHandler(e) { var relativeX = e.clientX - canvas.offsetLeft; if(relativeX > 0 && ...
2D maze game with device orientation - Game development
he ball, thus increase the velocity in the proper direction. Implementing the Device Orientation API Probably the most interesting part of the game is its usage of the Device Orientation API for control on mobile devices. Thanks to this you can play the game by tilting the device in the direction you want the ball to roll. ...
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
ail, $(selector) will call jQuery to select selector element(s), and assign it to an event API called .action(). ...
The HTML5 input types - Learn web development
, it can take a for attribute that allows you to associate it with the element or elements that the output value came from. To actually display the current value, and update it as it changed, you must use JavaScript, but this is relatively easy to do: const price = document.querySelector('#price'); const output = document.querySelector('.price-output'); output.textContent = price.value; price.addEventListener('input', function() { output.textContent = price.value; }); Here we store references to the range input and the output in two variables. Then we immediately set the output's textContent to the current value of the input. Finally, an event listener is set to ensure that whenever the range slider is moved, the output's textContent is updated to the new value. Note: range inputs are not support...
Example 2 - Learn web development
lid #000; border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #FFFFFF; } JavaScript Content window.addEventListener("load", function () { var form = document.querySelector('form'); form.classList.remove("no-widget"); form.classList.add("widget"); }); Result for JS No JS HTML Content <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div ...
Use JavaScript within a webpage - Learn web development
al script Usually, you'll be writing scripts in their own .js files. If you want to execute a .js script from your webpage, just use <script> with an src attribute pointing to the script file, using its URL: <script src="path/to/my/script.js"></script> Writing JavaScript within HTML You may also add JavaScript code between <script> tags rather than providing an src attribute. ...
Graceful asynchronous programming with Promises - Learn web development
hod of the promise object. The callback inside the .then() block (referred to as the executor) runs only when the promise call completes successfully and returns the Response object -- in promise-speak, when it has been fulfilled. It is passed the returned Response object as a parameter. Note: The way that a .then() block works is similar to when you add an event listener to an object using AddEventListener(). It doesn't run until an event occurs (when the promise fulfills). The most notable difference is that a .then() will only run once for each time it is used, whereas an event listener could be invoked multiple times. We immediately run the blob() method on this response to ensure that the response body is fully downloaded, and when it is available transform it into a Blob object that we c...
Basic math in JavaScript — numbers and operators - Learn web development
ting depending what holiday season it is Zoom a map in or out depending on what zoom level is selected We'll look at how to code such logic when we look at conditional statements in a future article. For now, let's look at a quick example: <button>Start machine</button> <p>The machine is stopped.</p> const btn = document.querySelector('button'); const txt = document.querySelector('p'); btn.addEventListener('click', updateBtn); function updateBtn() { if (btn.textContent === 'Start machine') { btn.textContent = 'Stop machine'; txt.textContent = 'The machine has started!'; } else { btn.textContent = 'Start machine'; txt.textContent = 'The machine is stopped.'; } } Open in new window You can see the equality operator being used just inside the updateBtn() function. In this ca...
Solve common problems in your JavaScript code - Learn web development
and instances, and how do you create them? What different ways are there to create objects in JavaScript? JSON How do you structure JSON data, and read it from JavaScript? How can you load a JSON file into a page? How do you convert a JSON object to a text string, and back again? Events What are event handlers and how do you use them? What are inline event handlers? What does the addEventListener() function do, and how do you use it? Which mechanism should I use to add event code to my web pages? What are event objects, and how do you use them? How do you prevent default event behaviour? How do events fire on nested elements? (event propagation, also related -- event bubbling and capturing) What is event delegation, and how does it work? Object-oriented JavaScript What are objec...
Ember interactivity: Events, classes and state - Learn web development
ur typed in todo task when we press the Enter key and have it appear in the todos list. We want to be able to capture the text typed into the input. We do this so that our JavaScript code knows what we typed in, and we can save our todo and pass that text along to the todo list component to display. We can capture the keydown event via the on modifier, which is just Ember syntactic sugar around addEventListener and removeEventListener (see this explanation if needed). Add the new line shown below to your header.hbs file: <input class='new-todo' aria-label='What needs to be done?' placeholder='What needs to be done?' autofocus {{on 'keydown' this.onKeyDown}} > This new attribute is inside double curly braces, which tells you it is part of Ember's dynamic templating syntax. The first argument...
Introduction to client-side frameworks - Learn web development
sier access to JavaScript's powers so you can build for today's web. If you want to see code samples from this section in action, you can check out a working version of the app on CodePen, which also allows users to add and delete new tasks. Read more about the JavaScript used in this section: document.createElement() document.createTextNode() document.createDocumentFragment() eventTarget.addEventListener() node.appendChild() node.removeChild() Another way to build UIs Every JavaScript framework offers a way to write user interfaces more declaratively. That is, they allow you to write code that describes how your UI should look, and the framework makes it happen in the DOM behind the scenes. The vanilla JavaScript approach to building out new DOM elements in repetition was difficult to under...
React interactivity: Events and state - Learn web development
Objective: To learn about handling events and state in React, and use those to start making the case study app interactive. Handling events If you've only written vanilla JavaScript before now, you might be used to having a separate JavaScript file, where you query for some DOM nodes and attach listeners to them. For example: const btn = document.querySelector('button'); btn.addEventListener('click', () => { alert("hi!"); }); In React, we write event handlers directly on the elements in our JSX, like this: <button type="button" onClick={() => alert("hi!")} > Say hi! </button> Note: This may seem counter-intuitive regarding best-practice advice that tends to advise against use of inline event handlers on HTML, but remember that JSX is actually part of your JavaScript. In...
TypeScript support in Svelte - Learn web development
s file. Rename it to actions.ts and add the type of the node parameter. It should end up looking like this: // actions.ts export function selectOnFocus(node: HTMLInputElement) { if (node && typeof node.select === 'function' ) { // make sure node is defined and has a select() method const onFocus = () => node.select() // event handler node.addEventListener('focus', onFocus) // when node gets focus call onFocus() return { destroy: () => node.removeEventListener('focus', onFocus) // this will be executed when the node is removed from the DOM } } } Now update Todo.svelte and NewTodo.svelte where we import the actions file. Remember that imports in TypeScript don't include the file extension. In each case i...
Adding a new todo form: Vue events, methods, and models - Learn web development
r the event until it's been triggered once, and then no more. .left: Only triggers the handler via the left mouse button event. .right: Only triggers the handler via the right mouse button event. .middle: Only triggers the handler via the middle mouse button event. .passive: Equivalent to using the { passive: true } parameter when creating an event listener in vanilla JavaScript using addEventListener(). In this case, we need to use the .prevent handler to stop the browser's default submit action. Add .prevent to the @submit handler in your template like so: <form @submit.prevent="onSubmit"> If you try submitting the form now, you'll notice that the page doesn't reload. If you open the console, you can see the results of the console.log() we added inside our onSubmit() method. Bi...
Handling common accessibility problems - Learn web development
n was pressed via the event object's keyCode property; if it is the keycode that matches Return/Enter, we run the function stored in the button's onclick handler using document.activeElement.onclick(). activeElement gives us the element that is currently focused on the page. Note: This technique will only work if you set your original event handlers via event handler properties (e.g. onclick). addEventListener won't work. This is a lot of extra hassle to build the functionality back in. And there's bound to be other problems with it. Better to just use the right element for the right job in the first place. Text alternatives Text alternatives are very important for accessibility -- if a person has a visual or hearing impairment that stops them being able to see or hear some content, then this is a p...
Frame script environment
removeEventListener() Stop listening to events from content. addMessageListener() Listen to messages from chrome. ...
Limitations of chrome scripts
appens in multiprocess Firefox. With the shim The shim intercepts chrome process code that adds listeners to XUL elements and sets up listeners in the content process, relaying the result back to the chrome process. The Event object itself is relayed to the chrome process as a CPOW. To make the shim unnecessary: register event listeners on the global object inside a frame script. For example: addEventListener("load", handler, true) // for example If you need to contact the chrome process when that happens, send it a message. Sandboxes You can create sandboxes in the chrome or the content process. Sandboxes are often used as a safe way to manipulate web content, and if that's your goal, create the sandbox in the content process. There is a shim for sandboxes: if you make a sandbox in the chro...
Frame script environment
removeEventListener() Stop listening to events from content. addMessageListener() Listen to messages from chrome. ...
Frame script loading and lifetime
unload event on the ContentMessageManager triggers ); Then in your frame script, listen for the unload event of the message manager (which is the global this), and sending a message. If you did not set the third argument to true in bootstrap.js on Services.mm.addMessageListener, sending this message during, and after, the unloading event will do nothing. ...
Message manager overview
-level variables defined by frame scripts are not shared). Frame scripts can use this object to send messages to the chrome process, and to receive messages from the chrome process. ...
HTMLIFrameElement.clearMatch()
u want to do. See Using the Browser API for more details. Syntax instanceOfHTMLIframeElement.clearMatch(); Returns Void. Parameters None. Examples The following function is taken from our Browser API demo, and (amongst other things) clears the search results when the search bar is hidden, if an existing search is active. See Implementing the search bar for more explanation. ...
HTMLIFrameElement.findAll()
ng The string you want to search for in the browser <iframe>'s text. caseSensitivity A string to declare whether you want the search to be case sensitive (case-sensitive) or insensitive (case-insensitive.) Example The following function is taken from our Browser API demo, and executes a search when a search form is submitted. See Implementing the search bar for more explanation. searchForm.addEventListener('submit', function(e) { e.preventDefault(); browser.findAll(searchBar.value, 'case-sensitive'); searchActive = true; prev.disabled = false; next.disabled = false; searchBar.blur(); }); Specification Not part of any specification. ...
HTMLIFrameElement.findNext()
eElement.findNext(direction); Return value Void. Parameters direction A string indicating the direction in which you want to cycle through the available search results. Available values are forward and backward. Examples The following functions are taken from our Browser API demo, and cycle through the available search results. See Implementing the search bar for more explanation. prev.addEventListener('touchend',function() { browser.findNext('backward'); }); next.addEventListener('touchend',function() { browser.findNext('forward'); }); Specification Not part of any specification. ...
HTMLIFrameElement.getManifest()
method of the HTMLIFrameElement interface retrieves the manifest of an app loaded in the browser <iframe> and returns it as JSON. Syntax instanceOfHTMLIframeElement.getManifest().then(function(json) { ... }); Parameters None. Return value A promise that resolves to a JSON object representation of the loaded app's manifest. Examples var browser = document.querySelector('iframe'); browser.addEventListener('mozbrowserloadend',function() { var request = browser.getManifest().then(function(json) { console.log(json); }); }); Specification Not part of any specification. ...
HTMLIFrameElement.getStructuredData()
x var instanceOfDOMRequest = instanceOfHTMLIframeElement.getStructuredData(); Returns A DOMRequest to handle the getStructuredData() request's success and error cases. If the request is successful, the request.result is a JSON object representation of all microdata contained on the page loaded in the browser. Parameters None. ...
HTMLIFrameElement.goBack()
nterface is used to navigate backwards in the browser <iframe>'s history. By calling this method, the browser <iframe> changes its location for the previous location available in its navigation history, which sends a series of related events: mozbrowserlocationchange, mozbrowserloadstart, and so on. Syntax instanceOfHTMLIframeElement.goBack(); Returns Void. Parameters None. Examples back.addEventListener('touchend',function() { browser.goBack(); }); Specification Not part of any specification. ...
HTMLIFrameElement.goForward()
LIFrameElement is used to navigate forward in the browser <iframe>'s history. By calling this method, the browser <iframe> changes its location to the next location available in its navigation history, which sends a series of related events: mozbrowserlocationchange, mozbrowserloadstart and so on. Syntax instanceOfHTMLIframeElement.goForward(); Returns Void. Parameters None. Examples fwd.addEventListener('touchend',function() { browser.goForward(); }); Specification Not part of any specification. ...
mozbrowseractivitydone
y Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: success A Boolean that indicates whether the activity has completed successfully (true) or not (false). ...
mozbrowserasyncscroll
e way to the bottom. Similarly, left + width may be greater than scrollWidth, and both left and top may be negative. Note: For performance reasons, this event is asynchronous. That means that the value retrieved through the event object can be different than the real current position of the scroll when the event is processed. ...
mozbrowseraudioplaybackchange
e type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Boolean Indicates whether audio is playing in the browser. ...
mozbrowsercaretstatechanged
Boolean indicating whether the current selection is editable (true) or not (false.) selectedTextContext A DOMString containing the currently-selected text content. sendDoCommandMsg A method allowing you to issue a command via an anonymouse function, i.e. function(command). Possible values are cut, copy, paste and selectAll. ...
mozbrowserclose
target Read only EventTarget The event target (the topmost target in the DOM tree). type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. ...
mozbrowsercontextmenu
s a menu item. id The menu item's id, if the context menu being accessed is a menu item. This is passed to the contextmenuItemSelected() function, to indicate which item has been selected. items An array of further Menu objects, which indicate the menu options available in a menu, if the context menu being accessed is a menu. ...
mozbrowserdocumentfirstpaint
target Read only EventTarget The event target (the topmost target in the DOM tree). type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. ...
mozbrowsererror
t cspBlocked phishingBlocked malwareBlocked unwantedBlocked offline malformedURI redirectLoop unknownSocketType netReset notCached isprinting deniedPortAccess proxyResolveFailure proxyConnectFailure contentEncodingFailure remoteXUL unsafeContentType corruptedContentError certerror other Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowsererror", function( event ) { console.log("An error occurred:" + event.detail); }); Related Events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequire...
mozbrowserfindchange
string that is currently being searched for. searchLimit A number indicating the maximum number of searches that can be returned. numberOfMatches A number indicating the number of matches returned by the search. activeMatchOrdinal A number indicating the position of the currently highlighted search result, e.g. 3 out of 5. ...
mozbrowserfirstpaint
target Read only EventTarget The event target (the topmost target in the DOM tree). type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. ...
mozbrowsericonchange
erties: href A DOMString representing the path to the new icon. sizes A DOMString listing the sizes the new icon is available in, e.g. "16x16" or "16x16 32x32". The any keyword can also be used, to represent "any size." rel A DOMString representing the rel attribute value from the <link> element used to link to the icon. ...
mozbrowserlocationchange
oolean that defines whether it's possible to go back in the navigation history (true) or not (false). canGoForward A Boolean that defines whether it's possible to go forward in the navigation history (true) or not (false). Example This example updates the URL bar so that it will always display the correct URL for the current location. ...
mozbrowsermanifestchange
her the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: href The URL of the new app manifest. ...
mozbrowsermetachange
t attribute value, i.e. the content of the meta tag. type A DOMString representing the type of meta change that this event object represents. This can be added, changed, removed, or undefined. lang Optional A DOMString representing the <meta> name attribute value, if included. If not included, the value returned is undefined. Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowsermetachange", function(event) { console.log("A meta tag has been " + event.details.type + ". Its name is " + event.details.name + ", and its content is " + event.details.content + "."); }); Related Events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow moz...
mozbrowseropensearch
Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: title A DOMString representing the title of the search engine. href A DOMString representing URL of the search engine. ...
mozbrowseropentab
les or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: url A DOMString representing the URL of the new document loaded. ...
mozbrowseropenwindow
name A DOMString representing the name of the new browser window. features A DOMString containing features represented by a list of names and values separated by commas. For a complete list of possible features, see window.open(). frameElement An object representing the new browser <iframe> that will embed the new content. ...
mozbrowserresize
ils Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: width A number representing the new width of the <iframe> viewport, in device pixels. height A number representing the new height of the <iframe> viewport, in device pixels. ...
mozbrowserscroll
mous JavaScript object with the following properties: top A number representing the new vertical scroll position of the <iframe> viewport -- in CSS pixels -- from the top of the viewport. left A number representing the new horizontal scroll position of the <iframe> viewport -- in CSS pixels -- from the left of the viewport. ...
mozbrowserscrollareachanged
Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: width A number representing the new scroll area width of the <iframe> viewport, in CSS pixels. height A number representing the new scroll area height of the <iframe> viewport, in CSS pixels. ...
mozbrowserscrollviewchange
hether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: state A DOMString representing the current state of scrolling in the viewport -- available values are started and stopped. ...
mozbrowsersecuritychange
Boolean indicating if the current SSL certificate is an Extended Validation certificate (true) or not (false). trackingContent A Boolean indicating if tracking content is present on the current page (true) or not (false). mixedContent A Boolean indicating if mixed content is present on the current page (true) or not (false). ...
mozbrowserselectionstatechanged
nts a percentage increase/decrease, e.g. 1.1 is a 10% zoom in, and 0.9% is a 10% zoom out. isCollapsed A Boolean Indicating whether the current selection is collapsed (true) or not (false). visible A Boolean Indicating whether the current selection is visible (true) or not (false). states The current state of the selection. ...
mozbrowsershowmodalprompt
e that if the embedder calls preventDefault() on this event, the iframe is blocked until unblock() is called. Obsolete properties of details msg_name A string representing the type of message. For that event, it's always showmodalprompt. initialValue A string representing the initial value for the window.prompt() methods. ...
mozbrowsertitlechange
Target The browser iframe type Read only DOMString The type of event. bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. detail Read only String The title of the document. ...
mozbrowserusernameandpasswordrequired
ether the server dealing with the authentication is a proxy server (true) or not (false). authenticate() A function that is called to enable the authentication to go ahead. It needs to take two parameters -- the username and password to authenticate. cancel() A function that is called to cancel the authentication. ...
mozbrowservisibilitychange
le Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: visible A Boolean that indicates whether the browser iframe is visible (true) or not (false). ...
HTMLIFrameElement.reload()
the future. The reload() method of the HTMLIFrameElement interface is used to reload the content of the <iframe>. Syntax instanceOfHTMLIframeElement.reload(hardReload); Returns Void. Parameters hardReload Optional A boolean that indicates whether all the resources to reload must be revalidated (true) or may be taken directly from the browser cache (false). Examples stopReload.addEventListener('touchend',function() { if(stopReload.textContent === 'x') { browser.stop(); } else { browser.reload(); } }); Specification Not part of any specification. ...
HTMLIFrameElement.stop()
Mozilla › Gecko › Chrome › API › Browser API › stop
se it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The stop() method of the HTMLIFrameElement interface is used to stop loading the content of the <iframe>. Syntax instanceOfHTMLIframeElement.stop(); Returns Void. Parameters None. Examples stopReload.addEventListener('touchend',function() { if(stopReload.textContent === 'x') { browser.stop(); } else { browser.reload(); } }); Specification Not part of any specification. ...
HTMLIFrameElement.zoom()
Mozilla › Gecko › Chrome › API › Browser API › zoom
nabled devices. Syntax var instanceOfDOMRequest = instanceOfHTMLIframeElement.zoom(zoomFactor); Returns Void. Parameters zoomFactor A unitless number value representing the amount to zoom in or out. It acts like a percentage, so for example 1.1 would zoom in by 10%, whereas 0.9 would zoom out by 10%. Examples var browser = document.querySelector('iframe'); var zoomFactor = 1; zoomIn.addEventListener('touchend',function() { zoomFactor += 0.1; browser.zoom(zoomFactor); }); zoomOut.addEventListener('touchend',function() { zoomFactor -= 0.1; browser.zoom(zoomFactor); }); Specification Not part of any specification. ...
Browser API
nmute() Unmutes any audio playing in the browser <iframe>. HTMLIFrameElement.getMuted() Indicates whether the browser <iframe> is currently muted. Event-related methods In order to manage the browser <iframe>'s content, many new events were added (see below). The following methods are used to deal with those events: The <iframe> gains support for the methods of the EventTarget interface addEventListener(), removeEventListener(), and dispatchEvent(). HTMLIFrameElement.sendMouseEvent() Sends a MouseEvent to the <iframe>'s content. Utility methods Last, there are some utility methods, useful for apps that host a browser <iframe>. HTMLIFrameElement.getStructuredData() Retrieves any structured microdata (and hCard and hCalendar microformat data) contained in the HTML loaded in the browser <i...
overflow-clip-box-block
...
overflow-clip-box-inline
...
overflow-clip-box
...
MozBeforePaint
This computes the current position for the animating box and updates the box's position on screen, and, if the animation sequence is not yet complete, calls window.requestAnimationFrame() to schedule the next animatio...
MozScrolledAreaChanged
ng (int) The width of the visible region of the document. heightRead only long (int) The height of the visible region of the document. ...
smartcard-insert
s Property Type Description targetRead only EventTarget The event target (the topmost target in the DOM tree). typeRead only DOMString The type of event. bubblesRead only Boolean Whether the event normally bubbles or not. cancelableRead only Boolean Whether the event is cancellable or not. Example document.addEventListener("smartcard-insert", smartcardChangeHandler ); Related Events smartcard-remove ...
smartcard-remove
s Property Type Description targetRead only EventTarget The event target (the topmost target in the DOM tree). typeRead only DOMString The type of event. bubblesRead only Boolean Whether the event normally bubbles or not. cancelableRead only Boolean Whether the event is cancellable or not. Example document.addEventListener("smartcard-remove", smartcardChangeHandler ); Related Events smartcard-insert ...
WebChannel.jsm
chrome code and a webpage Chrome code let channel = new WebChannel(webChannelId, Services.io.newURI("https://mozilla.org", null, null)); // receive messages channel.listen(function (webChannelId, message, senderContext) { // send messages channel.send({ data: { greeting: true } }, senderContext); }); Webpage code Receive Messages from an existing WebChannel in content code window.addEventListener("WebChannelMessageToContent", function(e) { // receive messages console.log(e.detail); }, true); Send Messages to an existing WebChannel in chrome code window.dispatchEvent(new window.CustomEvent("WebChannelMessageToChrome", { detail: { id: webChannelId, message: { something: true } } })); ...
Extras
o> </mrow> </mfrac> </mrow> </math> </foreignObject> <text>exp(?)</text> </switch> </g> </g> </svg> </div> Inline JavaScript HTML Content <math display="block"> <mfrac> <mtext id="num">Mouse</mtext> <mtext id="denum">Over</mtext> </mfrac> </math> JavaScript Content function whoIsThereAlert(evt) { alert("Who is there?"); } function attachListener(id) { document.getElementById(id).addEventListener("mouseover", whoIsThereAlert); } function init() { attachListener("num"); attachListener("denum"); } window.addEventListener("load", init); ...
MathML Torture Test
ont-family: TeX Gyre Termes Math; } .XITS math { font-family: XITS Math; } JavaScript Content function updateMathFont() { var mathFont = document.getElementById("MathFont").value; if (mathFont == "Default") { document.body.removeAttribute("class"); } else { document.body.setAttribute("class", mathFont); } } function load() { document.getElementById("MathFont"). addEventListener("change", updateMathFont, false) } window.addEventListener("load", load, false); The following test contains sample TeX formulas from Knuth's TeX book and equivalent MathML representations. It compares the rendering by the XeTeX engine using the default Latin Modern Math font against the MathML rendering by your browser using the default math font, or an alternative OpenType MATH fonts. ...
Mozilla DOM Hacking Guide
nit(), described in Section 1.5. Interface flattening One of the nicest -- and most important -- features of the XPConnect'ed DOM is the interface flattening. "Interface flattening is the ability to call methods on an object regardless of the interface it was defined on." For example, when we have the document object in JavaScript, we can call indistinctly document.getElementById(), or document.addEventListener(), although they are defined on two different interfaces (DOMDocument and DOMEventTarget. Needless to say this is critical for the use of the DOM in real-world content. In Mozilla interface flattening is obtained through the use of the nsIClassInfo interface. nsIClassInfo stores the interfaces available for an object and later on XPConnect uses those interfaces to lookup the right method to call...
Scroll-linked effects
ipt> function snap(destination) { if (Math.abs(destination - window.scrollY) < 3) { scrollTo(window.scrollX, destination); } else if (Math.abs(destination - window.scrollY) < 200) { scrollTo(window.scrollX, window.scrollY + ((destination - window.scrollY) / 2)); setTimeout(snap, 20, destination); } } var timeoutId = null; addEventListener("scroll", function() { if (timeoutId) clearTimeout(timeoutId); timeoutId = setTimeout(snap, 200, parseInt(document.getElementById('snaptarget').style.top)); }, true); </script> <div id="snaptarget" class="snaptarget" style="position: relative; top: 200px; width: 100%; height: 200px; background-color: green"></div> </body> In this example, there is a scroll event listener wh...
L20n HTML Bindings
erted in the final DOM. However, the title attribute is safe. It is important to note that applying translations doesn't replace DOM elements, but only modifies their text nodes and their attributes. This makes it possible to use L20n in conjunction with MVC frameworks. When all DOM nodes are localized, the document element will fire a DocumentLocalized event, which you can listen to: document.addEventListener('DocumentLocalized', function() { // the DOM has been localized and the user sees it in their language YourApp.init(); }); Exposing Context Data You can expose important bits of data to the localization context in form of context data. <script type="application/l10n-data+json"> { "newNotifications": 3, "user": { "name": "Jane", "gender": "feminine" } } </script> This data...
nsIEventListenerInfo
listener is implemented in JS, this returns the listener as a jsdIValue. Otherwise null. This is the method you should use if you want to get access to the actual listener, but the debugger service must be already active, which significantly slows down script execution. Accordingly, this should probably only be used by real debuggers. This approach is necessary because event listeners added with addEventListener won't necessarily be nsIEventListeners; the DOM code will fix up ordinary JavaScript functions to act as listeners. toSource() Tries to serialize the event listener to a string. AString toSource(); Parameters None. Return value Returns a string describing the event listener, or null if serialization isn't possible (for example, if the listener was written in C++). Remarks nsIEventListenerInfo wa...
nsIPushSubscription
key: String.fromCharCode.apply(null, btoa(subscription.getKey("p256dh"))), secret: String.fromCharCode.apply(null, btoa(subscription.getKey("auth"))), })); } pushService.subscribe...
Adding items to the Folder Pane
Pane rebuilds Every time the Folder Pane rebuilds, it fires a "mapRebuild" event, which is the ideal opportunity for extensions to step in and modify the display data. The following code snippet listens for that event: let gNumbersExt = { load: function gne_load() { window.removeEventListener("load", gNumbersExt.load, false); let tree = document.getElementById("folderTree"); tree.addEventListener("mapRebuild", gNumbersExt._insert, false); }, _insert: function gne__insert() { // This function is called when a rebuild occurs } }; window.addEventListener("load", gNumbersExt.load, true); The structure of folder-tree-items The Folder Pane stores its current display data in a property called _rowMap. This property is an array of folder-tree-items. Each item in this array satisfies ...
Building a Thunderbird extension 6: Adding JavaScript
iece of JavaScript code that inserts the current date into our statusbar widget. The statusbar is usually displayed at the bottom of the Thunderbird window. Depending on the installed theme the result will look something like this: Modify XUL elements with JavaScript Save the following JavaScript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js. ...
Creating a Custom Column
use a new function, addColumnHandler that takes a column ID and a handler object. Our implementation will need to call something similar to: gDBView.addColumnHandler("colReplyTo", columnHandler); Setting the Custom Column Handler We've added a special event that gets fired whenever a view is created. When that event fires, you should set up the custom column handler on the new view. ...
Access Window
ion as well as the currently opened tabs. You can do many things with the window object, such as accessing the height or width of the window/tab or setting its title, registering timer events and much more. The Window API will give you the complete details. Since window is a global variable you can use it directly from your JavaScript file. Check if the window is a tab or the root window window.addEventListener("load", function(e) { alert("Is root?: " + isRoot()); }, false); function isRoot() { if(window != window.top) return "false"; else return "true"; } The example above tells you if the window object is a reference of the application window or of one of it is a tabs. Register a timer window.setInterval( function() { alert('foobar'); }, 60000); //execute the function once v...
Detect Opening Folder
Some actions require execution every time you open a folder (for example, registering a custom column handler. To do this you need to capture the select event of the folder [[XUL:tree|tree]] whose id is (conveniently) folderTree like so: window.document.getElementById('folderTree').addEventListener("select", testColumns, false); ...
Filter Incoming Mail
You can take a look at a working code in the CapsKiller add-on repository. ...
Use SQLite
bFile); } this.dbConnection = dbConnection; }, _dbCreate: function(aDBService, aDBFile) { var dbConnection = aDBService.openDatabase(aDBFile); this._dbCreateTables(dbConnection); return dbConnection; }, _dbCreateTables: function(aDBConnection) { for(var name in this.dbSchema.tables) aDBConnection.createTable(name, this.dbSchema.tables[name]); }, }; window.addEventListener("load", function(e) { tbirdsqlite.onLoad(e); }, false); This is another practical sample on how to handle openDatabase and SQL queries on the Client Side, using in-memory (BLOB) storage of 2Mb: var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); tx.executeSql('INSERT INTO...
WebIDL bindings
Calling the dispatchTheEvent method would cause dispatch of an event that content script can see via listeners it has added. Note that in this case the chrome implementation is relying on some [ChromeOnly] methods on EventTarget that were added specifically to make it possible to easily implement event handlers. Other cases can do similar things as needed. ...
Add to iPhoto
oking up to the context menu On startup, we find the content area's context menu and add an event listener to it that will be called when the context menu is displayed. We'll use our handler for this event to add the "Add Image to iPhoto" option if the user has right-clicked on an image. ...
Debug eval sources - Firefox Developer Tools
ug JavaScript code that is evaluated dynamically, either as a string passed to eval() or as a string passed to the Function constructor. In the video below, we load a page containing a source like this: var script = `function foo() { console.log('called foo'); } //# sourceURL=my-foo.js`; eval(script); var button = document.getElementById("foo"); button.addEventListener("click", foo, false); The evaluated string is given the name "my-foo.js" using the //# sourceURL directive. This source is then listed in the source list pane, and can be opened and debugged like any other source. The name of the source will also appear in stack traces appearing in the Web Console. The debugger will also stop at debugger; statements in unnamed eval sources. ...
DevTools API - Firefox Developer Tools
e for a ToolPanel implementation. // In the ToolDefintion object, do // build: (window, target) => new MyPanel(window, target), function MyPanel(window, target) { // The window object that has loaded the URL defined in the ToolDefinition this.window = window; // The Target this toolbox is debugging. this.target = target; // Do synchronous initialization here. window.document.body.addEventListener("click", this.handleClick); } MyPanel.prototype = { open: function() { // Any asynchronous operations should be done here. return this.doSomethingAsynchronous() .then(() => this); }, destroy: function() { // Synchronous destruction. this.window.document.body.removeEventListener("click", this.handleClick); // Async destruction. return this.destroySomethingAsy...
Monster example - Firefox Developer Tools
Specifically: the code creates an object with three properties, each an array: one for fierce monsters one for friendly monsters one for monsters who haven't decided yet. for each array, the code creates and appends 5000 randomly-initialized monsters. Each monster ha...
Animation inspector example: CSS transitions - Firefox Developer Tools
utton != 0) { return; } if (e.target.classList.contains("icon")) { var wasSelected = (e.target.getAttribute("id") == "selected"); clearSelection(); if (!wasSelected) { e.target.setAttribute("id", "selected"); } } } function clearSelection() { var selected = document.getElementById("selected"); if (selected) { selected.removeAttribute("id"); } } document.addEventListener("click", toggleSelection); ...
Animation inspector example: Web Animations API - Firefox Developer Tools
KeyframeSet, noteKeyframeOptions); iconAnimation.pause(); noteAnimation.pause(); var firstTime = true; function animateChannel(e) { if (e.button != 0) { return; } if (e.target.id != "icon") { return; } if (firstTime) { iconAnimation.play(); noteAnimation.play(); firstTime = false; } else { iconAnimation.reverse(); noteAnimation.reverse(); } } document.addEventListener("click", animateChannel); ...
Waterfall - Firefox Developer Tools
e stack at the end of the period: that is, at the point console.timeEnd() was called. If console.timeEnd() was called from the resolution of a Promise, it will also display "(Async: Promise)", under which it will show the "async stack": that is, the call stack at the point the promise was made. ...
AbortController.AbortController() - Web APIs
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. You can...
AbortController.abort() - Web APIs
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. You can...
AbortController.signal - Web APIs
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. You can...
AbortController - Web APIs
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 a DOMException named Abo...
Accelerometer.x - Web APIs
Web › API › Accelerometer › x
et on your server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions. Syntax var xAcceleration = accelerometer.x Value A Number. Example Acceleration is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let accelerometer = new Accelerometer({frequency: 60}); accelerometer.addEventListener('reading', e => { console.log("Acceleration along the X-axis " + accelerometer.x); console.log("Acceleration along the Y-axis " + accelerometer.y); console.log("Acceleration along the Z-axis " + accelerometer.z); }); accelerometer.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
Accelerometer.y - Web APIs
Web › API › Accelerometer › y
et on your server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions. Syntax var yAcceleration = accelerometer.y Value A Number. Example Acceleration is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let accelerometer = new Accelerometer({frequency: 60}); accelerometer.addEventListener('reading', e => { console.log("Acceleration along the X-axis " + accelerometer.x); console.log("Acceleration along the Y-axis " + accelerometer.y); console.log("Acceleration along the Z-axis " + accelerometer.z); }); accelerometer.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
Accelerometer.z - Web APIs
Web › API › Accelerometer › z
et on your server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions. Syntax var zAcceleration = accelerometer.z Value A Number. Example Acceleration is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let accelerometer = new Accelerometer({frequency: 60}); accelerometer.addEventListener('reading', e => { console.log("Acceleration along the X-axis " + accelerometer.x); console.log("Acceleration along the Y-axis " + accelerometer.y); console.log("Acceleration along the Z-axis " + accelerometer.z); }); accelerometer.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
Accelerometer - Web APIs
ad only Returns a double containing the acceleration of the device along the device's y axis. Accelerometer.z Read only Returns a double containing the acceleration of the device along the device's z axis. Example Acceleration is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let acl = new Accelerometer({frequency: 60}); acl.addEventListener('reading', () => { console.log("Acceleration along the X-axis " + acl.x); console.log("Acceleration along the Y-axis " + acl.y); console.log("Acceleration along the Z-axis " + acl.z); }); acl.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. AccelerometerThe definition of 'Ac...
AddressErrors - Web APIs
along the updateDetails object. This lets the Payment Request API know to present the specified error or errors but to allow the user to keep trying to edit the address. Setting up the Donate Now button This code creates a handler for the load event on the window which in turn adds the needed click event handler to the "Donate Now" button so that clicking it starts the payment process. window.addEventListener("load", function(ev) { document.getElementById("pay").addEventListener("click", process, false); }, false); See addEventListener() for information about event handlers and how they work. HTML Here's the simple HTML for this example. <p>Donate US $65 to our worthwhile cause and we will send you a totally not-useless gift as a token of our thanks!</p> <button id="pay">Donate Now</button> R...
Animation.commitStyles() - Web APIs
s the end styling state of an animation to the element being animated, even after that animation has been removed. It will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. Syntax animation.commitStyles(); Parameters None. Return value None. Examples const divElem = document.querySelector('div'); document.body.addEventListener('mousemove', evt => { let anim = divElem.animate( { transform: `translate(${ evt.clientX}px, ${evt.clientY}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitStyles(); }); Specifications Specification Status Comment Web AnimationsThe definition of 'commitStyles()' in that specification. Working Draft ...
Animation.finish() - Web APIs
Web › API › Animation › finish
hod called), it sets the playback time to 0. Syntax Animation.finish(); Parameters None. Return value None. Exceptions InvalidState The player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity. Examples The following example shows how to use the finish() method and catch an InvalidState error. interfaceElement.addEventListener("mousedown", function() { try { player.finish(); } catch(e if e instanceof InvalidState) { console.log("finish() called on paused or finished animation."); } catch(e); logMyErrors(e); //pass exception object to error handler } }); The following example finishes all the animations on a single element, regardless of their direction of playback. elem.getAnimations().forEach( ...
Animation.onremove - Web APIs
n is removed (i.e., put into an active replace state). Syntax var removeHandler = animation.onremove; animation.onremove = removeHandler; Value A function to be called to handle the remove event, or null if no remove event handler is set. ...
Animation.persist() - Web APIs
Web › API › Animation › persist
API's Animation interface explicitly persists an animation, when it would otherwise be removed due to the browser's Automatically removing filling animations behavior. Syntax animation.persist(); Parameters None. Return value None. ...
Animation.play() - Web APIs
Web › API › Animation › play
uration / 2 }); // Pause the cake's animation so it doesn't play immediately. nommingCake.pause(); // This function will play when ever a user clicks or taps var growAlice = function() { // Play Alice's animation. aliceChange.play(); // Play the cake's animation. nommingCake.play(); } // When a user holds their mouse down or taps, call growAlice to make all the animations play. cake.addEventListener("mousedown", growAlice, false); cake.addEventListener("touchstart", growAlice, false); Specifications Specification Status Comment Web AnimationsThe definition of 'play()' in that specification. Working Draft ...
Animation.replaceState - Web APIs
nimation has been removed by the browser's Automatically removing filling animations behavior. persisted: The animation has been explicitly persisted by invoking Animation.persist() on it. removed: The animation has been explicitly removed. ...
Animation.updatePlaybackRate() - Web APIs
pdatePlaybackRate(2); Parameters playbackRate The new speed to set. This may be a positive number (to speed up or slow down the animation), a negative number (to make it play backwards), or zero (to effectively pause the animation). Return value None. Examples A speed selector component would benefit from smooth updating of updatePlaybackRate(), as demonstrated below: speedSelector.addEventListener('input', evt => { cartoon.updatePlaybackRate(parseFloat(evt.target.value)); cartoon.ready.then(() => { console.log(`Playback rate set to ${cartoon.playbackRate}`); }); }); Specifications Specification Status Comment Web AnimationsThe definition of 'updatePlaybackRate()' in that specification. Working Draft ...
Attr.localName - Web APIs
Web › API › Attr › localName
evious DOM specifications this API was defined within the Node interface. Syntax name = attribute.localName Return value A DOMString representing the local part of the attribute's qualified name. Example The following example shows "id" in an alert dialog. HTML Content <button id="example">Click me</button> JavaScript Content const element = document.querySelector("#example"); element.addEventListener("click", function() { const attribute = element.attributes[0]; alert(attribute.localName); }); Notes The local name of an attribute is the part of the attribute's qualified name that comes after the colon. Qualified names are typically used in XML as part of the namespace(s) of the particular XML documents. Note: In Gecko 1.9.2 and earlier, the property returns the upper-cased version ...
AudioContext.createMediaStreamDestination() - Web APIs
Opus file </p> <button>Make sine wave</button> <audio controls></audio> <script> var b = document.querySelector("button"); var clicked = false; var chunks = []; var ac = new AudioContext(); var osc = ac.createOscillator(); var dest = ac.createMediaStreamDestination(); var mediaRecorder = new MediaRecorder(dest.stream); osc.connect(dest); b.addEventListener("click", function(e) { if (!clicked) { mediaRecorder.start(); osc.start(0); e.target.innerHTML = "Stop recording"; clicked = true; } else { mediaRecorder.stop(); osc.stop(0); e.target.disabled = true; } }); mediaRecorder.ondataavailable = function(evt) { // push each chunk (blob...
AudioScheduledSourceNode: ended event - Web APIs
ge notes This event occurs when a AudioScheduledSourceNode has stopped playing, either because it's reached a predetermined stop time, the full duration of the audio has been performed, or because the entire buffer has been played. Examples In this simple example, an event listener for the ended event is set up to enable a "Start" button in the user interface when the node stops playing: node.addEventListener('ended', () => { document.getElementById("startButton").disabled = false; }) You can also set up the event handler using the AudioScheduledSourceNode.onended property: node.onended = function() { document.getElementById("startButton").disabled = false; } For an example of the ended event in use, see our audio-buffer example on GitHub. Specifications Specification Status Co...
AudioScheduledSourceNode - Web APIs
herits methods from its parent interface, AudioNode, and adds the following methods: start() Schedules the node to begin playing the constant sound at the specified time. If no time is specified, the node begins playing immediately. stop() Schedules the node to stop playing at the specified time. If no time is specified, the node stops playing at once. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface: ended Fired when the source node has stopped playing, either because it's reached a predetermined stop time, the full duration of the audio has been performed, or because the entire buffer has been played. Also available using the onended event handler property. Specification Specification Statu...
AudioTrackList: addtrack event - Web APIs
The addtrack event is fired when a track is added to an AudioTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onaddtrack Examples Using addEventListener(): const videoElement = document.querySelector('video'); videoElement.audioTracks.addEventListener('addtrack', (event) => { console.log(`Audio track: ${event.track.label} added`); }); Using the onaddtrack event handler property: const videoElement = document.querySelector('video'); videoElement.audioTracks.onaddtrack = (event) => { console.log(`Audio track: ${event.track.label} added`); }; Specifications Specification Status HTML Living StandardThe definition of 'addtrack' in that specification. Living Standard ...
AudioTrackList.onaddtrack - Web APIs
y onaddtrack is an event handler which is called when the addtrack event occurs, indicating that a new audio track has been added to the media element whose audio tracks the AudioTrackList represents. The event is passed into the event handler in the form of a TrackEvent object, whose track property identifies the newly-added track. Note: You can also add a handler for the addtrack event using addEventListener(). Syntax AudioTrackList.onaddtrack = eventHandler; Value Set onaddtrack to a function that accepts as input a TrackEvent object which indicates in its track property which audio track has been added to the media. Usage notes The addtrack event is called whenever a new track is added to the media element whose audio tracks are represented by the AudioTrackList object. This happens when tra...
AudioTrackList.onchange - Web APIs
ccurs, indicating that one or more of the AudioTracks in the AudioTrackList have been enabled or disabled. The event is passed into the event handler in the form of an Event object; the event doesn't provide any additional information. To determine the new state of media's tracks, you'll have to look at their AudioTrack.enabled flags. Note: You can also add a handler for the change event using addEventListener(). Syntax AudioTrackList.onchange = eventHandler; Value Set onchange to a function that should be called whenever tracks are enabled or disabled on the media element. Example This snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. ...
AudioTrackList.onremovetrack - Web APIs
d when the removetrack event occurs, indicating that an audio track has been removed from the media element, and therefore also from the AudioTrackList. The event is passed into the event handler in the form of a TrackEvent object, whose track property identifies the track that was removed from the media element's AudioTrackList. Note: You can also add a handler for the removetrack event using addEventListener(). Syntax AudioTrackList.onremovetrack = eventHandler; Value Set onremovetrack to a function that accepts as input a TrackEvent object which indicates in its track property which audio track has been removed from the media element. Example This simple example just fetches the current number of audio tracks in the media element whenever a track is removed from the media element. document.q...
AudioTrackList: removetrack event - Web APIs
The removetrack event is fired when a track is removed from an AudioTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onremovetrack Examples Using addEventListener(): const videoElement = document.querySelector('video'); videoElement.audioTracks.addEventListener('removetrack', (event) => { console.log(`Audio track: ${event.track.label} removed`); }); Using the onremovetrack event handler property: const videoElement = document.querySelector('video'); videoElement.audioTracks.onremovetrack = (event) => { console.log(`Audio track: ${event.track.label} removed`); }; Specifications Specification Status HTML Living StandardThe definition of 'removetrack' in that specification. Living Stand...
Background Tasks API - Web APIs
This example will create a random number of tasks (between 100 and 200 of them). To do so, we use the...
BatteryManager - Web APIs
ge event; This event is sent when the battery charging time is updated BatteryManager.ondischargingtimechange A handler for the dischargingtimechange event; This event is sent when the battery discharging time is updated. BatteryManager.onlevelchange A handler for the levelchange event; This event is sent when the battery level is updated. Methods Inherited from EventTarget: 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...
BeforeInstallPromptEvent.prompt() - Web APIs
The prompt() method of the BeforeInstallPromptEvent interface allows a developer to show the install prompt at a time of their own choosing. Syntax BeforeInstallPromptEvent.prompt() Parameters None. Returns An empty Promise. Example var isTooSoon = true; window.addEventListener("beforeinstallprompt", function(e) { if (isTooSoon) { e.preventDefault(); // Prevents prompt display // Prompt later instead: setTimeout(function() { isTooSoon = false; e.prompt(); // Throws if called more than once or default not prevented }, 10000); } // The event was re-dispatched in response to our request // ... }); ...
BeforeInstallPromptEvent - Web APIs
which would allow the user to chose between a web version or an Android version. BeforeInstallPromptEvent.userChoice Read only Returns a Promise that resolves to a DOMString containing either "accepted" or "dismissed". ...
BeforeUnloadEvent - Web APIs
><text x="201" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">BeforeUnloadEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Bubbles No Cancelable Yes Target objects defaultView Interface Event Examples window.addEventListener("beforeunload", function( event ) { event.returnValue = "\o/"; }); // is equivalent to window.addEventListener("beforeunload", function( event ) { event.preventDefault(); }); WebKit-derived browsers don't follow the spec for the dialog box. An almost-cross-browser working example would be close to the below example. window.addEventListener("beforeunload", function (e) { var confirmationM...
Blob - Web APIs
Web › API › Blob
= document.createElement('a'); link.href = url; link.innerText = 'Open the array URL'; document.body.appendChild(link); Result Click the link in the example to see the browser decode the object URL. Extracting data from a blob One way to read content from a Blob is to use a FileReader. The following code reads the content of a Blob as a typed array: const reader = new FileReader(); reader.addEventListener('loadend', () => { // reader.result contains the contents of blob as a typed array }); reader.readAsArrayBuffer(blob); Another way to read content from a Blob is to use a Response. The following code reads the content of a Blob as text: const text = await (new Response(blob)).text(); Or by using Blob.prototype.text(): const text = await blob.text(); By using other methods of FileReader, ...
BluetoothCharacteristicProperties - Web APIs
l if a GATT characteristic supports value change notifications. let device = await navigator.bluetooth.requestDevice({ filters: [{services: ['heart_rate']}] }); let gatt = await device.gatt.connect(); let service = await gatt.getPrimaryService('heart_rate'); let characteristic = await service.getCharacteristic('heart_rate_measurement'); if (characteristic.properties.notify) { characteristics.addEventListener('characteristicvaluechanged', function(event) { console.log(`Received heart rate measurement: ${event.target.value}`); } await characteristic.startNotifications(); } Specifications Specification Status Comment Web BluetoothThe definition of 'BluetoothCharacteristicProperties' in that specification. Draft Initial definition. Browser Compatibili...
CSSPseudoElement - Web APIs
b Animations API. Instances of this interface may be obtained by calling Element.pseudo(). Properties CSSPseudoElement.element Read only Returns the originating/parent Element of the pseudo-element. CSSPseudoElement.type Read only Returns the pseudo-element selector as a CSSOMString. Methods CSSPseudoElement extends EventTarget, so it inherits the following methods: EventTarget.addEventListener() Registers an event handler of a specific event type on the pseudo-element. EventTarget.dispatchEvent() Dispatches an event to this pseudo-element. EventTarget.removeEventListener() Removes an event listener from the pseudo-element. Examples Basic example using Element.pseudo Using pseudo-elements, most modern browsers will automatically add quotation marks around text inside a <q> elem...
Managing screen orientation - Web APIs
or example, games based on the orientation of the device could be messed up by such a change of the orientation. The Screen Orientation API is made to prevent or handle such a change. Listening orientation change The orientationchange event is triggered each time the device change the orientation of the screen and the orientation itself can be read with the Screen.orientation property. screen.addEventListener("orientationchange", function () { console.log("The orientation of the screen is: " + screen.orientation); }); Preventing orientation change Any web application can lock the screen to suits its own needs. The screen is locked using the Screen.lockOrientation() method and unlocked using the Screen.unlockOrientation(). The Screen.lockOrientation() accepts a string (or series of strings) to de...
Cache.add() - Web APIs
Web › API › Cache › add
request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) Examples This code block waits for an InstallEvent to fire, then calls waitUntil() to handle the install process for the app. This consists of calling CacheStorage.open to create a new cache, then using Cache.add to add an asset to it. this.addEventListener('install', function(event) { event.waitUntil( caches.open('v1').then(function(cache) { return cache.add('/sw-test/index.html'); }) ); }); Specifications Specification Status Comment Service WorkersThe definition of 'Cache: add' in that specification. Working Draft Initial definition. ...
Cache.addAll() - Web APIs
Web › API › Cache › addAll
does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) Examples This code block waits for an InstallEvent to fire, then runs waitUntil() to handle the install process for the app. This consists of calling CacheStorage.open to create a new cache, then using addAll() to add a series of assets to it. ...
Cache.match() - Web APIs
Web › API › Cache › match
ler won't intercept the request. If there are any other fetch handlers registered, they will get a chance to call event.respondWith(). If no fetch handlers call event.respondWith(), the request will be handled by the browser as if there were no service worker involvement. If fetch() returns a valid HTTP response with an response code in the 4xx or 5xx range, the catch() will NOT be called. self.addEventListener('fetch', function(event) { // We only want to call event.respondWith() if this is a GET request for an HTML document. if (event.request.method === 'GET' && event.request.headers.get('accept').indexOf('text/html') !== -1) { console.log('Handling fetch event for', event.request.url); event.respondWith( fetch(event.request).catch(function(e) { console.error('Fetch fai...
CacheStorage.delete() - Web APIs
snippet we wait for an activate event, and then run a waitUntil() block that clears up any old, unused caches before a new service worker is activated. Here we have an array of cache names we want to keep (cachesToKeep). We return the keys of the caches in the CacheStorage object using CacheStorage.keys, then check each key to see if it is in the array. If not, we delete it using delete(). ...
CacheStorage.keys() - Web APIs
Web › API › CacheStorage › keys
e event, and then run a waitUntil() block that clears up any old, unused caches before a new service worker is activated. Here we have a whitelist containing the names of the caches we want to keep (cacheWhitelist). We return the keys of the caches in the CacheStorage object using keys(), then check each key to see if it is in the whitelist. If not, we delete it using CacheStorage.delete(). ...
CacheStorage.match() - Web APIs
the CacheStorage using CacheStorage.match(). If so, serve that. If not, open the v1 cache using open(), put the default network request in the cache using Cache.put() and return a clone of the default network request using return response.clone(). The last is necessary because put() consumes the response body. If this fails (e.g., because the network is down), return a fallback response. ...
CacheStorage.open() - Web APIs
Web › API › CacheStorage › open
pen. Return value A Promise that resolves to the requested Cache object. Examples This example is from the MDN sw-test example (see sw-test running live). Here we wait for an InstallEvent to fire, then runs waitUntil() to handle the install process for the app. This consists of calling CacheStorage.open() to create a new cache, then using Cache.addAll() to add a series of assets to it. ...
CanvasRenderingContext2D.drawImage() - Web APIs
e9c6fc.jpg" width="300" height="227"> </div> JavaScript The source image is taken from the coordinates (33, 71), with a width of 104 and a height of 124. It is drawn to the canvas at (21, 20), where it is given a width of 87 and a height of 104. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const image = document.getElementById('source'); image.addEventListener('load', e => { ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104); }); Result Understanding source element size The drawImage() method uses the source element's intrinsic size in CSS pixels when drawing. For example, if you load an Image and specify the optional size parameters in its constructor, you will have to use the naturalWidth and naturalHeight properties of the created inst...
CanvasRenderingContext2D.filter - Web APIs
xample applies the contrast, sepia, and drop-shadow filters to a photo of a gecko. HTML <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/90/a34a525ace.jpg"> </div> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const image = document.getElementById('source'); image.addEventListener('load', e => { ctx.filter = 'contrast(1.4) sepia(1) drop-shadow(9px 9px 2px #e81)'; ctx.drawImage(image, 10, 10, 180, 120); }); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.filter' in that specification. Living Standard Initial definition. ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
er the cursor is in a circular Path2D path. If yes, the circle becomes green, otherwise it is red. ...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
green, otherwise it is red. ...
CanvasRenderingContext2D.miterLimit - Web APIs
eTo(100, 100); 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(); }) textarea.addEventListener("input", drawCanvas); window.addEventListener("load", drawCanvas); ScreenshotLive sample Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.miterLimit'...
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
); ctx.scrollPathIntoView();</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(); }) textarea.addEventListener("input", drawCanvas); window.addEventListener("load", drawCanvas); Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.scrollPathIntoView' in that spec...
Hit regions and accessibility - Web APIs
from the canvas. You can add a hit region to your path and check for the MouseEvent.region property to test if your mouse is hitting your region, for example. <canvas id="canvas"></canvas> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.arc(70, 80, 10, 0, 2 * Math.PI, false); ctx.fill(); ctx.addHitRegion({id: 'circle'}); canvas.addEventListener('mousemove', function(event) { if (event.region) { alert('hit region: ' + event.region); } }); </script> The addHitRegion() method also takes a control option to route events to an element (that is a descendant of the canvas): ctx.addHitRegion({control: element}); This can be useful for routing to <input> elements, for example. See also this codepen demo. Focus rings When working wit...
Using images - Web APIs
g.src = 'myImage.png'; // Set source path When this script gets executed, the image starts loading. If you try to call drawImage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). So you need to be sure to use the load event so you don't try this before the image has loaded: var img = new Image(); // Create new img element img.addEventListener('load', function() { // execute drawImage statements here }, false); img.src = 'myImage.png'; // Set source path If you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. It's beyond the scope of this tutorial to look at image pre-loading tactics, but you should keep that in mind. Embedding an ima...
Client.type - Web APIs
Web › API › Client › type
"sharedworker" Example // service worker client (e.g. a document) function sendMessage(message) { return new Promise(function(resolve, reject) { // note that this is the ServiceWorker.postMessage version navigator.serviceWorker.controller.postMessage(message); window.serviceWorker.onMessage = function(e) { resolve(e.data); }; }); } // controlling service worker self.addEventListener("message", function(e) { // e.source is a client object e.source.postMessage("Hello! Your message was: " + e.data); // Let's also post the type value back to the client e.source.postMessage(e.source.type); }); Specifications Specification Status Comment Service WorkersThe definition of 'type' in that specification. Working Draft Initial definition. ...
Client.url - Web APIs
Web › API › Client › url
The url read-only property of the Client interface returns the URL of the current service worker client. Syntax var clientUrl = client.url; Value A USVString. ...
Clients.claim() - Web APIs
Web › API › Clients › claim
larly over the network, or possibly via a different service worker. Syntax await clients.claim(); Parameters None. Return value A Promise that resolves to undefined. Example The following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker. self.addEventListener('activate', event => { event.waitUntil(clients.claim()); }); Specifications Specification Status Comment Service WorkersThe definition of 'claim()' in that specification. Working Draft Initial definition. ...
Clients.openWindow() - Web APIs
(windowClient.focus()...
Clients - Web APIs
Web › API › Clients
ou to control the types of clients returned. Clients.openWindow() Opens a new browser window for a given url and returns a Promise for the new WindowClient. Clients.claim() Allows an active service worker to set itself as the controller for all clients within its scope. Examples The following example shows an existing chat window or creates a new one when the user clicks a notification. ...
Constraint validation API - Web APIs
ic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern. If you wanted to instead display custom error messages, you could use JavaScript like the following: const nameInput = document.querySelector('input'); const form = document.querySelector('form'); nameInput.addEventListener('input', () => { nameInput.setCustomValidity(''); nameInput.checkValidity(); }); nameInput.addEventListener('invalid', () => { if(nameInput.value === '') { nameInput.setCustomValidity('Enter your username!'); } else { nameInput.setCustomValidity('Usernames can only contain upper and lowercase letters. Try again!'); } }); The example renders like so: In brief: We check th...
ContentIndexEvent.id - Web APIs
is a String which identifies the deleted content index via it's id. Syntax var id = ContentIndexEvent.id; Value A String representation of the deleted content index id. Examples This example listens for the contentdelete event and logs the removed content index id. The ContentIndexEvent is only available to the {domxref('ServiceWorkerGlobalScope','global scope')}} of a ServiceWorker. self.addEventListener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); Specifications Specification Status Comment UnknownThe definition of 'id' in that specification. Unknown Initial definition. ...
ContentIndexEvent - Web APIs
f its parent interface, ExtendableEvent. id Read only A String which identifies the deleted content index via it's id. Methods While ContentIndexEvent offers no methods of its own, it inherits any specified by its parent interface, ExtendableEvent. Examples This example shows the sevice worker script listening for the contentdelete event and logs the removed content index id. self.addEventListener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); Specifications Specification Status Comment UnknownThe definition of 'ContentIndexEvent' in that specification. Unknown Initial definition. ...
Content Index API - Web APIs
he scope of the service worker. They are accessible from the WorkerGlobalScope.self property: // service worker script self.registration.index.add(item); self.registration.index.delete(item.id); const contentIndexItems = self.registration.index.getAll(); contentdelete event When an item is removed from the user agent interface, a contentdelete event is received by the service worker. self.addEventListener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); The contentdelete event is only fired when the deletion happens due to interaction with the browser's built-in user interface. It is not fired when the ContentIndex.delete method is called. Specifications Specification ...
CustomEvent() - Web APIs
ulting to null, of type any, that is an event-dependent value associated with the event. The CustomEventInit dictionary also accepts fields from the EventInit dictionary. Return value A new CustomEvent object of the specified type, with any other properties configured according to the CustomEventInit dictionary (if one was provided). Example // add an appropriate event listener obj.addEventListener("cat", function(e) { process(e.detail) }); // create and dispatch the event var event = new CustomEvent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchEvent(event); Additional examples can be found at Creating and triggering events. Specifications Specification Status Comment DOMThe definition of 'CustomEvent()' in that specification. Living ...
CustomEvent.detail - Web APIs
The detail readonly property of the CustomEvent interface returns any data passed when initializing the event. Note: This feature is available in Web Workers. Syntax let myDetail = customEventInstance.detail; Return value Whatever data the event was initialized with. Example // add an appropriate event listener obj.addEventListener("cat", function(e) { process(e.detail) }); // create and dispatch the event let event = new CustomEvent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchEvent(event); // Will return an object contaning the hazcheeseburger property let myDetail = event.detail; Specifications Specification Status Comment DOMThe definition of 'detail' in that specification. Living Standard Initial definition. ...
DOMTokenList.toggle() - Web APIs
he call. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then replace a token in the list, and write the list into the <span>'s Node.textContent. First, the HTML: <span class="a b">classList is 'a b'</span> Now the JavaScript: let span = document.querySelector("span"); let classes = span.classList; span.addEventListener('click', function() { let result = classes.toggle("c"); if (result) { span.textContent = `'c' added; classList is now "${classes}".`; } else { span.textContent = `'c' removed; classList is now "${classes}".`; } }) The output looks like this: Specifications Specification Status Comment DOMThe definition of 'toggle()' in that specification. Livi...
DeviceLightEvent - Web APIs
...
DeviceMotionEvent - Web APIs
ation is expressed in m/s2. DeviceMotionEvent.rotationRateRead only An object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma. Rotation rate is expressed in degrees per seconds. DeviceMotionEvent.intervalRead only A number representing the interval of time, in milliseconds, at which data is obtained from the device. Example window.addEventListener('devicemotion', function(event) { console.log(event.acceleration.x + ' m/s2'); }); Specifications Specification Status Comment DeviceOrientation Event SpecificationThe definition of 'DeviceMotionEvent' in that specification. Editor's Draft Initial definition. ...
DeviceOrientationEvent - Web APIs
nt.webkitCompassHeading Read only A number represents the difference between the motion of the device around the z axis of the world system and the direction of the north, express in degrees with values ranging from 0 to 360. DeviceOrientationEvent.webkitCompassAccuracy Read only The accuracy of the compass means that the deviation is positive or negative. It's usually 10. Example window.addEventListener('deviceorientation', function(event) { console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma); }); Specifications Specification Status Comment DeviceOrientation Event Specification Editor's Draft Initial specification. ...
DeviceProximityEvent - Web APIs
using the proximity sensor of a device. ...
Document: animationcancel event - Web APIs
Event handler property onanimationcancel The original target for this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationcancel. Examples This code adds a listener to the animationcancel event. document.addEventListener('animationcancel', () => { console.log('Animation canceled'); }); The same, but using the onanimationcancel property instead of addEventListener(): document.onanimationcancel = () => { console.log('Animation canceled'); }; See a live example of this event. Specifications Specification Status Comment CSS Animations Working Draft Initial definition ...
Document: animationend event - Web APIs
Event Event handler property onanimationend The original target for this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationend. Examples This example listens for the animationend event: document.addEventListener('animationend', () => { console.log('Animation ended'); }); The same, but using the onanimationend event handler property: document.onanimationend = () => { console.log('Animation ended'); }; See a live example of this event. Specifications Specification Status Comment CSS Animations Working Draft Initial definition ...
Document: animationiteration event - Web APIs
this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationiteration. Examples This code uses animationiteration to keep track of the number of iterations an animation has completed: let iterationCount = 0; document.addEventListener('animationiteration', () => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }); The same, but using the onanimationiteration event handler property: let iterationCount = 0; document.onanimationiteration = () => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }; See a live example of this event. Specifications ...
Document: animationstart event - Web APIs
rty onanimationstart The original target for this event is the Element that had the animation applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationstart. Examples This listens for the animationstart event and logs a message when it is fired: document.addEventListener('animationstart', () => { console.log('Animation started'); }); The same, but using onanimationstart: document.onanimationstart = () => { console.log('Animation started'); }; See a live example of this event. Specifications Specification Status Comment CSS Animations Working Draft Initial definition ...
Document.caretRangeFromPoint() - Web APIs
range.startContainer; offset = range.startOffset; } // Only split TEXT_NODEs if (textNode && textNode.nodeType == 3) { let replacement = textNode.splitText(offset); let br = document.createElement('br'); textNode.parentNode.insertBefore(br, replacement); } } let paragraphs = document.getElementsByTagName("p"); for (let i = 0; i < paragraphs.length; i++) { paragraphs[i].addEventListener('click', insertBreakAtPoint, false); } Result ...
Document: copy event - Web APIs
able Yes Interface ClipboardEvent Event handler property oncopy The original target for this event is the Element that was the intended target of the copy action. ...
Document.createEvent() - Web APIs
created Event object. type is a string that represents the type of event to be created. Possible event types include "UIEvents", "MouseEvents", "MutationEvents", and "HTMLEvents". See Notes section for details. Example // Create the event. var 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); Notes Event type strings suitable for passing to createEvent() are listed in the DOM standard -- see the table in step 2. Bear in mind that most event objects now have constructors, which are the modern recommended way to create event object instances.
Document: cut event - Web APIs
celable Yes Interface ClipboardEvent Event handler property oncut The original target for this event is the Element that was the intended target of the cut action. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: cut event. Examples document.addEventListener('cut', (event) => { console.log('cut action initiated') }); Specifications Specification Status Clipboard API and events Working Draft ...
Document: fullscreenchange event - Web APIs
e, and this event then bubbles up to the Document. To find out whether the Element is entering or exiting full-screen mode, check the value of DocumentOrShadowRoot.fullscreenElement: if this value is null then the element is exiting full-screen mode, otherwise it is entering full-screen mode. Examples In this example, a handler for the fullscreenchange event is added to the Document. document.addEventListener('fullscreenchange', (event) => { // document.fullscreenElement will point to the element that // is in fullscreen mode if there is one. If there isn't one, // the value of the property is null. if (document.fullscreenElement) { console.log(`Element: ${document.fullscreenElement.id} entered full-screen mode.`); } else { console.log('Leaving full-screen mode.'); } }); See Elem...
Document: fullscreenerror event - Web APIs
onfullscreenerror As with the fullscreenchange event, two fullscreenerror events are fired; the first is sent to the Element which failed to change modes, and the second is sent to the Document which owns that element. ...
Document.hidden - Web APIs
Web › API › Document › hidden
The Document.hidden read-only property returns a Boolean value indicating if the page is considered hidden or not. Syntax var boolean = document.hidden Examples document.addEventListener("visibilitychange", function() { console.log( document.hidden ); // Modify behavior... }); Specifications Specification Status Comment Page Visibility (Second Edition)The definition of 'Document.hidden' in that specification. Recommendation Initial definition ...
Document: 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 This example logs the KeyboardEvent.code value whenever you release a key. addEventListener keyup example <p>Focus the IFrame first (e.g. by clicking in it), then try pressing some keys.</p> <p id="log"></p> const log = document.getElementById('log'); document.addEventList...
Document.onafterscriptexecute - Web APIs
script. It does not fire if the element is added dynamically, such as with appendChild(). ...
Document.onbeforescriptexecute - Web APIs
start executing. Does not fire if the element is added dynamically, eg with appendChild(). ...
Document.ononline - Web APIs
Web › API › Document › ononline
r is online and false if it is definitely offline (disconnected from the network). The online and offline events are fired when the value of this attribute changes. It is important to note that this event and attribute are inherently unreliable. A computer can be connected to a network without having Internet access. 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 ...
Document: paste event - Web APIs
e Yes Interface ClipboardEvent Event handler property onpaste The original target for this event is the Element that was the intended target of the paste action. ...
Document.readyState - Web APIs
Living Standard HTML 5.1The definition of 'D...
Document: readystatechange event - Web APIs
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: scroll event - Web APIs
and animation frames are fired at about the same rate, and therefore the optimization below is often unnecessary. This example optimizes thescroll event for requestAnimationFrame. // Reference: http://www.html5rocks.com/en/tutorials/speed/animations/ let last_known_scroll_position = 0; let ticking = false; function doSomething(scroll_pos) { // Do something with the scroll position } window.addEventListener('scroll', function(e) { last_known_scroll_position = window.scrollY; if (!ticking) { window.requestAnimationFrame(function() { doSomething(last_known_scroll_position); ticking = false; }); ticking = true; } }); See more, similar examples on the resize event page. Specifications Specification Status CSS Object Model (CSSOM) View Module Wor...
Document: selectionchange event - Web APIs
The selectionchange event of the Selection API is fired when the current text selection on a document is changed. Bubbles No Cancelable No Interface Event Event handler property onselectionchange Examples // addEventListener version document.addEventListener('selectionchange', () => { console.log(document.getSelection()); }); // onselectionchange version document.onselectionchange = () => { console.log(document.getSelection()); }; Specifications Specification Status Comment Selection APIThe definition of 'selectionchange' in that specification. Working Draft Initial definition. ...
Document: selectstart event - Web APIs
The selectstart event of the Selection API is fired when a user starts a new selection. If the event is canceled, the selection is not changed. Bubbles Yes Cancelable Yes Interface Event Event handler property onselectstart Examples // addEventListener version document.addEventListener('selectstart', () => { console.log('Selection started'); }); // onselectstart version document.onselectstart = () => { console.log('Selection changed.'); }; Specifications Specification Status Comment Selection APIThe definition of 'selectstart' in that specification. Working Draft Initial definition. ...
Document: transitioncancel event - Web APIs
GlobalEventHandlers.ontransitioncancel The original target for this event is the Element that had the transition applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitioncancel. Examples This code adds a listener to the transitioncancel event: document.addEventListener('transitioncancel', () => { console.log('Transition canceled'); }); The same, but using the ontransitioncancel property instead of addEventListener(): document.ontransitioncancel = () => { console.log('Transition canceled'); }; See a live example of this event. Specifications Specification Status Comment CSS TransitionsThe definition of 'transitioncancel' in t...
Document: transitionend event - Web APIs
event is fired, the transitionend event will not fire. The original target for this event is the Element that had the transition applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitionend. Examples This code adds a listener to the transitionend event: document.addEventListener('transitionend', () => { console.log('Transition ended'); }); The same, but using the ontransitionend property instead of addEventListener(): document.ontransitionend = () => { console.log('Transition ended'); }; See a live example of this event. Specifications Specification Status Comment CSS TransitionsThe definition of 'transitionend' in that specification.
Document: transitionrun event - Web APIs
Event handler property ontransitionrun The original target for this event is the Element that had the transition applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitionrun. Examples This code adds a listener to the transitionrun event: document.addEventListener('transitionrun', () => { console.log('Transition is running but hasn't necessarily started transitioning yet'); }); The same, but using the ontransitionrun property instead of addEventListener(): document.ontransitionrun = () => { console.log('Transition started running'); }; See a live example of this event. Specifications Specification Status Comment CSS Tra...
Document: transitionstart event - Web APIs
rty GlobalEventHandlers.ontransitionstart The original target for this event is the Element that had the transition applied. You can listen for this event on the Document interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitionstart. Examples This code adds a listener to the transitionstart event: document.addEventListener('transitionstart', () => { console.log('Started transitioning'); }); The same, but using the ontransitionstart property instead of addEventListener(): document.ontransitionrun = () => { console.log('Started transitioning'); }; See a live example of this event. Specifications Specification Status Comment CSS TransitionsThe definition of 'transitionstart' in tha...
Document.visibilityState - Web APIs
the standard. Check compatibility table for details. When the value of this property changes, the visibilitychange event is sent to the Document. Typical use of this can be to prevent the download of some assets when the document is solely prerendered, or stop some activities when the document is in the background or minimized. Syntax var string = document.visibilityState Examples document.addEventListener("visibilitychange", function() { console.log( document.visibilityState ); // Modify behavior... }); Specifications Specification Status Comment Page Visibility (Second Edition)The definition of 'Document.visibilityState' in that specification. Recommendation Initial definition. ...
Document: visibilitychange event - Web APIs
Interface Event Event handler property onvisibilitychange Usage notes The event doesn't include the document's updated visibility status, but you can get that information from the document's visibilityState property. Examples This example begins playing a music track when the document becomes visible, and pauses the music when the document is no longer visible. document.addEventListener("visibilitychange", function() { if (document.visibilityState === 'visible') { backgroundMusic.play(); } else { backgroundMusic.pause(); } }); Specifications Specification Status Comment Page Visibility (Second Edition)The definition of 'visibilitychange' in that specification. Recommendation Browser compatibility No compatibility data f...
Document - Web APIs
Web › API › Document
Root.elementFromPoint() Returns the topmost element at the specified coordinates. DocumentOrShadowRoot.elementsFromPoint() Returns an array of all elements at the specified coordinates. DocumentOrShadowRoot.caretPositionFromPoint() Returns a CaretPosition object containing the DOM node containing the caret, and caret's character offset within that node. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. scroll Fired when the document view or an element has been scrolled. Also available via the onscroll property. visibilitychange Fired when the content of a tab has become visible or has been hidden. Also available via the onvisibilitychange property. wheel Fired when the user rotates a wheel button on a p...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
Working Draft Initial definition. ...
Examples of web and XML development using the DOM - Web APIs
>Event Propagation</title> <style> #t-daddy { border: 1px solid red } #c1 { background-color: pink; } </style> <script> function stopEvent(ev) { c2 = document.getElementById("c2"); c2.innerHTML = "hello"; // this ought to keep t-daddy from getting the click. ...
Introduction to the DOM - Web APIs
of data those elements hold, as in the table object example in the previous section. The following is a brief list of common APIs in web and XML page scripting using the DOM. document.getElementById(id) document.getElementsByTagName(name) document.createElement(name) parentNode.appendChild(node) element.innerHTML element.style.left element.setAttribute() element.getAttribute() element.addEventListener() window.content window.onload window.scrollTo() Testing the DOM API This document provides samples for every interface that you can use in your own web development. In some cases, the samples are complete HTML pages, with the DOM access in a <script> element, the interface (e.g, buttons) necessary to fire up the script in a form, and the HTML elements upon which the DOM operates listed as ...
DragEvent.dataTransfer - Web APIs
r property holds the drag operation's data (as a DataTransfer object). This property is Read only . Syntax let data = dragEvent.dataTransfer; Return value data A DataTransfer object which contains the drag event's data. Example This example illustrates accessing the drag and drop data within the dragend event handler. function processData(d) { // Process the data ... } dragTarget.addEventListener("dragend", function(ev) { // Call the drag and drop data processor if (ev.dataTransfer !== null) processData(ev.dataTransfer); }, false); Specifications Specification Status Comment HTML Living StandardThe definition of 'DragEvent.dataTransfer' in that specification. Living Standard HTML 5.1The definition of 'DragEvent.dataTransfer' in that sp...
Element: MSManipulationStateChanged event - Web APIs
anning or zooming an element). It is a proprietary event specific to Microsoft Edge and Internet Explorer. Bubbles Unknown Cancelable Unknown Interface MSManipulationEvent Event handler property Unknown Get manipulation states using the lastState and currentState properties. Examples // Listen for panning state change events outerScroller.addEventListener("MSManipulationStateChanged", function(e) { // Check to see if they lifted while pulled to the top if (e.currentState == MS_MANIPULATION_STATE_INERTIA && outerScroller.scrollTop === 0) { refreshItemsAsync(); } }); Specifications Not part of any specification. ...
Element: click event - Web APIs
(but it must have an href) <button> <img> <input> <label> (but it must be associated with a form control) <textarea> This list is incomplete; you can help MDN by doing further testing/research and expanding it. Examples This example displays the number of consecutive clicks on a <button>. HTML <button>Click</button> JavaScript const button = document.querySelector('button'); button.addEventListener('click', event => { button.innerHTML = `Click count: ${event.detail}`; }); Result Try making rapid, repeated clicks on the button to increase the click count. If you take a break between clicks, the count will reset. Specifications Specification Status UI Events Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'click'...
Element: contextmenu event - Web APIs
ired at the first paragraph. As a result, the first paragraph will do nothing when right-clicked, while the second paragraph will show the standard context menu offered by your browser. HTML <p id="noContextMenu">The context menu has been disabled on this paragraph.</p> <p>But it has not been disabled on this one.</p> JavaScript noContext = document.getElementById('noContextMenu'); noContext.addEventListener('contextmenu', e => { e.preventDefault(); }); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'contextmenu' in that specification. Living Standard ...
Element: copy event - Web APIs
ve example HTML <div class="source" contenteditable="true">Try copying text from this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> CSS div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } JS const source = document.querySelector('div.source'); source.addEventListener('copy', (event) => { const selection = document.getSelection(); event.clipboardData.setData('text/plain', selection.toString().toUpperCase()); event.preventDefault(); }); Result Specifications Specification Status Clipboard API and events Working Draft ...
Element: cut event - Web APIs
Web › API › Element › cut event
ve example HTML <div class="source" contenteditable="true">Try cutting text from this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> CSS div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } JS const source = document.querySelector('div.source'); source.addEventListener('cut', (event) => { const selection = document.getSelection(); event.clipboardData.setData('text/plain', selection.toString().toUpperCase()); selection.deleteFromDocument(); event.preventDefault(); }); Result Specifications Specification Status Clipboard API and events Working Draft ...
Element: dblclick event - Web APIs
of time. dblclick fires after two click events (and by extension, after two pairs of mousedown and mouseup events). Bubbles Yes Cancelable Yes Interface MouseEvent Event handler property ondblclick Examples This example toggles the size of a card when you double click on it. ...
Element: error event - Web APIs
area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } button { height: 2rem; margin: .5rem; } img { width: 0; height: 0; } JS const log = document.querySelector('.event-log-contents'); const badImg = document.querySelector('.bad-img'); badImg.addEventListener('error', (event) => { log.textContent = log.textContent + `${event.type}: Loading image\n`; console.log(event) }); const imgError = document.querySelector('#img-error'); imgError.addEventListener('click', () => { badImg.setAttribute('src', 'i-dont-exist'); }); Result Specifications Specification Status UI Events Working Draft ...
Element: fullscreenerror event - Web APIs
lscreenerror As with the fullscreenchange event, two fullscreenerror events are fired; the first is sent to the Element which failed to change modes, and the second is sent to the Document which contains that element. ...
Element.insertAdjacentText() - Web APIs
ue Void. Exceptions Exception Explanation SyntaxError The position specified is not a recognised value. 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. Example beforeBtn.addEventListener('click', function() { para.insertAdjacentText('afterbegin',textInput.value); }); afterBtn.addEventListener('click', function() { para.insertAdjacentText('beforeend',textInput.value); }); Have a look at our insertAdjacentText.html demo on GitHub (see the source code too.) Here we have a simple paragraph. You can enter some text into the form element, then press the Insert before and Insert a...
Element: msContentZoom event - Web APIs
of the content). It is a proprietary event specific to Microsoft Edge and Internet Explorer. Zoomed elements can expose their zoom level through msContentZoom (ie. scrollTop/Left). The zoom level can be reset with Element.msZoomTo(). Bubbles Unknown Cancelable Unknown Interface Unknown Event handler property Unknown Example contentZoom.addEventListener("MSContentZoom", function(e) { zoomFactor.value = contentZoom.msContentZoomFactor.toFixed(2); }); Specifications Not part of any specification. ...
Element: overflow event - Web APIs
tyle> #wrapper { width: 20px; height: 20px; background: #000; padding: 5px; overflow: hidden; } #child { width: 40px; height: 40px; border: 2px solid grey; background: #ccc; } </style> <script> var wrapper = document.getElementById("wrapper"), child = document.getElementById("child"), toggle = document.getElementById("toggle"); wrapper.addEventListener("overflow", function( event ) { console.log( event ); }, false); wrapper.addEventListener("underflow", function( event ) { console.log( event ); }, false); toggle.addEventListener("change", function( event ) { if ( event.target.checked ) { child.style.width = "40px"; child.style.height = "40px"; } else { child.style.width = "10px"; ...
Element.part - Web APIs
Web › API › Element › part
example. Here the part attribute is used to find the shadow parts, and the part property is then used to change the part identifiers of each tab so the correct styling is applied to the active tab when tabs are clicked. let tabs = []; let children = this.shadowRoot.children; for(let elem of children) { if(elem.getAttribute('part')) { tabs.push(elem); } } tabs.forEach((tab) => { tab.addEventListener('click', (e) => { tabs.forEach((tab) => { tab.part = 'tab'; }) e.target.part = 'tab active'; }) console.log(tab.part); }) Specifications Specification Status Comment Shadow PartsThe definition of 'Element.part' in that specification. Working Draft ...
Element: paste event - Web APIs
ve example HTML <div class="source" contenteditable="true">Try copying text from this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> CSS div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } JS const target = document.querySelector('div.target'); target.addEventListener('paste', (event) => { let paste = (event.clipboardData || window.clipboardData).getData('text'); paste = paste.toUpperCase(); const selection = window.getSelection(); if (!selection.rangeCount) return false; selection.deleteFromDocument(); selection.getRangeAt(0).insertNode(document.createTextNode(paste)); event.preventDefault(); }); Result Specifications ...
Element: scroll event - Web APIs
and animation frames are fired at about the same rate, and therefore the optimization below is often unnecessary. This example optimizes thescroll event for requestAnimationFrame. // Reference: http://www.html5rocks.com/en/tutorials/speed/animations/ let last_known_scroll_position = 0; let ticking = false; function doSomething(scroll_pos) { // Do something with the scroll position } window.addEventListener('scroll', function(e) { last_known_scroll_position = window.scrollY; if (!ticking) { window.requestAnimationFrame(function() { doSomething(last_known_scroll_position); ticking = false; }); ticking = true; } }); Note: You can find more examples on the resize event page. Specifications Specification Status CSS Object Model (CSSOM) View Modul...
Element: select event - Web APIs
ments. Examples Selection logger <input value="Try selecting some text in this element."> <p id="log"></p> function logSelection(event) { const log = document.getElementById('log'); const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd); log.textContent = `You selected: ${selection}`; } const input = document.querySelector('input'); input.addEventListener('select', logSelection); onselect equivalent You can also set up the event handler using the onselect property: input.onselect = logSelection; Specifications Specification Status UI EventsThe definition of 'select' in that specification. Working Draft ...
Element: show event - Web APIs
s fired on/bubbled to an element that has a contextmenu attribute. Bubbles No Cancelable No Interface Event Event handler property onshow Examples <div contextmenu="test"></div> <menu type="context" id="test"> <menuitem label="alert" onclick="alert('the alert label has been clicked')" /> </menu> <script> document.getElementById("test").addEventListener("show", function(e){ alert("the context menu will be displayed"); }, false); </script> Specifications Specification Status HTML5The definition of 'show event' in that specification. Recommendation ...
Element.toggleAttribute() - Web APIs
r The specified attribute name contains one or more characters which are not valid in attribute names. Example In the following example, toggleAttribute() is used to toggle the readonly attribute of a <input>. ...
Element: underflow event - Web APIs
tyle> #wrapper { width: 20px; height: 20px; background: #000; padding: 5px; overflow: hidden; } #child { width: 40px; height: 40px; border: 2px solid grey; background: #ccc; } </style> <script> var wrapper = document.getElementById("wrapper"), child = document.getElementById("child"), toggle = document.getElementById("toggle"); wrapper.addEventListener("overflow", function( event ) { console.log( event ); }, false); wrapper.addEventListener("underflow", function( event ) { console.log( event ); }, false); toggle.addEventListener("change", function( event ) { if ( event.target.checked ) { child.style.width = "40px"; child.style.height = "40px"; } else { child.style.width = "10px"; ...
Event.cancelable - Web APIs
Web › API › Event › cancelable
e canceled. function preventScrollWheel(event) { if (typeof event.cancelable !== 'boolean' || event.cancelable) { // The event can be canceled, so we do so. event.preventDefault(); } else { // The event cannot be canceled, so it is not safe // to call preventDefault() on it. console.warn(`The following event couldn't be canceled:`); console.dir(event); } } document.addEventListener('wheel', preventScrollWheel); Notes Whether an event can be canceled or not is something that's determined when that event is initialized. To cancel an event, call the preventDefault() method on the event. This keeps the implementation from executing the default action that is associated with the event. Specifications Specification Status Comment DOMThe definitio...
Event.composed - Web APIs
Web › API › Event › composed
The composed property returns true beause the click event is always able to propagate across shadow boundaries. You'll notice a difference in the value of composedPath for the two elements. The <ope...
Event.composedPath() - Web APIs
First, the composed property returns true beause the click event is always able to propagate across shadow boundaries. Second, you'll notice a difference in the value of composedPath for the two elements.
Event.currentTarget - Web APIs
arget is interesting to use when attaching the same event handler to several elements. function hide(e){ e.currentTarget.style.visibility = 'hidden'; console.log(e.currentTarget); // When this function is used as an event handler: this === e.currentTarget } var ps = document.getElementsByTagName('p'); for(var i = 0; i < ps.length; i++){ // Console: print the clicked <p> element ps[i].addEventListener('click', hide, false); } // Console: print <body> document.body.addEventListener('click', hide, false); // Click around and make paragraphs disappear Note: The value of event.currentTarget is only available while the event is being handled. If you console.log() the event object, storing it in a variable, and then look for the currentTarget key in the console, its value will be null. Instead, ...
Event.initEvent() - Web APIs
Web › API › Event › initEvent
y property Event.bubbles will give its value. cancelable Is a Boolean defining whether the event can be canceled. Once set, the read-only property Event.cancelable will give its value. Example // Create the event. var event = document.createEvent('Event'); // Create a click event that bubbles up and // cannot be canceled event.initEvent('click', true, false); // Listen for the event. elem.addEventListener('click', function (e) { // e.target matches elem }, false); elem.dispatchEvent(event); Specifications Specification Status Comment DOMThe definition of 'Event.initEvent()' in that specification. Living Standard From Document Object Model (DOM) Level 2 Events Specification, deprecated it, superseded by event constructors. Document Object Model (DOM) Lev...
Event.msConvertURL() - Web APIs
getURL); Parameters file [in] Type: File The file object to be converted. targetType [in] Type: DOMString One of the following values indicating the desired conversion type: "specified", "base64", or "unchanged". targetURL [in, optional] Type: URL The target URL. Return value This method does not return a value. Example var blobList = []; document.getElementById("pasteZone").addEventListener('paste', handlePaste, false); function handlePaste(evt) { var fileList = window.clipboardData.files; // Note that window.DataTransfer.files is not applicable. if (!fileList) { console.log("fileList is null."); return; } for (var i = 0; i < fileList.length; i++) { var file = fileList[i]; var url = URL.createObjectURL(file); if...
Event.target - Web APIs
Web › API › Event › target
Living Standard DOM4The definition of 'Event.target' in that specification. Obsolete Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'Event.target' in that specification. Obsolete ...
Event.timeStamp - Web APIs
Web › API › Event › timeStamp
005 ms). In older implementations, the value is a DOMTimeStamp, accurate to a millisecond. Example HTML <p> Focus this iframe and press any key to get the current timestamp for the keypress event. </p> <p>timeStamp: <span id="time">-</span></p> JavaScript function getTime(event) { var time = document.getElementById("time"); time.firstChild.nodeValue = event.timeStamp; } document.body.addEventListener("keypress", getTime); Result Reduced time precision To offer protection against timing attacks and fingerprinting, the precision of Event.timeStamp might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms. // reduced time precision (2ms) in Firefox 60 event.timeSta...
Event - Web APIs
Web › API › Event
r interfaces based on the main Event interface. Event itself contains the properties and methods which are common to all events. Many DOM elements can be set up to accept (or "listen" for) these events, and execute code in response to process (or "handle") them. Event-handlers are usually connected (or "attached") to various HTML elements (such as <button>, <div>, <span>, etc.) using EventTarget.addEventListener(), and this generally replaces using the old HTML event handler attributes. Further, when properly added, such handlers can also be disconnected if needed using removeEventListener(). Note: One element can have several such handlers, even for the exact same event--particularly if separate, independent code modules attach them, each for its own independent purposes. (For example, a webpage with ...
EventSource: error event - Web APIs
The error event of the EventSource API is fired when a connection with an event source fails to be opened. Bubbles No Cancelable No Interface Event or ErrorEvent Event handler property EventSource.onerror Examples var evtSource = new EventSource('sse.php'); // addEventListener version evtSource.addEventListener('error', (e) => { console.log("An error occurred while attempting to connect."); }); // onerror version evtSource.onerror = (e) => { console.log("An error occurred while attempting to connect."); }; Specifications Specification Status HTML Living StandardThe definition of 'error event' in that specification. Living Standard ...
EventSource: message event - Web APIs
s No Cancelable No Interface MessageEvent Event handler property EventSource.onmessage Examples In this basic example, an EventSource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. ...
EventSource: open event - Web APIs
The open event of the EventSource API is fired when a connection with an event source is opened. Bubbles No Cancelable No Interface Event Event handler property EventSource.onopen Examples var evtSource = new EventSource('sse.php'); // addEventListener version evtSource.addEventListener('open', (e) => { console.log("The connection has been established."); }); // onopen version evtSource.onopen = (e) => { console.log("The connection has been established."); }; Specifications Specification Status HTML Living StandardThe definition of 'open event' in that specification. Living Standard ...
EventTarget() - Web APIs
instance. Syntax var myEventTarget = new EventTarget(); Parameters None. Return value An instance of the EventTarget object. Examples class MyEventTarget extends EventTarget { constructor(mySecret) { super(); this._secret = mySecret; } get secret() { return this._secret; } }; let myEventTarget = new MyEventTarget(5); let value = myEventTarget.secret; // == 5 myEventTarget.addEventListener("foo", function(e) { this._secret = e.detail; }); let event = new CustomEvent("foo", { detail: 7 }); myEventTarget.dispatchEvent(event); let newValue = myEventTarget.secret; // == 7 Specifications Specification Status Comment DOMThe definition of 'EventTarget() constructor' in that specification. Living Standard ...
ExtendableEvent.waitUntil() - Web APIs
initially called within the event callback, but after that it can be called multiple times, until all the promises passed to it settle. Note: The behaviour described in the above paragraph was fixed in Firefox 43 (see bug 1180274). Syntax extendableEvent.waitUntil(promise); Parameters A Promise. Return value undefined. Example Using waitUntil() within a service worker's install event: addEventListener('install', event => { const preCache = async () => { const cache = await caches.open('static-v1'); return cache.addAll([ '/', '/about/', '/static/styles.css' ]); }; event.waitUntil(preCache()); }); Specifications Specification Status Comment Service WorkersThe definition of 'waitUntil()' in that specification. Working Draft Initi...
ExtendableEvent - Web APIs
xample, the same approach can be used for multiple caches. It maps a shorthand identifier for a cache to a specific, versioned cache name. Note: In Chrome, logging statements are visible via the "Inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals. var CACHE_VERSION = 1; var CURRENT_CACHES = { prefetch: 'prefetch-cache-v' + CACHE_VERSION }; self.addEventListener('install', function(event) { var urlsToPrefetch = [ './static/pre_fetched.txt', './static/pre_fetched.html', 'https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif' ]; console.log('Handling install event. Resources to pre-fetch:', urlsToPrefetch); event.waitUntil( caches.open(CURRENT_CACHES['prefetch']).then(function(cache) { return cache.addAll(urlsT...
ExtendableMessageEvent.data - Web APIs
face returns the event's data. It can be any data type. Syntax var myData = extendableMessageEvent.data; Value Any data type. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
ExtendableMessageEvent.lastEventId - Web APIs
the event source. This is an empty string. Syntax var myLastEventId = extendableMessageEvent.lastEventId; Value A DOMString. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
ExtendableMessageEvent.origin - Web APIs
turns the origin of the Client that sent the message. Syntax var myOrigin = extendableMessageEvent.origin; Value A USVString. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
ExtendableMessageEvent.ports - Web APIs
the message is being sent through.) Syntax var myPorts = extendableMessageEvent.ports; Value An array of MessagePort objects. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
ExtendableMessageEvent.source - Web APIs
e message was sent. Syntax var mySource = extendableMessageEvent.source; Value A Client, ServiceWorker or MessagePort object. Examples When the following code is used inside a service worker to respond to a push messages by sending the data received via PushMessageData to the main context via a channel message, the event object of onmessage will be a ExtendableMessageEvent. ...
FetchEvent.preloadResponse - Web APIs
nippet is from the navigation preload page. The ServiceWorkerGlobalScope.onfetch event handler listens for the fetch event. When fired, pass a promise that back to the controlled page to FetchEvent.respondWith(). This promise resolves to the first matching URL request in the Cache object. If no match is found, the code checks for a preloaded response. Else it fetches a response from the network. 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...
FetchEvent.client - Web APIs
Web › API › FetchEvent › client
The FetchEvent.client read-only property returns the Client that the current service worker is controlling. Note: This feature has been deprecated, with its functionality replaced by FetchEvent.clientId and Clients.get(). See this Github issue for discussion/background. Syntax var myClient = FetchEvent.client; Value A Client object. Example self.addEventListener('fetch', function(event) { console.log(event.client); }); ...
FetchEvent.clientId - Web APIs
The clientId read-only property of the FetchEvent interface returns the id of the Client that the current service worker is controlling. The Clients.get() method could then be passed this ID to retrieve the associated client. Syntax var myClientId = fetchEvent.clientId; Value A DOMString that represents the client ID. Example self.addEventListener('fetch', function(event) { console.log(event.clientId); }); Specifications Specification Status Comment Service WorkersThe definition of 'clientId' in that specification. Working Draft Initial definition. ...
FetchEvent.isReload - Web APIs
The isReload read-only property of the FetchEvent interface returns true if the event was dispatched by the user attempting to reload the page, and false otherwise. ...
FetchEvent.navigationPreload - Web APIs
y of the FetchEvent interface returns a Promise that resolves to the instance of NavigationPreloadManager associated with the current service worker registration. Syntax var promise = fetchEvent.navigationPreload Value A Promise that resolves to the instance of NavigationPreloadManager. Example 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...
FetchEvent.replacesClientId - Web APIs
about:blank to another page, as about:blank's client will be reused, rather than be replaced. Additionally, if the fetch isn't a navigation, replacesClientId will be an empty string. This could be used to access/communicate with a client that will imminently be replaced, right before a navigation. Syntax var myReplacedClientId = fetchEvent.replacesClientId; Value A DOMString. Example self.addEventListener('fetch', function(event) { console.log(event.replacesClientId); }); Specifications Specification Status Comment Service WorkersThe definition of 'replacesClientId' in that specification. Working Draft Initial definition. ...
FetchEvent.request - Web APIs
This promise resolves to the first matching URL request in the Cache object. If no match is found, the code fetches a response from the network. The code also handles exceptions thrown from the ServiceWorkerGlobalScope.fetch operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set. self.addEventListener('fetch', function(event) { console.log('Handling fetch event for', event.request.url); event.respondWith( caches.match(event.request).then(function(response) { if (response) { console.log('Found response in cache:', response); return response; } console.log('No response found in cache. About to fetch from network...'); return fetch(event.request)...
FetchEvent.respondWith() - Web APIs
orkError A network error is triggered on certain combinations of FetchEvent.request.mode and Response.type values, as hinted at in the "global rules" listed above. InvalidStateError The event has not been dispatched or respondWithWith() has already been invoked. Examples This fetch event tries to return a response from the cache API, falling back to the network otherwise. addEventListener('fetch', event => { // Prevent the default, and handle the request ourselves. event.respondWith(async function() { // Try to get the response from a cache. const cachedResponse = await caches.match(event.request); // Return it if we found one. if (cachedResponse) return cachedResponse; // If we didn't find a match in the cache, use the network. return fetch(event.reque...
FetchEvent.resultingClientId - Web APIs
aces the previous client during a page navigation. For example, when navigating from page A to page B resultingClientId is the ID of the client associated with page B. If the fetch request is a subresource request or the request's destination is report, resultingClientId will be an empty string. Syntax var myResultingClientId = fetchEvent.resultingClientId; Value A DOMString. Example self.addEventListener('fetch', function(event) { console.log(event.resultingClientId); }); Specifications Specification Status Comment Service WorkersThe definition of 'resultingClientId' in that specification. Working Draft Initial definition. ...
FetchEvent - Web APIs
the lifetime of the event. Used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching. Examples This fetch event uses the browser default for non-GET requests. For GET requests it tries to return a match in the cache, and falls back to the network. If it finds a match in the cache, it asynchronously updates the cache for next time. self.addEventListener('fetch', event => { // Let the browser do its default thing // for non-GET requests. if (event.request.method != 'GET') return; // Prevent the default, and handle the request ourselves. event.respondWith(async function() { // Try to get the response from a cache. const cache = await caches.open('dynamic-v1'); const cachedResponse = await cache.match(event.request); if ...
Using Fetch - Web APIs
he HTTP status code message. Response.ok -- seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a Boolean. ...
File.lastModified - Web APIs
Web › API › File › lastModified
since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. Syntax const time = instanceOfFile.lastModified; Value A number that represents the number of milliseconds since the Unix epoch. ...
File.webkitRelativePath - Web APIs
example, a directory picker is presented which lets the user choose one or more directories. When the change event occurs, a list of all files contained within the selected directory hierarchies is generated and displayed. ...
FileSystemDirectoryEntry.getDirectory() - Web APIs
y for a specified language, then load that dictionary. let dictionary = null; function loadDictionaryForLanguage(appDataDirEntry, lang) { dictionary = null; appDataDirEntry.getDirectory("Dictionaries", {}, function(dirEntry) { dirEntry.getFile(lang + "-dict.json", {}, function(fileEntry) { fileEntry.file(function(dictFile)) { let reader = new FileReader(); reader.addEventListener("loadend", function() { dictionary = JSON.parse(reader.result); }); reader.readAsText(dictFile); }); }); }); } The loadDictionaryForLanguage() function starts by using getDirectory() to obtain the FileSystemDirectoryEntry object representing a subfolder named "Dictionaries" located inside the specified app data directory. The success callback for this take...
FileSystemDirectoryEntry.getFile() - Web APIs
y for a specified language, then load that dictionary. let dictionary = null; function loadDictionaryForLanguage(appDataDirEntry, lang) { dictionary = null; appDataDirEntry.getDirectory("Dictionaries", {}, function(dirEntry) { dirEntry.getFile(lang + "-dict.json", {}, function(fileEntry) { fileEntry.file(function(dictFile)) { let reader = new FileReader(); reader.addEventListener("loadend", function() { dictionary = JSON.parse(reader.result); }); reader.readAsText(dictFile); }); }); }); } The loadDictionaryForLanguage() function starts by using getDirectory() to obtain the FileSystemDirectoryEntry object representing a subfolder named "Dictionaries" located inside the specified app data directory. The success callback for this take...
Guide to the Fullscreen API - Web APIs
, Alt-Tab) while in fullscreen mode exits fullscreen mode as well. Example In this example, a video is presented in a web page. Pressing the Return or Enter key lets the user toggle between windowed and fullscreen presentation of the video. View Live Examples Watching for the Enter key When the page is loaded, this code is run to set up an event listener to watch for the Enter key. document.addEventListener("keydown", function(e) { if (e.keyCode == 13) { toggleFullScreen(); } }, false); Toggling fullscreen mode This code is called when the user hits the Enter key, as seen above. function toggleFullScreen() { if (!document.fullscreenElement) { document.documentElement.requestFullscreen(); } else { if (document.exitFullscreen) { document.exitFullscreen(); } } } Thi...
Fullscreen API - Web APIs
ation switcher (or Alt-Tab) will likewise exit full-screen mode. Example In this example, a video is presented in a web page. Pressing the Return or Enter key lets the user toggle between windowed and full-screen presentation of the video. View Live Examples Watching for the Enter key When the page is loaded, this code is run to set up an event listener to watch for the Enter key. document.addEventListener("keypress", function(e) { if (e.keyCode === 13) { toggleFullScreen(); } }, false); Toggling full-screen mode This code is called by the event handler above when the user hits the Enter key. function toggleFullScreen() { if (!document.fullscreenElement) { document.documentElement.requestFullscreen(); } else { if (document.exitFullscreen) { document.exitFullscreen();...
Gamepad.id - Web APIs
Web › API › Gamepad › id
cimal strings containing the USB vendor and product id of the controller The name of the controller as provided by the driver. For example, a PS2 controller returned 810-3-USB Gamepad. This information is intended to allow you to find a mapping for the controls on the device as well as display useful feedback to the user. Syntax readonly attribute DOMString id; Example window.addEventListener("gamepadconnected", function() { var gp = navigator.getGamepads()[0]; gamepadInfo.innerHTML = "Gamepad connected at index " + gp.index + ": " + gp.id + "."; }); Value A string. Specifications Specification Status Comment GamepadThe definition of 'Gamepad.id' in that specification. Working Draft Initial definition ...
Gamepad.index - Web APIs
Web › API › Gamepad › index
The Gamepad.index property of the Gamepad interface returns an integer that is auto-incremented to be unique for each device currently connected to the system. This can be used to distinguish multiple controllers; a gamepad that is disconnected and reconnected will retain the same index. Syntax readonly attribute long index; Example window.addEventListener("gamepadconnected", function() { var gp = navigator.getGamepads()[0]; gamepadInfo.innerHTML = "Gamepad connected at index " + gp.index + ": " + gp.id + "."; }); Value A number. Specifications Specification Status Comment GamepadThe definition of 'Gamepad.index' in that specification. Working Draft Initial definition ...
Gamepad - Web APIs
Web › API › Gamepad
e access to experimental features like haptic feedback and WebVR controller pose information. Gamepad.hand Read only An enum defining what hand the controller is being held in, or is most likely to be held in. Gamepad.hapticActuators Read only An array containing GamepadHapticActuator objects, each of which represents haptic feedback hardware available on the controller. Example 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); }); Specifications Specification Status Comment GamepadThe definition of 'Gamepad' in that specification. Working Draft Initial definition Gamepad ExtensionsThe defin...
GamepadEvent.gamepad - Web APIs
The GamepadEvent.gamepad property of the GamepadEvent interface returns a Gamepad object, providing access to the associated gamepad data for fired gamepadconnected and gamepaddisconnected events. Syntax readonly attribute Gamepad gamepad; Example 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); }); Value A Gamepad object. Specifications Specification Status Comment GamepadThe definition of 'GamepadEvent.gamepad' in that specification. Working Draft Initial definition ...
Using the Geolocation API - Web APIs
ude: ${latitude} ?, Longitude: ${longitude} ?`; } function error() { status.textContent = 'Unable to retrieve your location'; } if(!navigator.geolocation) { status.textContent = 'Geolocation is not supported by your browser'; } else { status.textContent = 'Locating...'; navigator.geolocation.getCurrentPosition(success, error); } } document.querySelector('#find-me').addEventListener('click', geoFindMe); Result ...
Geolocation API - Web APIs
ude: ${latitude} ?, Longitude: ${longitude} ?`; } function error() { status.textContent = 'Unable to retrieve your location'; } if(!navigator.geolocation) { status.textContent = 'Geolocation is not supported by your browser'; } else { status.textContent = 'Locating...'; navigator.geolocation.getCurrentPosition(success, error); } } document.querySelector('#find-me').addEventListener('click', geoFindMe); Result Specifications Specification Status Comment Geolocation API Recommendation ...
GlobalEventHandlers.onanimationcancel - Web APIs
sole, but you might find other use cases, such as starting a new animation or effect, or terminating some dependent operation. function handleCancelEvent(event) { log("Animation canceled", event); }; Then we add a method to handle toggle display between "flex" and "none" and establish it as the handler for a click event on the "Hide/Show" the Box button: document.getElementById('toggleBox').addEventListener('click', function() { if (box.style.display == "none") { box.style.display = "flex"; document.getElementById("toggleBox").innerHTML = "Hide the box"; } else { box.style.display = "none"; document.getElementById("toggleBox").innerHTML = "Show the box"; } }); Toggling the box to display: none has the effect of aborting its animation. In browsers that support animationcancel,...
GlobalEventHandlers.onanimationend - Web APIs
For information about why, and how to support running an animation more ...
GlobalEventHandlers.onanimationiteration - Web APIs
of the animation have occurred. The onanimationiteration event handler is then set up. It simply sets the box's animation-play-state to "paused", then updates the text displayed in the button to indicate that clicking the button will start playing the next iteration of theanimation. Finally, we set up a handler for a click on the button that runs the animation: document.getElementById("play").addEventListener("click", function(event) { box.style.animationPlayState = "running"; iterationCounter++; }, false); This sets the box element's animation-play-state to "running" and increments the iteration counter. That's all there is to it! Result Assembled together, you get this: Each time the box reaches the opposing corner, it stops, with the button reflecting which iteration number is up next, un...
GlobalEventHandlers.onanimationstart - Web APIs
For information about why, and how to support running an animation more ...
GlobalEventHandlers.onauxclick - Web APIs
behavior being somewhat inconsistent. Syntax target.onauxclick = functionRef; Value functionRef is a function name or a function expression. The function receives a MouseEvent object as its sole argument. Within the function, this will be the element upon which the event was triggered. Only one onauxclick handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener() method instead, since it's more flexible. Example In this example we define functions for two event handlers -- onclick and onauxclick. The former changes the color of the button background, while the latter changes the button foreground (text) color. You can see the two functions in action by trying the demo out with a multi-button mouse (see it live on GitHub; also see the source code). va...
GlobalEventHandlers.oncancel - Web APIs
o dismiss a <dialog>. This event handler prevents the event from bubbling, so any parent handlers are not notified of the event. Syntax target.oncancel = functionRef; Value functionRef is a function name or a function expression. The function receives an Event object as its sole argument. Only one oncancel handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener() method instead, since it's more flexible. Specifications Specification Status Comment HTML Living StandardThe definition of 'oncancel' in that specification. Living Standard ...
GlobalEventHandlers.onclick - Web APIs
ple who don't use a mouse or a touch screen. Syntax target.onclick = functionRef; Value functionRef is a function name or a function expression. The function receives a MouseEvent object as its sole argument. Within the function, this will be the element upon which the event was triggered. Only one onclick handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener() method instead, since it's more flexible. Examples Detecting clicks This example simply changes the color of an element when it's clicked upon. HTML <div id="demo">Click here</div> JavaScript document.getElementById('demo').onclick = function changeContent() { document.getElementById('demo').innerHTML = "Help me"; document.getElementById('demo').style = "Color: red"; } Result ...
GlobalEventHandlers.onclose - Web APIs
The close event fires when the user closes a <dialog>. Note: To handle the closing of a window, use onbeforeunload or onunload. Syntax target.onclose = functionRef; Value functionRef is a function name or a function expression. The function receives an Event object as its sole argument. Only one onclose handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener() method instead, since it's more flexible. Specifications Specification Status Comment HTML Living StandardThe definition of 'onclose' in that specification. Living Standard ...
GlobalEventHandlers.oncontextmenu - Web APIs
use button is clicked on the window. Unless the default behavior is prevented, the browser context menu will activate. Syntax target.oncontextmenu = functionRef; Value functionRef is a function name or a function expression. The function receives an Event object as its sole argument. Only one oncontextmenu handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener() method instead, since it's more flexible. Examples Disabling context menus This snippet prevents context menus from opening in the window. The context menu typically appears upon a right click. HTML <p>Try opening the context menu. Is it disabled?<p> JavaScript window.oncontextmenu = (e) => { e.preventDefault(); } Result Pausing an animation This example pauses a spinning shape w...
GlobalEventHandlers.ondblclick - Web APIs
ment. It fires after two click events. Syntax target.ondblclick = functionRef; Value functionRef is a function name or a function expression. The function receives a MouseEvent object as its sole argument. Within the function, this will be the element upon which the event was triggered. Only one ondblclick handler can be assigned to an object at a time. You may prefer to use the EventTarget.addEventListener() method instead, since it's more flexible. Example This example logs the position of double clicks. HTML <p>Double click anywhere in this example.</p> <p id="log"></p> JavaScript let log = document.getElementById('log'); document.ondblclick = logDoubleClick; function logDoubleClick(e) { log.textContent = `Position: (${e.clientX}, ${e.clientY})`; } Result Specifications Sp...
GlobalEventHandlers.onformdata - Web APIs
also be triggered by the invocation of a FormData() constructor. onformdata is available on HTMLFormElement. Syntax target.onformdata = functionRef; Value functionRef is a function name or a function expression. The function receives a FormDataEvent object as its sole argument. ...
GlobalEventHandlers.onload - Web APIs
ent fires when the document has finished loading!</p> </body> </html> Notes The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading. There are also DOM Events like DOMContentLoaded and DOMFrameContentLoaded (which can be handled using EventTarget.addEventListener()) which are fired after the DOM for the page has been constructed, but do not wait for other resources to finish loading. Specifications Specification Status Comment HTML Living StandardThe definition of 'onload' in that specification. Living Standard Initial definition ...
GlobalEventHandlers.onloadend - Web APIs
ventHandler representing the code to be called when the loadend event is raised (when progress has stopped on the loading of a resource.) Syntax img.onloadend = funcRef; Value funcRef is the handler function to be called when the resource's loadend event fires. Examples HTML content <img src="myImage.jpg"> JavaScript content // 'loadstart' fires first, then 'load', then 'loadend' image.addEventListener('load', function(e) { console.log('Image loaded'); }); image.addEventListener('loadstart', function(e) { console.log('Image load started'); }); image.addEventListener('loadend', function(e) { console.log('Image load finished'); }); ...
GlobalEventHandlers.onloadstart - Web APIs
Handler representing the code to be called when the loadstart event is raised (when progress has begun on the loading of a resource.) Syntax img.onloadstart = funcRef; Value funcRef is the handler function to be called when the resource's loadstart event fires. Examples HTML content <img src="myImage.jpg"> JavaScript content // 'loadstart' fires first, then 'load', then 'loadend' image.addEventListener('load', function(e) { console.log('Image loaded'); }); image.addEventListener('loadstart', function(e) { console.log('Image load started'); }); image.addEventListener('loadend', function(e) { console.log('Image load finished'); }); Specifications Specification Status Comment HTML Living StandardThe definition of 'onloadstart' in that specification. Living ...
GlobalEventHandlers.onscroll - Web APIs
l handles general wheel rotation, while onscroll handles scrolling of an object's content. Syntax target.onscroll = functionRef Value functionRef A function name, or a function expression. The function receives a UIEvent object as its sole argument. Only one onscroll handler can be assigned to an object at a time. For greater flexibility, you can pass a scroll event to the EventTarget.addEventListener() method instead. Example This example monitors scrolling on a <textarea>, and logs the element's vertical scroll position accordingly. HTML <textarea>1 2 3 4 5 6 7 8 9</textarea> <p id="log"></p> CSS textarea { width: 4rem; height: 8rem; font-size: 3rem; } JavaScript const textarea = document.querySelector('textarea'); const log = document.getElementById('log'); textarea.onscroll ...
Gyroscope.x - Web APIs
Web › API › Gyroscope › x
sistent 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. Syntax var x = gyroscope.x Value A Number. Example The gyroscope is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let gyroscope = new Gyroscope({frequency: 60}); gyroscope.addEventListener('reading', e => { console.log("Angular velocity along the X-axis " + gyroscope.x); console.log("Angular velocity along the Y-axis " + gyroscope.y); console.log("Angular velocity along the Z-axis " + gyroscope.z); }); gyroscope.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
Gyroscope.y - Web APIs
Web › API › Gyroscope › y
sistent 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. Syntax var y = gyroscope.y Value A Number. Example The gyroscope is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let gyroscope = new Gyroscope({frequency: 60}); gyroscope.addEventListener('reading', e => { console.log("Angular velocety along the X-axis " + gyroscope.x); console.log("Angular velocety along the Y-axis " + gyroscope.y); console.log("Angular velocety along the Z-axis " + gyroscope.z); }); gyroscope.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
Gyroscope.z - Web APIs
Web › API › Gyroscope › z
sistent 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. Syntax var z = gyroscope.z Value A Number. Example The gyroscope is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let gyroscope = new Gyroscope({frequency: 60}); gyroscope.addEventListener('reading', e => { console.log("Angular velocety along the X-axis " + gyroscope.x); console.log("Angular velocety along the Y-axis " + gyroscope.y); console.log("Angular velocety along the Z-axis " + gyroscope.z); }); gyroscope.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
Gyroscope - Web APIs
Web › API › Gyroscope
ns a double, containing the angular velocity of the device along the device's y axis. Gyroscope.z Read only Returns a double, containing the angular velocity of the device along the device's z axis. Example The gyroscope is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let gyroscope = new Gyroscope({frequency: 60}); gyroscope.addEventListener('reading', e => { console.log("Angular velocity along the X-axis " + gyroscope.x); console.log("Angular velocity along the Y-axis " + gyroscope.y); console.log("Angular velocity along the Z-axis " + gyroscope.z); }); gyroscope.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
Audio() - Web APIs
y the audio through to the end without interruption. Listen for the canplay event. It is sent to the <audio> element when there's enough audio available to begin playback, although interruptions may occur). Listen for the canplaythrough event. It is sent when it's estimated that the audio should be able to play to the end without interruption. The event-based approach is best: myAudioElement.addEventListener("canplaythrough", event => { /* the audio is now playable; play it if permissions allow */ myAudioElement.play(); }); Memory usage and management If all references to an audio element created using the Audio() constructor are deleted, the element itself won't be removed from memory by the JavaScript runtime's garbage collection mechanism if playback is currently underway. Instead, the audio...
HTMLAudioElement - Web APIs
n page load. Modern browser's default autoplay policy will block that from happening. Refer to firefox and chrome for best practices and work arounds. Some of the more commonly used properties of the audio element include src, currentTime, duration, paused, muted, and volume. This snippet copies the audio file's duration to a variable: var audioElement = new Audio('car_horn.wav'); audioElement.addEventListener('loadeddata', () => { let duration = audioElement.duration; // The duration variable now holds the duration (in seconds) of the audio clip }) Events Inherits methods from its parent, HTMLMediaElement, and from its ancestor HTMLElement. Listen to events using addEventListener() or by assigning an event listener to the oneventname property of this interface. Specifications Speci...
HTMLButtonElement.labels - Web APIs
-only property returns a NodeList of the <label> elements associated with the <button> element. Syntax var labelElements = button.labels; Return value A NodeList containing the <label> elements associated with the <button> element. Example HTML <label id="label1" for="test">Label 1</label> <button id="test">Button</button> <label id="label2" for="test">Label 2</label> JavaScript window.addEventListener("DOMContentLoaded", function() { const button = document.getElementById("test"); for(var i = 0; i < button.labels.length; i++) { console.log(button.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Standard Initial definiti...
HTMLCanvasElement.toDataURL() - Web APIs
6AP/Z" var mediumQuality = canvas.toDataURL('image/jpeg', 0.5); var lowQuality = canvas.toDataURL('image/jpeg', 0.1); Example: Dynamically change images You can use this technique in coordination with mouse events in order to dynamically change images (gray-scale vs. ...
HTMLCanvasElement: webglcontextcreationerror event - Web APIs
able to create a WebGLRenderingContext context. This event has a WebGLContextEvent.statusMessage property, which can contain a platform dependent string with more information about the failure. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example var canvas = document.getElementById('canvas'); canvas.addEventListener('webglcontextcreationerror', function(e) { console.log(e.statusMessage || 'Unknown error'); }, false); var gl = canvas.getContext('webgl'); // logs statusMessage or "Unknown error" if unable to create WebGL context Specifications Specification Status Comment WebGL 1.0The definition of 'webglcontextcreationerror' in that specification. Recommendation Initial def...
HTMLCanvasElement: webglcontextlost event - Web APIs
iated with a WebGLRenderingContext object has been lost. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example With the help of the WEBGL_lose_context extension, you can simulate the webglcontextlost event: const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', (event) => { console.log(event); }); gl.getExtension('WEBGL_lose_context').loseContext(); // "webglcontextlost" event is logged. Specifications Specification Status Comment WebGL 1.0The definition of 'webglcontextlost' in that specification. Recommendation Initial definition. ...
HTMLCanvasElement: webglcontextrestored event - Web APIs
state of your WebGL application and recreate resources. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example With the help of the WEBGL_lose_context extension, you can simulate the webglcontextrestored event: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').restoreContext(); // "webglcontextrestored" event is logged. Specifications Specification Status Comment WebGL 1.0The definition of 'webglcontextrestored' in that specification. Recommendation Initial definition. ...
HTMLCanvasElement - Web APIs
ferControlToOffscreen() Transfers control to an OffscreenCanvas object, either on the main thread or on a worker. Obsolete methods HTMLCanvasElement.mozGetAsFile() Returns a File object representing the image contained in the canvas; this file is a memory-based file, with the specified name. If type is not specified, the image type is image/png. Events Listen to these events using addEventListener(). webglcontextcreationerror Fired if the user agent is unable to create a WebGLRenderingContext or WebGL2RenderingContext context. webglcontextlost Fired if the user agent detects that the drawing buffer associated with a WebGLRenderingContext or WebGL2RenderingContext object has been lost. webglcontextrestored Fired if the user agent restores the drawing buffer for a WebGLRenderingConte...
HTMLDetailsElement: toggle event - Web APIs
Living Standard ...
HTMLDetailsElement - Web APIs
ll: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, HTMLElement. HTMLDetailsElement.open Is a boolean reflecting the open HTML attribute, indicating whether or not the element's contents (not counting the <summary>) is to be shown to the user. Methods No specific method; inherits methods from its parent, HTMLElement. Events Listen to this event using addEventListener() or by assigning an event listener to the oneventname property of this interface. toggle Fired when the open/closed state of a <details> element is toggled. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLDetailsElement' in that specification. Candidate Recommendation ...
HTMLDialogElement.returnValue - Web APIs
Specifications Specification Status Comment HTML Living StandardThe definition of 'returnvalue' in that specification. L...
HTMLDialogElement.show() - Web APIs
'); var cancelButton = document.getElementById('cancel'); var dialog = document.getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if(dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } } // Update button opens a modal dialog updateButton.addEventListener('click', function() { dialog.showModal(); openCheck(dialog); }); // Form cancel button closes the dialog box cancelButton.addEventListener('click', function() { dialog.close('animalNotChosen'); openCheck(dialog); }); })(); </script> Specifications Specification Status Comment HTML Living StandardThe defi...
HTMLElement: beforeinput event - Web APIs
Yes Default Action Update the DOM element Examples This example logs current value of the element immediately before replacing that value with the new one applied to the <input> element. HTML <input placeholder="Enter some text" name="name"/> <p id="values"></p> JavaScript const input = document.querySelector('input'); const log = document.getElementById('values'); input.addEventListener('beforeinput', updateValue); function updateValue(e) { log.textContent = e.target.value; } Result Specifications Specification Status UI EventsThe definition of 'beforeinput event' in that specification. Working Draft ...
HTMLElement.hidden - Web APIs
ents which are. Syntax isHidden = HTMLElement.hidden; HTMLElement.hidden = true | false; Value A Boolean which is true if the element is hidden from view; otherwise, the value is false. Example Here's an example where a hidden block is used to contain a thank you message that is displayed after a user agrees to an unusual request. JavaScript document.getElementById("okButton") .addEventListener("click", function() { document.getElementById("welcome").hidden = true; document.getElementById("awesome").hidden = false; }, false); This code sets up a handler for the welcome panel's "OK" button that hides the welcome panel and makes the follow-up panel--with the curious name "awesome"--visible in its place. HTML The HTML for the two boxes are shown here. The welcome panel <div id="we...
HTMLElement: input event - Web APIs
he value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like. Examples This example logs the value whenever you change the value of the <input> element. HTML <input placeholder="Enter some text" name="name"/> <p id="values"></p> JavaScript const input = document.querySelector('input'); const log = document.getElementById('values'); input.addEventListener('input', updateValue); function updateValue(e) { log.textContent = e.target.value; } Result Specifications Specification Status HTML Living StandardThe definition of 'input event' in that specification. Living Standard Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'input event' in that specification. Obsolete ...
HTMLElement - Web APIs
ementInternals instance to the custom element. HTMLOrForeignElement.blur() Removes keyboard focus from the currently focused element. HTMLElement.click() Sends a mouse click event to the element. HTMLOrForeignElement.focus() Makes the element the current keyboard focus. HTMLElement.forceSpellCheck() Runs the spell checker on the element's contents. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. invalid Fired when an element does not satisfy its constraints during constraint validation. Also available via the oninvalid property. Animation events animationcancel Fired when an animation unexpectedly aborts. Also available via the onanimationcancel property. animationend Fired when an animation ...
HTMLFormElement.reportValidity() - Web APIs
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user. Syntax HTMLFormElement.reportValidity() Return value Boolean Example document.forms['myform'].addEventListener('submit', function() { document.forms['myform'].reportValidity(); }, false); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement.reportValidity()' in that specification. Living Standard HTML 5.1The definition of 'HTMLFormElement.reportValidity()' in that specification. Recommendation Initial definition ...
HTMLFormElement - Web APIs
uestAutocomplete() Triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not off or on. The form will receive an event once the user has finished with the interface, the event will either be autocomplete when the fields have been filled or autocompleteerror when there was a problem. Events Listen to these events using addEventListener(), or by assigning an event listener to the oneventname property of this interface. formdata The formdata event fires after the entry list representing the form's data is constructed. Also available via the onformdata property. reset The reset event fires when a form is reset. Also available via the onreset property. submit The submit event fires when a form is submitted. Also availabl...
HTMLImageElement.crossOrigin - Web APIs
d for all cross-origin loads. JavaScript The code below demonstrates setting the crossOrigin property on an <img> element to configure CORS access for the fetch of a newly-created image. const imageUrl = "https://mdn.mozillademos.org/files/16797/clock-demo-400px.png"; const container = document.querySelector(".container"); function loadImage(url) { const image = new Image(200, 200); image.addEventListener("load", () => container.prepend(image) ); image.addEventListener("error", () => { const errMsg = document.createElement("output"); errMsg.value = `Error loading image at ${url}`; container.append(errMsg); }); image.crossOrigin = "anonymous"; image.alt = ""; image.src = url; } loadImage(imageUrl); HTML <div class="container"> <p>Here's a paragraph. It's a very in...
HTMLImageElement.height - Web APIs
files/17374/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 300px"> JavaScript The JavaScript code looks at the height to determine the height of the image given the width at which it's currently drawn. var clockImage = document.querySelector("img"); let output = document.querySelector(".size"); const updateHeight = event => { output.innerText = clockImage.height; }; window.addEventListener("load", updateHeight); window.addEventListener("resize", updateHeight); Result This example may be easier to try out in its own window. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLImageElement.height' in that specification. Living Standard Browser compatibility The compatibility table on this page is gene...
HTMLImageElement.naturalHeight - Web APIs
. CSS .box { width: 200px; height: 200px; } .image { width: 100%; } .output { padding-top: 2em; } The main thing of note in the CSS above is that the style used for the container the image will be drawn in is 200px wide, and the image will be drawn to fill its width (100%). JavaScript let output = document.querySelector(".output"); let image = document.querySelector("img"); window.addEventListener("load", event => { output.innerHTML += `Natural size: ${image.naturalWidth} x ` + `${image.naturalHeight} pixels<br>`; output.innerHTML += `Displayed size: ${image.width} x ` + `${image.height} pixels`; }); The JavaScript code simply dumps the natural and as-displayed sizes into the <div> with the class output. This is done in response to the wind...
HTMLImageElement.naturalWidth - Web APIs
. CSS .box { width: 200px; height: 200px; } .image { width: 100%; } .output { padding-top: 2em; } The main thing of note in the CSS above is that the style used for the container the image will be drawn in is 200px wide, and the image will be drawn to fill its width (100%). JavaScript let output = document.querySelector(".output"); let image = document.querySelector("img"); window.addEventListener("load", event => { output.innerHTML += `Natural size: ${image.naturalWidth} x ` + `${image.naturalHeight} pixels<br>`; output.innerHTML += `Displayed size: ${image.width} x ` + `${image.height} pixels`; }); The JavaScript code simply dumps the natural and as-displayed sizes into the <div> with the class output. This is done in response to the wind...
HTMLImageElement.sizes - Web APIs
e handles the two buttons that let you toggle the third width option between 40em and 50em; this is done by handling the click event, using the JavaScript string object method replace() to replace the relevant portion of the sizes string. let image = document.querySelector("article img"); let break40 = document.getElementById("break40"); let break50 = document.getElementById("break50"); break40.addEventListener("click", event => image.sizes = image.sizes.replace(/50em,/, "40em,")); break50.addEventListener("click", event => image.sizes = image.sizes.replace(/40em,/, "50em,")); Result This result may be viewed in its own window here. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLImageElement.sizes' in that specification. ...
HTMLImageElement.width - Web APIs
200px, 400px"> JavaScript The JavaScript code looks at the width to determine the width of the image at the moment. This is done in the window's load and resize event handlers, in order to always provide this information. var clockImage = document.querySelector("img"); let output = document.querySelector(".size"); const updateWidth = event => { output.innerText = clockImage.width; }; window.addEventListener("load", updateWidth); window.addEventListener("resize", updateWidth); Result This example may be easier to try out in its own window. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLImageElement.width' in that specification. Living Standard Browser compatibility The compatibility table on this page is generat...
HTMLInputElement: invalid event - Web APIs
se of an invalid value in the input, the invalid value is logged. HTML <form action="#"> <ul> <li><label>Enter an integer between 1 and 10: <input type="number" min="1" max="10" required></label></li> <li><input type="submit" value="submit"></li> </ul> </form><p id="log"></p> JavaScript const input = document.querySelector('input') const log = document.getElementById('log') input.addEventListener('invalid', logValue) function logValue(e) { log.textContent += e.target.value } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'Invalid event' in that specification. Living Standard HTML 5.1The definition of 'Invalid event' in that specification. Recommendation HTML5The definition of 'Inv...
HTMLInputElement.labels - Web APIs
lement.labels read-only property returns a NodeList of the <label> elements associated with the <input> element. Syntax var labelElements = input.labels; Return value A NodeList containing the <label> elements associated with the <input> element. Example HTML <label id="label1" for="test">Label 1</label> <input id="test"/> <label id="label2" for="test">Label 2</label> JavaScript window.addEventListener("DOMContentLoaded", function() { const input = document.getElementById("test"); for(var i = 0; i < input.labels.length; i++) { console.log(input.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Standard No change ...
HTMLInputElement.stepDown() - Web APIs
Try it with 0, 5, -2, etc. */ input.stepDown(); } } CSS input:invalid { border: red solid 3px; } ...
HTMLInputElement.stepUp() - Web APIs
Try it with 0 */ input.stepUp() } } CSS input:invalid { border: red solid 3px; } Result Note if you don't...
HTMLInputElement.webkitEntries - Web APIs
is selected in the <input> element. More specifically, files are represented by FileSystemFileEntry objects, and, if they're allowed, directories are represented by FileSystemDirectoryEntry objects. Example This example shows how to create a file selection <input> element and process the selected files. HTML <input id="files" type="file" multiple> JavaScript document.getElementById("files").addEventListener("change", function(event) { event.target.webkitEntries.forEach(function(entry) { /* do stuff with the entry */ }); }); Each time a change event occurs, this code iterates over the selected files, obtaining their FileSystemEntry-based objects and acting on them. Specifications Specification Status Comment File and Directory Entries APIThe definition of 'webk...
HTMLInputElement.webkitdirectory - Web APIs
example, a directory picker is presented which lets the user choose one or more directories. When the change event occurs, a list of all files contained within the selected directory hierarchies is generated and displayed. ...
HTMLInputElement - Web APIs
nt type value., if the element has no step value, if the value cannot be converted to a number, if the resulting value is above the max or below the min. HTMLInputElement.mozGetFileNameArray() Returns an array of all the file names from the input. HTMLInputElement.mozSetFileNameArray() Sets the filenames for the files selected on the input. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface: input Fires when the value of an <input>, <select>, or <textarea> element has been changed. Note that this is actually fired on the HTMLElement interface and also applies to contenteditable elements, but we've listed it here because it is most commonly used with form input elements. Also available via the onin...
HTMLMediaElement: abort event - Web APIs
The abort event is fired when the resource was not fully loaded, but not as the result of an error. ...
HTMLMediaElement.captureStream() - Web APIs
ce for WebRTC. Example In this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the ID "playback" into a MediaStream. The stream can then be used for other purposes--like a source for streaming over WebRTC, to allow sharing prerecorded videos with another person during a video call. document.querySelector('.playAndRecord').addEventListener('click', function() { var playbackElement = document.getElementById("playback"); var captureStream = playbackElement.captureStream(); playbackElement.play(); }); See Recording a media element for a longer and more intricate example and explanation. Specifications Specification Status Comment Media Capture from DOM ElementsThe definition of 'captureStream()' in th...
HTMLMediaElement: emptied event - Web APIs
No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onemptied Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's emptied event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('emptied', (event) => { console.log('Uh oh. The media is empty. Did you call load()?'); }); Using the onemptied event handler property: const video = document.querySelector('video'); video.onemptied = (event) => { console.log('Uh oh. The media is empty. Did you call load()?'); }; Specifications Specificat...
HTMLMediaElement: error event - Web APIs
The error event is fired when the resource could not be loaded due to an error (for example, a network connectivity problem). ...
HTMLMediaElement: loadedmetadata event - Web APIs
only int The number of channels. mozSampleRate Read only int The sample rate per second. mozFrameBufferLength Read only int The number of samples collected in all channels. Examples These examples add an event listener for the HTMLMediaElement's loadedmetadata event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('loadedmetadata', (event) => { console.log('The duration and dimensions ' + ' of the media and tracks are now known. '); }); Using the onloadedmetadata event handler property: const video = document.querySelector('video'); video.onloadedmetadata = (event) => { console.log('The duration and dimensions ' + ' ...
HTMLMediaElement: loadstart event - Web APIs
deo { grid-area: video; } .event-log { grid-area: log; } .event-log>label { display: block; } JS const loadVideo = document.querySelector('button'); const video = document.querySelector('video'); const eventLog = document.querySelector('.event-log-contents'); let source = null; function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}\n`; } video.addEventListener('loadstart', handleEvent); video.addEventListener('progress', handleEvent); video.addEventListener('canplay', handleEvent); video.addEventListener('canplaythrough', handleEvent); loadVideo.addEventListener('click', () => { if (source) { document.location.reload(); } else { loadVideo.textContent = "Reset example"; source = document.createElement('source'); ...
HTMLMediaElement.networkState - Web APIs
ADING 2 The browser is downloading HTMLMediaElement data. NETWORK_NO_SOURCE 3 No HTMLMediaElement src found. Examples This example will listen for the audio element to begin playing and then check if it is still loading data. <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getElementById('example'); obj.addEventListener('playing', function() { if (obj.networkState === 2) { // Still loading... } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.networkState' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.networkState' in that specification. Recommendation ...
HTMLMediaElement: pause event - Web APIs
s No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onpause Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's pause event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('pause', (event) => { console.log('The Boolean paused property is now true. Either the ' + 'pause() method was called or the autoplay attribute was toggled.'); }); Using the onpause event handler property: const video = document.querySelector('video'); video.onpause = (event) => { console.log('The Boolean paused p...
HTMLMediaElement.play() - Web APIs
te response. For even more in-depth information about autoplay and autoplay blocking, see our article Autoplay guide for media and Web Audio APIs. ...
HTMLMediaElement: play event - Web APIs
les No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onplay Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's play event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('play', (event) => { console.log('The Boolean paused property is now false. Either the ' + 'play() method was called or the autoplay attribute was toggled.'); }); Using the onplay event handler property: const video = document.querySelector('video'); video.onplay = (event) => { console.log('The Boolean paused prop...
HTMLMediaElement: progress event - Web APIs
grid-area: video; } .event-log { grid-area: log; } .event-log>label { display: block; } JavaScript const loadVideo = document.querySelector('button'); const video = document.querySelector('video'); const eventLog = document.querySelector('.event-log-contents'); let source = null; function handleEvent(event) { eventLog.textContent = eventLog.textContent + `${event.type}\n`; } video.addEventListener('loadstart', handleEvent); video.addEventListener('progress', handleEvent); video.addEventListener('canplay', handleEvent); video.addEventListener('canplaythrough', handleEvent); loadVideo.addEventListener('click', () => { if (source) { document.location.reload(); } else { loadVideo.textContent = "Reset example"; source = document.createElement('source'); ...
HTMLMediaElement.readyState - Web APIs
played through to the end without interruption. Examples This example will listen for audio data to be loaded for the element `example`. It will then check if at least the current playback position has been loaded. If it has, the audio will play. <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getElementById('example'); obj.addEventListener('loadeddata', function() { if(obj.readyState >= 2) { obj.play(); } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.readyState' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.readyState' in that specification. Recommendation ...
HTMLMediaElement: timeupdate event - Web APIs
rget Element Default Action None Event handler property GlobalEventHandlers.ontimeupdate Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's timeupdate event, then post a message when that event handler has reacted to the event firing. Remember, the event frequency is dependant on the system load. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('timeupdate', (event) => { console.log('The currentTime attribute has been updated. Again.'); }); Using the ontimeupdate event handler property: const video = document.querySelector('video'); video.ontimeupdate = (event) => { console.log('The currentTime attribute has been updated. Again.'); }; Specifications ...
HTMLMediaElement - Web APIs
the source is simply set to the other element's currentSrc. This is optimized so this element gets access to all of the other element's cached and buffered data; in fact, the two elements share downloaded data, so data downloaded by either element is available to both. Events Inherits methods from its parent, HTMLElement , defined in the GlobalEventHandlers mixin. Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. abort Fired when the resource was not fully loaded, but not as the result of an error. canplay Fired when the user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content canplaythrough Fired when th...
HTMLMeterElement.labels - Web APIs
ns a NodeList of the <label> elements associated with the <meter> element. Syntax var labelElements = meter.labels; Return value A NodeList containing the <label> elements associated with the <meter> element. Example HTML <label id="label1" for="test">Label 1</label> <meter id="test" min="0" max="100" value="70">70</meter> <label id="label2" for="test">Label 2</label> JavaScript window.addEventListener("DOMContentLoaded", function() { const meter = document.getElementById("test"); for(var i = 0; i < meter.labels.length; i++) { console.log(meter.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Standard No change ...
HTMLOutputElement.labels - Web APIs
-only property returns a NodeList of the <label> elements associated with the <output> element. Syntax var labelElements = output.labels; Return value A NodeList containing the <label> elements associated with the <output> element. Example HTML <label id="label1" for="test">Label 1</label> <output id="test">Output</output> <label id="label2" for="test">Label 2</label> JavaScript window.addEventListener("DOMContentLoaded", function() { const output = document.getElementById("test"); for(var i = 0; i < output.labels.length; i++) { console.log(output.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Standard No change ...
HTMLProgressElement.labels - Web APIs
eList of the <label> elements associated with the <progress> element. Syntax var labelElements = progress.labels; Return value A NodeList containing the <label> elements associated with the <progress> element. Example HTML <label id="label1" for="test">Label 1</label> <progress id="test" value="70" max="100">70%</progress> <label id="label2" for="test">Label 2</label> JavaScript window.addEventListener("DOMContentLoaded", function() { const progress = document.getElementById("test"); for(var i = 0; i < progress.labels.length; i++) { console.log(progress.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Standard No change ...
HTMLSelectElement.disabled - Web APIs
Living Standard HTML5The definition of 'HTMLSelectElement' in that specification...
HTMLSelectElement.labels - Web APIs
th the <select> element. Syntax var labelElements = select.labels; Return value A NodeList containing the <label> elements associated with the <select> element. Example HTML <label id="label1" for="test">Label 1</label> <select id="test"> <option value="1">Option 1</option> <option value="2">Option 2</option> </select> <label id="label2" for="test">Label 2</label> JavaScript window.addEventListener("DOMContentLoaded", function() { const select = document.getElementById("test"); for(var i = 0; i < select.labels.length; i++) { console.log(select.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Standard No change ...
HTMLSelectElement.options - Web APIs
LOptionsCollection of the <option> elements contained by the <select> element. Syntax var options = select.options; Return value A HTMLOptionsCollection containing the <option> elements contained by the <select> element. Example HTML <label for="test">Label</label> <select id="test"> <option value="1">Option 1</option> <option value="2">Option 2</option> </select> JavaScript window.addEventListener("DOMContentLoaded", function() { const select = document.getElementById("test"); for(var i = 0; i < select.options.length; i++) { console.log(select.options[i].label); // "Option 1" and "Option 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'options' in that specification. Living Standard No change ...
HTMLSelectElement.selectedIndex - Web APIs
Living Standard No change since the latest snapshot, HTML5. HTML5The definition of 'HTML...
HTMLSelectElement.selectedOptions - Web APIs
it is to trigger fetching the HTMLCollection of selected elements using the selected property. ...
HTMLSelectElement - Web APIs
the user. If there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true. HTMLSelectElement.setCustomValidity() Sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does not have a custom validity error. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface: input event Fires when the value of an <input>, <select>, or <textarea> element has been changed. Example Get information about the selected option /* assuming we have the following HTML <select id='s'> <option>First</option> <option selected>Second</option> <option>Third</option> </select> */ ...
HTMLSlotElement.assignedNodes() - Web APIs
r the nodes to be returned. The available options are: flatten: A Boolean indicating whether to return the assigned nodes of any available child <slot> elements (true) or not (false). Defaults to false. Return value An array of nodes. Examples The following snippet is taken from our slotchange example (see it live also). let slots = this.shadowRoot.querySelectorAll('slot'); slots[1].addEventListener('slotchange', function(e) { let nodes = slots[1].assignedNodes(); console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outerHTML + '".'); }); Here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template -- which is the one that keeps having its contents changed in the example. Every time the element inserted in the s...
HTMLSlotElement.name - Web APIs
of the HTMLSlotElement interface returns or sets the slot name. A slot is a placeholder inside a web component that users can fill with their own markup. Syntax var name = htmlSlotElement.name htmlSlotElement.name = name Value A DOMString. Examples The following snippet is taken from our slotchange example (see it live also). let slots = this.shadowRoot.querySelectorAll('slot'); slots[1].addEventListener('slotchange', function(e) { let nodes = slots[1].assignedNodes(); console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outerHTML + '".'); }); Here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template -- which is the one that keeps having its contents changed in the example. Every time the element inserted in the s...
HTMLSlotElement: slotchange event - Web APIs
roperty None In order to trigger a slotchange event, one has to set or remove the slot attribute. Examples element.setAttribute('slot', slotName); // element.assignedSlot = $slot element.removeAttribute('slot'); // element.assignedSlot = null The following snippet is taken from our slotchange example (see it live also). let slots = this.shadowRoot.querySelectorAll('slot'); slots[1].addEventListener('slotchange', function(e) { let nodes = slots[1].assignedNodes(); console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outerHTML + '".'); }); Here we grab references to all the <slot>s, then add a slotchange event listener to the template's second slot -- which is the one which has its contents changed in the example. Every time the element inserted in the slot chan...
HTMLSlotElement - Web APIs
other slots that are descendants of this slot. If no assigned nodes are found, it returns the slot's fallback content. Events slotchange Fired on an HTMLSlotElement instance (<slot> element) when the node(s) contained in that slot change. Examples The following snippet is taken from our slotchange example (see it live also). let slots = this.shadowRoot.querySelectorAll('slot'); slots[1].addEventListener('slotchange', function(e) { let nodes = slots[1].assignedNodes(); console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outerHTML + '".'); }); Here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template -- which is the one that keeps having its contents changed in the example. Every time the element inserted in the s...
HTMLTextAreaElement.labels - Web APIs
y returns a NodeList of the <label> elements associated with the <textarea> element. Syntax var labelElements = textArea.labels; Return value A NodeList containing the <label> elements associated with the <textArea> element. Example HTML <label id="label1" for="test">Label 1</label> <textArea id="test">Some text</textArea> <label id="label2" for="test">Label 2</label> JavaScript window.addEventListener("DOMContentLoaded", function() { const textArea = document.getElementById("test"); for(var i = 0; i < textArea.labels.length; i++) { console.log(textArea.labels[i].textContent); // "Label 1" and "Label 2" } }); Specifications Specification Status Comment HTML Living StandardThe definition of 'labels' in that specification. Living Standard No change ...
HTMLTextAreaElement - Web APIs
DOMstring) Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. The two methods blur() and focus() are inherited from HTMLElement from HTML5 on, but were defined on HTMLTextAreaElement in DOM Level 2 HTML and earlier specifications. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface: input event Fires when the value of an <input>, <select>, or <textarea> element has been changed. Examples Autogrowing textarea example Make a textarea autogrow while typing: JavaScript function autoGrow (oField) { if (oField.scrollHeight > oField.clientHeight) { oField.style.height = oField.scrollH...
HTMLVideoElement.msHorizontalMirror - Web APIs
ay be useful for playback of a webcam video, providing the user with better mirroring of their real behaviors (ie. ...
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
Web › API › History › back
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
Web › API › History › forward
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. ...
IDBOpenDBRequest - Web APIs
onaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">IDBOpenDBRequest</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Also inherits methods from its parents IDBRequest and EventTarget. Methods No methods, but inherits methods from its parents IDBRequest and EventTarget. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. blocked Fired when an open connection to a database is blocking a versionchange transaction on the same database. Also available via the onblocked property. upgradeneeded Fired when an attempt was made to open a database with a version number higher than its current version. Also available via the onupgradene...
IDBRequest - Web APIs
ly or when an error occurs. IDBRequest.transaction Read only The transaction for the request. This property can be null for certain requests, for example those returned from IDBFactory.open unless an upgrade is needed. (You're just connecting to a database, so there is no transaction to return). Methods No methods, but inherits methods from EventTarget. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. error Fired when an error caused a request to fail. Also available via the onerror property. success Fired when an IDBRequest succeeds. Also available via the onsuccess property. Example In the following code snippet, we open a database asynchronously and make a request; onerror and onsuccess functions a...
IDBTransaction: abort event - Web APIs
{ unique: 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 `abort` transaction.addEventListener('abort', () => { console.log('Transaction was aborted'); }); // abort the transaction transaction.abort(); }; The same example, but assigning the event handler to the onabort property: // Open the database const DBOpenRequest = window.indexedDB.open('toDoList', 4); DBOpenRequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('...
IDBTransaction: error event - Web APIs
ore.createIndex('day', 'day', { unique: 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'); transaction.addEventListener('error', () => { console.log(`Error adding new item: ${newItem.taskTitle}`); }); const objectStore = transaction.objectStore('toDoList'); const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2020 }; const objectStoreRequest = objectStore.add(newItem); }; The same example, using the onerror property instead of addEventListener(): // Open...
IDBTransaction - Web APIs
commit() For an active transaction, commits the transaction. Note that this doesn't normally have to be called -- a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made. commit() can be used to start the commit process without waiting for events from outstanding requests to be dispatched. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. abort Fired when an IndexedDB transaction is aborted. Also available via the onabort property. complete Fired when a transaction successfully completes. Also available via the oncomplete property. error Fired when a request returns an error and the event bubbles up to the transaction object. Also availab...
ImageCapture - Web APIs
Working Draft Initial definition. ...
Basic concepts - Web APIs
lets you know if the operation succeeded or failed. This sounds a little complicated at first, but there are sanity measures baked in. It's not that different from the way that XMLHttpRequest works. IndexedDB uses a lot of requests. Requests are objects that receive the success or failure DOM events that were mentioned previously. They have onsuccess and onerror properties, and you can call addEventListener() and removeEventListener() on them. They also have readyState, result, and errorCode properties that tell you the status of the request. The result property is particularly magical, as it can be many different things, depending on how the request was generated (for example, an IDBCursor instance, or the key for a value that you just inserted into the database). IndexedDB uses DOM events to...
firesTouchEvents - Web APIs
uch events. You can use this property to detect mouse events that represent an action that may already have been handled by touch event handlers. This doesn't necessarily mean the device is a touch screen. For example, stylus and mouse devices typically generate touch events on mobile browsers. Syntax var boolean = InputDeviceCapabilities.firesTouchEvents Returns A Boolean Example myButton.addEventListener('mousedown', function(e) { if (!e.sourceCapabilities.firesTouchEvents) myButton.classList.add("pressed"); }); Specifications Specification Status Comment InputDeviceCapabilitiesThe definition of 'fireTouchEvents' in that specification. Draft Initial definition. ...
InputDeviceCapabilities API - Web APIs
ements both a touchstart and a mousedown event. We can assume that if the touchstart event is triggered that the user's device has a touch interface. What about when the mousedown event is triggered? It would be useful to know if a touchstart event were also triggered so that we don't take the same action twice. We can do this by checking the sourceCapabilities property of the UIEvent. myButton.addEventListener('mousedown', function(e) { // Touch event case handled above, don't change the style again on tap. if (!e.sourceCapabilities.firesTouchEvents) myButton.classList.add("pressed"); }); Interfaces InputDeviceCapabilities Provides logical information about an input device. Specifications Specification Status Comment InputDeviceCapabilities Draft Initial de...
InputEvent.data - Web APIs
Web › API › InputEvent › data
when any change is made to the contents of the <input> element (either by typing or pasting), the text that was added is retrieved via the InputEvent.data property and reported in the paragraph below the input. <p>Some text to copy and paste.</p> <input type="text"> <p class="result"></p> var editable = document.querySelector('input') var result = document.querySelector('.result'); editable.addEventListener('input', (e) => { result.textContent = "Inputted text: " + e.data; }); Specifications Specification Status Comment Input Events Level 2The definition of 'data' in that specification. Working Draft Initial definition. ...
InputEvent.dataTransfer - Web APIs
Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribut...
InputEvent.inputType - Web APIs
;border:2px dashed red;"> <p>Some sample text. Try inserting line breaks, or deleting text in different ways, or pasting different content in.</p> <hr> <ul> <li>A sample</li> <li>bulleted</li> <li>list.</li> </ul> <p>Another paragraph.</p> </div> JavaScript const log = document.getElementById('log'); const editable = document.querySelector('div[contenteditable]'); editable.addEventListener('input', logInputType); function logInputType(event) { log.textContent = `Input type: ${event.inputType}`; } Result Try editing the text inside the <div> and see what happens. Note: See also Masayuki Nakano's InputEvent test suite for a more detailed example. Specifications Specification Status Comment UI EventsThe definition of 'inputType' in that specificati...
InstallEvent.activeWorker - Web APIs
The activeWorker read-only property of the InstallEvent interface returns the ServiceWorker that is currently actively controlling the page. This will return null if no active worker is already controlling the page. Syntax var myActiveWorker = event.activeWorker Value A ServiceWorker object. Examples self.addEventListener('install', function(event) { var myActiveWorker = event.activeWorker; }); ...
InstallEvent - Web APIs
you can use this approach for multiple caches. The code maps a shorthand identifier for a cache to a specific, versioned cache name. Note: Logging statements are visible in Google Chrome via the "Inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals. var CACHE_VERSION = 1; var CURRENT_CACHES = { prefetch: 'prefetch-cache-v' + CACHE_VERSION }; self.addEventListener('install', function(event) { var urlsToPrefetch = [ './static/pre_fetched.txt', './static/pre_fetched.html', 'https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif' ]; console.log('Handling install event. Resources to pre-fetch:', urlsToPrefetch); event.waitUntil( caches.open(CURRENT_CACHES['prefetch']).then(function(cache) { return cache.addAll(urlsToP...
KeyboardEvent.charCode - Web APIs
he key property instead. Syntax var code = event.charCode; Return value A number that represents the Unicode value of the character key that was pressed. Example HTML <p>Type anything into the input box below to log a <code>charCode</code>.</p> <input type="text" /> <p id="log"></p> JavaScript let input = document.querySelector('input'); let log = document.querySelector('#log'); input.addEventListener('keypress', function(e) { log.innerText = `Key pressed: ${String.fromCharCode(e.charCode)}\ncharCode: ${e.charCode}`; }); Result Notes In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, but never both. If the key pressed generates a character (e.g., 'a'), charCode is set to the code of that character; charCode respects the lett...
KeyboardEvent.keyCode - Web APIs
Code attribute for printable characters when handling keydown and keyup events. As described above, the keyCode attribute is not useful for printable characters, especially those input with the Shift or Alt key pressed. When implementing a shortcut key handler, the keypress event is usually better (at least when Gecko is the runtime in use). See Gecko Keypress Event for details. Example window.addEventListener("keydown", function (event) { if (event.defaultPrevented) { return; // Should do nothing if the default action has been cancelled } var handled = false; if (event.key !== undefined) { // Handle the event with KeyboardEvent.key and set handled true. } else if (event.keyCode !== undefined) { // Handle the event with KeyboardEvent.keyCode and set handled true. } if (handl...
LargestContentfulPaint - Web APIs
// Update `lcp` to the latest value, using `renderTime` if it's available, // otherwise using `loadTime`. (Note: `renderTime` may not be available on // image elements loaded cross-origin without the `Timing-Allow-Origin` header.) lcp = lastEntry.renderTime || lastEntry.loadTime; }); po.observe({type: 'largest-contentful-paint', buffered: true}); // Send data to the server. addEventListener('visibilitychange', function fn() { if (lcp && document.visibilityState === 'hidden') { console.log('LCP:', lcp); removeEventListener('visibilitychange', fn, true); } }, true); } catch (e) { // Do nothing if the browser doesn't support this API. } Specifications Specification Status Comment Largest Contentful PaintThe definition of 'LargestConten...
LayoutShift - Web APIs
org/show_bug.cgi?id=209216 try { let cumulativeLayoutShiftScore = 0; const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { // Only count layout shifts without recent user input. if (!entry.hadRecentInput) { cumulativeLayoutShiftScore += entry.value; } } }); observer.observe({type: 'layout-shift', buffered: true}); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') { // Force any pending records to be dispatched. observer.takeRecords(); observer.disconnect(); console.log('CLS:', cumulativeLayoutShiftScore); } }); } catch (e) { // Do nothing if the browser doesn't support this API. } Specifications Specification Status Comment Layout Ins...
LinearAccelerationSensor.x - Web APIs
something that would ever be shown to a user. See Feature-Policy for implementation instructions. Syntax var xLinearAccelerationSensor = linearAccelerationSensor.x Value A Number. Example Linear acceleration is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let laSensor = new LinearAccelerationSensor({frequency: 60}); laSensor.addEventListener('reading', e => { console.log("Linear acceleration along the X-axis " + laSensor.x); console.log("Linear acceleration along the Y-axis " + laSensor.y); console.log("Linear acceleration along the Z-axis " + laSensor.z); }); laSensor.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
LinearAccelerationSensor.y - Web APIs
ur server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions. Syntax var yAcceleration = accelerometer.y Value A Number. Example Linear acceleration is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let laSensor = new LinearAccelerationSensor({frequency: 60}); laSensor.addEventListener('reading', e => { console.log("Linear acceleration along the X-axis " + laSensor.x); console.log("Linear acceleration along the Y-axis " + laSensor.y); console.log("Linear acceleration along the Z-axis " + laSensor.z); }); laSensor.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
LinearAccelerationSensor.z - Web APIs
ur server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions. Syntax var zAcceleration = accelerometer.z Value A Number. Example Linear acceleration is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let laSensor = new LinearAccelerationSensor({frequency: 60}); laSensor.addEventListener('reading', e => { console.log("Linear acceleration along the X-axis " + laSensor.x); console.log("Linear acceleration along the Y-axis " + laSensor.y); console.log("Linear acceleration along the Z-axis " + laSensor.z); }); laSensor.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
LinearAccelerationSensor - Web APIs
leration of the device along the device's y axis. LinearAccelerationSensor.z Read only Returns a double containing the linear acceleration of the device along the device's z axis. Example Linear acceleration is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. let laSensor = new LinearAccelerationSensor({frequency: 60}); laSensor.addEventListener('reading', e => { console.log("Linear acceleration along the X-axis " + laSensor.x); console.log("Linear acceleration along the Y-axis " + laSensor.y); console.log("Linear acceleration along the Z-axis " + laSensor.z); }); laSensor.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. ...
Location - Web APIs
Web › API › Location
e:40%; line-height:1.5; background:black;} [title]:hover:before, :target:before {background:black; color:yellow;} [title] [title]:before {margin-top:1.5em;} [title] [title] [title]:before {margin-top:3em;} [title]:hover, :target {position:relative; z-index:1; outline:50em solid rgba(255,255,255,.8);} JavaScript [].forEach.call(document.querySelectorAll('[title][id]'), function (node) { node.addEventListener("click", function(e) { e.preventDefault(); e.stopPropagation(); window.location.hash = '#' + $(this).attr('id'); }); }); [].forEach.call(document.querySelectorAll('[title]'), function (node) { node.addEventListener("click", function(e) { e.preventDefault(); e.stopPropagation(); window.location.hash = ''; }); }); Result Properties Location.ancestorOrigins Is a...
MSCandidateWindowHide - 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.oncandidatewindowhide = handler; addEventListener Method object.addEventListener("MSCandidateWindowHide", handler, useCapture) nbsp; Parameters pEvtObj [in] Type: IHTMLEventObj Pointer to an IHTMLEventObj interface for the current event. The handler of this event will see that the isCandidateWindowVisible method returns false, and no ClientRect object is returned from getCandidateWindowClientRect. Web applications need only regis...
MSCandidateWindowUpdate - Web APIs
ternet 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.oncandidatewindowupdate = handler; addEventListener Method object.addEventListener("MSCandidateWindowUpdate", handler, useCapture) Parameters pEvtObj [in] Type: IHTMLEventObj Pointer to an IHTMLEventObj interface for the current event. TAn IME candidate window may be identified as needing to change size for any of the following reasons: As a result of displaying new / changed alternatives or predictions Web applications need on...
Magnetometer.x - Web APIs
Web › API › Magnetometer › x
cies set on your server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions. Syntax var magnetometerx = magnetometer.x Value A Number. Example The magnetometer is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. 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.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. Magnet...
Magnetometer.y - Web APIs
Web › API › Magnetometer › y
cies set on your server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions. Syntax var magnetometery = magnetometer.x Value A Number. Example The magnetometer is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. 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.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. Magnet...
Magnetometer.z - Web APIs
Web › API › Magnetometer › z
cies set on your server. This is not something that would ever be shown to a user. See Feature-Policy for implementation instructions. Syntax var magnetometerz = magnetometer.z Value A Number. Example The magnetometer is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. 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.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. Magnet...
Magnetometer - Web APIs
ter.y Read only Returns a double containing the magnetic field around the device's y axis. Magnetometer.z Read only Returns a double containing the magnetic field around the device's z axis. Example The magnetometer is typically read in the Sensor.onreading event callback. In the example below this occurs sixty times a second. 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.start(); Specifications Specification Status Comment Generic Sensor API Candidate Recommendation Defines sensors in general. Magnet...
MediaDevices: devicechange event - Web APIs
A devicechange event is sent to a MediaDevices instance whenever a media device such as a camera, microphone, or speaker is connected to or removed from the system. It's a generic Event with no added properties. Bubbles No Cancelable No Interface Event Event handler ondevicechange Example You can use the devicechange event in an addEventListener method: navigator.mediaDevices.addEventListener('devicechange', function(event) { updateDeviceList(); }); Or use the ondevicechange event handler property: navigator.mediaDevices.ondevicechange = function(event) { updateDeviceList(); } Specifications Specification Status Media Capture and StreamsThe definition of 'devicechange' in that specification. Candidate Recommenda...
MediaDevices.ondevicechange - Web APIs
padding: 6px; } JavaScript content Other code Below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail. ...
MediaQueryList.addListener() - Web APIs
The addListener() method of the MediaQueryList interface adds a listener to the MediaQueryListener that will run a custom callback function in response to the media query status changing. This is basically an alias for EventTarget.addEventListener(), for backwards compatibility purposes. Older browsers should use addListener instead of addEventListener since MediaQueryList only inherits from EventTarget in newer browsers. Syntax MediaQueryList.addListener(func) Parameters func A function or function reference representing the callback function you want to run when the media query status changes. In the original implementation, the callback was a non-standard MediaQueryListListener object. In the new implementation the standard event mechanism is used, the callback is a standard function, and the ...
MediaQueryList.onchange - Web APIs
representing a function that is invoked when the change event fires, i.e when the status of media query support changes. The event object is a MediaQueryListEvent instance, which is recognised as a MediaListQuery instance in older browsers, for backwards compatibility purposes. Syntax MediaQueryList.onchange = function() { ... ...
MediaRecorder.ondataavailable - Web APIs
lled every second with a blob of media data that's one second long. You can use timeslice alongside MediaRecorder.stop() and MediaRecorder.requestData() to produce multiple same-length blobs plus other shorter blobs as well. The Blob containing the media data is available in the dataavailable event's data property. Syntax MediaRecorder.ondataavailable = function(event) { ... } MediaRecorder.addEventListener('dataavailable', function(event) { ... }) Example ... var chunks = []; mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.s...
MediaRecorder.onpause - Web APIs
}) Example ... ...
MediaRecorder.onresume - Web APIs
}) Example ... ...
MediaRecorder.onstart - Web APIs
diaRecorder.onstartevent handler (part of the MediaRecorder API) handles the start event, allowing you to run code in response to media recording being started by a MediaRecorder. The start event is thrown as a result of the MediaRecorder.start() method being invoked. At this point, the data starts being gathered into a Blob. Syntax MediaRecorder.onstart = function(event) { ... } MediaRecorder.addEventListener('start', function(event) { ... }) Example ... record.onclick = function() { mediaRecorder.start(); console.log("recorder started"); } mediaRecorder.onstart = function() { // do something in response to // recording being started } ... Properties None. Specifications Specification Status Comment MediaStream RecordingThe definition of 'MediaR...
MediaRecorder.onstop - Web APIs
ia a MediaRecorder being stopped. The stop event is thrown either as a result of the MediaRecorder.stop() method being invoked, or when the media stream being captured ends. In each case, the stop event is preceded by a dataavailable event, making the Blob captured up to that point available for you to use in your application. Syntax MediaRecorder.onstop = function(event) { ... } MediaRecorder.addEventListener('stop', function(event) { ... }) Example ... mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.lo...
MediaRecorder.onwarning - Web APIs
The MediaRecorder.onwarning event handler (part of the MediaRecorder API) handles the recordingwarning event, allowing you to run code in response to non-fatal errors being thrown during media recording via a MediaRecorder, which don't halt recording. Syntax mediaRecorder.onwarning = function(event) { ... } mediaRecorder.addEventListener('warning', function(event) { ... }) Example ... mediaRecorder.onwarning = function(e) { console.log("A warning has been raised: " + e.message); } ... Properties message Contains information about the error that occurred. ...
MediaRecorder - Web APIs
media recording resumes after being paused. MediaRecorder.onstart An EventHandler called to handle the start event, which occurs when media recording starts. MediaRecorder.onstop An EventHandler called to handle the stop event, which occurs when media recording ends, either when the MediaStream ends -- or after the MediaRecorder.stop() method is called. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. error Fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. Also available via the onerror property. Example if (navigator.mediaDevices) { console.log('getUserMedia supported.'); var constraints = { audio: true }; var chunks = []; nav...
MediaSource.MediaSource() - Web APIs
...
MediaSource.activeSourceBuffers - Web APIs
h of the active tracks. Example The following snippet is based on a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation.) function sourceOpen (_) { //console.log(this.readyState); // open var mediaSource = this; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); fetchAB(assetURL, function (buf) { sourceBuffer.addEventListener('updateend', function (_) { mediaSource.endOfStream(); console.log(mediaSource.activeSourceBuffers); // will contain the source buffer that was added above, // as it is selected for playing in the video player video.play(); //console.log(mediaSource.readyState); // ended }); sourceBuffer.appendBuffer(buf); }); }; ... Specifications Specifi...
MediaSource.addSourceBuffer() - Web APIs
RL = 'frag_bunny.mp4'; // Need to be specific for Blink regarding codecs // ./mp4info frag_bunny.mp4 | grep Codec var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'; if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) { var mediaSource = new MediaSource; //console.log(mediaSource.readyState); // closed video.src = URL.createObjectURL(mediaSource); mediaSource.addEventListener('sourceopen', sourceOpen); } else { console.error('Unsupported MIME type or codec: ', mimeCodec); } function sourceOpen (_) { //console.log(this.readyState); // open var mediaSource = this; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); fetchAB(assetURL, function (buf) { sourceBuffer.addEventListener('updateend', function (_) { mediaSource.endOfStream(); vid...
MediaSource.duration - Web APIs
Specifications Specification Status Comment Media Source ExtensionsThe definition of 'duration' in that specification. Recommendation Initia...
MediaSource.endOfStream() - Web APIs
RL = 'frag_bunny.mp4'; // Need to be specific for Blink regarding codecs // ./mp4info frag_bunny.mp4 | grep Codec var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'; if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) { var mediaSource = new MediaSource; //console.log(mediaSource.readyState); // closed video.src = URL.createObjectURL(mediaSource); mediaSource.addEventListener('sourceopen', sourceOpen); } else { console.error('Unsupported MIME type or codec: ', mimeCodec); } function sourceOpen (_) { //console.log(this.readyState); // open var mediaSource = this; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); fetchAB(assetURL, function (buf) { sourceBuffer.addEventListener('updateend', function (_) { mediaSource.endOfStream(); vid...
MediaSource.isTypeSupported() - Web APIs
RL = 'frag_bunny.mp4'; // Need to be specific for Blink regarding codecs // ./mp4info frag_bunny.mp4 | grep Codec var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'; if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) { var mediaSource = new MediaSource; //console.log(mediaSource.readyState); // closed video.src = URL.createObjectURL(mediaSource); mediaSource.addEventListener('sourceopen', sourceOpen); } else { console.error('Unsupported MIME type or codec: ', mimeCodec); } function sourceOpen (_) { //console.log(this.readyState); // open var mediaSource = this; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); fetchAB(assetURL, function (buf) { sourceBuffer.addEventListener('updateend', function (_) { mediaSource.endOfStream(); vid...
MediaSource.sourceBuffers - Web APIs
ue A SourceBufferList. Example The following snippet is based on a simple example written by Nick Desaulniers (view the full demo live, or download the source for further investigation.) function sourceOpen (_) { //console.log(this.readyState); // open var mediaSource = this; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); fetchAB(assetURL, function (buf) { sourceBuffer.addEventListener('updateend', function (_) { mediaSource.endOfStream(); console.log(mediaSource.sourceBuffers); // will contain the source buffer that was added above video.play(); //console.log(mediaSource.readyState); // ended }); sourceBuffer.appendBuffer(buf); }); }; ... Specifications Specification Status Comment Media Source ExtensionsThe definiti...
MediaSource - Web APIs
= 'frag_bunny.mp4'; // Need to be specific for Blink regarding codecs // ./mp4info frag_bunny.mp4 | grep Codec var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'; if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) { var mediaSource = new MediaSource(); //console.log(mediaSource.readyState); // closed video.src = URL.createObjectURL(mediaSource); mediaSource.addEventListener('sourceopen', sourceOpen); } else { console.error('Unsupported MIME type or codec: ', mimeCodec); } function sourceOpen (_) { //console.log(this.readyState); // open var mediaSource = this; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); fetchAB(assetURL, function (buf) { sourceBuffer.addEventListener('updateend', function (_) { mediaSource.endOfStream(); vid...
MediaStream: addtrack event - Web APIs
The addtrack event is fired when a new MediaStreamTrack object has been added to a MediaStream. Bubbles No Cancelable No Interface MediaStreamTrackEvent Event handler property onaddtrack Examples Using addEventListener(): let stream = new MediaStream(); stream.addEventListener('addtrack', (event) => { console.log(`New ${event.track.kind} track added`); }); Using the onaddtrack event handler property: let stream = new MediaStream(); stream.onaddtrack = (event) => { console.log(`New ${event.track.kind} track added`); }; Specifications Specification Status Media Capture and StreamsThe definition of 'addtrack' in that specification. Candidate Recommendation ...
MediaStream: removetrack event - Web APIs
The removetrack event is fired when a new MediaStreamTrack object has been removed from a MediaStream. Bubbles No Cancelable No Interface MediaStreamTrackEvent Event handler property onremovetrack Examples Using addEventListener(): let stream = new MediaStream(); stream.addEventListener('removetrack', (event) => { console.log(`${event.track.kind} track removed`); }); Using the onremovetrack event handler property: let stream = new MediaStream(); stream.onremovetrack = (event) => { console.log(`${event.track.kind} track removed`); }; Specifications Specification Status Media Capture and StreamsThe definition of 'removetrack' in that specification. Candidate Recommendation ...
MediaStreamTrack: ended event - Web APIs
end. The user revoked the permissions needed for the data to be sent. The hardware generating the source data has been removed or ejected. A remote peer has permanently stopped sending data; pausing media does not generate an ended event. Examples This example sets up an event handler for the ended event, which changes an on-screen icon to indicate that the track is no longer active. ...
MediaStreamTrack - Web APIs
nstraints last set using applyConstraints(). MediaStreamTrack.getSettings() Returns a MediaTrackSettings object containing the current values of each of the MediaStreamTrack's constrainable properties. MediaStreamTrack.stop() Stops playing the source associated to the track, both the source and the track are deassociated. The track state is set to ended. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface: ended Sent when playback of the track ends (when the value readyState changes to ended). Also available using the onended event handler property. mute Sent to the MediaStreamTrack when the value of the muted property is changed to true, indicating that the track is unable to provide data temporarily (such as...
Using the Media Capabilities API - Web APIs
= document.getElementById("results") li.innerHTML = content; ul.appendChild(li); }).catch((error) => { var li = document.createElement('li'), ul = document.getElementById("results"); li.innerText = 'Codec ' + mc.videoConfiguration.video.contentType + ' threw an error: ' + error; ul.appendChild(li); }); } } document.getElementById('tryit').addEventListener('click', mc.tryit); Live Result ...
Media Session API - Web APIs
oustrack', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('nexttrack', function() { /* Code excerpted. */ }); } Some user agents disable autoplay for media elements on mobile devices and require a user gesture to start media. The following example adds a pointerup event to an on-page play button, which is then used to kick off the media session code: playButton.addEventListener('pointerup', function(event) { var audio = document.querySelector('audio'); // User interacted with the page. Let's play audio... audio.play() .then(_ => { /* Set up media session controls, as shown above. */ }) .catch(error => { console.log(error) }); }); Specifications Specification Status Comment Media Session Standard Draft Initial definition. ...
MessageChannel() - Web APIs
ng with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment ...
MessageChannel.port1 - Web APIs
The handleMessage handler then responds to a message being sent back from the <iframe> (using MessagePort.onmessage), putting it into a paragraph. The handleMessage method is associated to the port1 to listen when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } Specifications Specification Status Comment HTML Living StandardThe definition of 'port1' in that specification. Living Standard ...
MessageChannel.port2 - Web APIs
ng with a message. The handleMessage handler then responds to a message being sent back from the IFrame (using MessagePort.onmessage), putting it into a paragraph. MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment ...
MessageChannel - Web APIs
.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. ...
MessageEvent.ports - Web APIs
rty of the MessageEvent interface is an array of MessagePort objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). Syntax var myPorts = messageEvent.ports; Value An array of MessagePort objects. Example onconnect = function(e) { var port = e.ports[0]; port.addEventListener('message', function(e) { var workerResult = 'Result: ' + (e.data[0] * e.data[1]); port.postMessage(workerResult); }); port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter. } Specifications Specification Status Comment HTML Living StandardThe definition of 'ports' in that specification. Living Standard I...
MessagePort.close() - Web APIs
Web › API › MessagePort › close
he close() method of the MessagePort interface disconnects the port, so it is no longer active. This stops the flow of messages to that port. Note: This feature is available in Web Workers. Syntax port.close() Returns Void. Parameters None. Example In the following code block, you can see a handleMessage handler function, run when a message is sent back to this document using EventTarget.addEventListener. channel.port1.addEventListener('message', handleMessage, false); function handleMessage(e) { para.innerHTML = e.data; textInput.value = ''; } channel.port1.start(); You could stop messages being sent at any time using channel.port1.close(); Specifications Specification Status Comment HTML Living StandardThe definition of 'close()' in that specification. Livi...
MessagePort.onmessage - Web APIs
tMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment ...
MessagePort.postMessage() - Web APIs
tMessage along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph -- MessageChannel.port1 is listened to, to check when the message arrives. var channel = new MessageChannel(); var para = document.querySelector('p'); var ifr = document.querySelector('iframe'); var otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } For a full working example, see our channel messaging basic demo on Github (run it live too). Specifications Specification Status Comment ...
MouseEvent.altKey - Web APIs
Web › API › MouseEvent › altKey
r altKeyPressed = instanceOfMouseEvent.altKey Return value A Boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. Example This example logs the altKey property when you trigger a click event. HTML <p>Click anywhere to test the <code>altKey</code> property.</p> <p id="log"></p> JavaScript let log = document.querySelector('#log'); document.addEventListener('click', logKey); function logKey(e) { log.textContent = `The alt key is pressed: ${e.altKey}`; } Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.altkey' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Events Specification. Docu...
MouseEvent.button - Web APIs
Web › API › MouseEvent › button
keyboard or other input mechanisms to indicate main, secondary, auxilary, etc. Others may have many buttons mapped to different functions and button values. ...
MouseEvent.buttons - Web APIs
ward" button) Example This example logs the buttons property when you trigger a mousedown event. HTML <p>Click anywhere with one or more mouse buttons.</p> <pre id="log">buttons: </pre> JavaScript let log = document.createTextNode('?'); // let log = new Text('?'); function logButtons(e) { log.data = `${e.buttons} (${e.type})`; // log.nodeValue= `${e.buttons} (${e.type})`; } document.addEventListener('mouseup', logButtons); document.addEventListener('mousedown', logButtons); // document.addEventListener('mousemove', logButtons); document.querySelector('#log').appendChild(log) Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.buttons' in that specification. Obsolete Initia...
MouseEvent.clientX - Web APIs
as redefined by the CSSOM View Module. Originally, this property was defined as a long integer. See the "Browser compatibility" section for details. Example This example displays your mouse's coordinates whenever you trigger the mousemove event. HTML <p>Move your mouse to see its position.</p> <p id="screen-log"></p> JavaScript let screenLog = document.querySelector('#screen-log'); document.addEventListener('mousemove', logKey); function logKey(e) { screenLog.innerText = ` Screen X/Y: ${e.screenX}, ${e.screenY} Client X/Y: ${e.clientX}, ${e.clientY}`; } Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'clientX' in that specification. Working Draft Redefines MouseEvent from long to double. D...
MouseEvent.clientY - Web APIs
as redefined by the CSSOM View Module. Originally, this property was defined as a long integer. See the "Browser compatibility" section for details. Example This example displays your mouse's coordinates whenever you trigger the mousemove event. HTML <p>Move your mouse to see its position.</p> <p id="screen-log"></p> JavaScript let screenLog = document.querySelector('#screen-log'); document.addEventListener('mousemove', logKey); function logKey(e) { screenLog.innerText = ` Screen X/Y: ${e.screenX}, ${e.screenY} Client X/Y: ${e.clientX}, ${e.clientY}`; } Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'clientY' in that specification. Working Draft Redefines MouseEvent from long to double. D...
MouseEvent.ctrlKey - Web APIs
rlKeyPressed = instanceOfMouseEvent.ctrlKey Return value A Boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. Example This example logs the ctrlKey property when you trigger a click event. HTML <p>Click anywhere to test the <code>ctrlKey</code> property.</p> <p id="log"></p> JavaScript let log = document.querySelector('#log'); document.addEventListener('click', logKey); function logKey(e) { log.textContent = `The ctrl key is pressed: ${e.ctrlKey}`; } Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.ctrlKey' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Events Specification. D...
MouseEvent.metaKey - Web APIs
taKeyPressed = instanceOfMouseEvent.metaKey Return value A Boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. Example This example logs the metaKey property when you trigger a click event. HTML <p>Click anywhere to test the <code>metaKey</code> property.</p> <p id="log"></p> JavaScript let log = document.querySelector('#log'); document.addEventListener('click', logKey); function logKey(e) { log.textContent = `The meta key is pressed: ${e.metaKey}`; } Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.metaKey' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Events Specification. D...
MouseEvent.movementX - Web APIs
A number Example This example logs the amount of mouse movement using movementX and movementY. HTML <p id="log">Move your mouse around.</p> JavaScript function logMovement(event) { log.insertAdjacentHTML('afterbegin', `movement: ${event.movementX}, ${event.movementY}<br>`); while (log.childNodes.length > 128) log.lastChild.remove() } const log = document.getElementById('log'); document.addEventListener('mousemove', logMovement); Result Specifications Specification Status Comment Pointer LockThe definition of 'MouseEvent.movementX' in that specification. Candidate Recommendation Initial definition ...
MouseEvent.movementY - Web APIs
Syntax var yShift = instanceOfMouseEvent.movementY; Return value A number Example This example logs the amount of mouse movement using movementX and movementY. HTML <p id="log">Move your mouse around.</p> JavaScript function logMovement(event) { log.innerText = `movement: ${event.movementX}, ${event.movementY}\n${log.innerText}`; } const log = document.getElementById('log'); document.addEventListener('mousemove', logMovement); Result Specifications Specification Status Comment Pointer LockThe definition of 'MouseEvent.movementY' in that specification. Candidate Recommendation Initial definition. ...
MouseEvent.pageX - Web APIs
Web › API › MouseEvent › pageX
ve to the page's origin. Since this example is presented in an <iframe>, that top-left corner is the top-left corner of the frame, not the browser window. JavaScript var box = document.querySelector(".box"); var pageX = document.getElementById("x"); var pageY = document.getElementById("y"); function updateDisplay(event) { pageX.innerText = event.pageX; pageY.innerText = event.pageY; } box.addEventListener("mousemove", updateDisplay, false); box.addEventListener("mouseenter", updateDisplay, false); box.addEventListener("mouseleave", updateDisplay, false); The JavaScript code uses addEventListener() to register the function updateDisplay() as the event handler for the mousemove, mouseenter, and mouseleave events. updateDisplay() simply replaces the contents of the <span> elements meant to contain ...
MouseEvent.region - Web APIs
Web › API › MouseEvent › region
e A DOMString representing the id of the hit region. ...
MouseEvent.screenX - Web APIs
value. Early versions of the spec defined this as an integer referring to the number of pixels. See the "Browser compatibility" section for details. Example This example displays your mouse's coordinates whenever you trigger the mousemove event. ...
MouseEvent.screenY - Web APIs
value. Early versions of the spec defined this as an integer referring to the number of pixels. See the "Browser compatibility" section for details. Example This example displays your mouse's coordinates whenever you trigger the mousemove event. HTML <p>Move your mouse to see its position.</p> <p id="screen-log"></p> JavaScript let screenLog = document.querySelector('#screen-log'); document.addEventListener('mousemove', logKey); function logKey(e) { screenLog.innerText = ` Screen X/Y: ${e.screenX}, ${e.screenY} Client X/Y: ${e.clientX}, ${e.clientY}`; } Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'screenY' in that specification. Working Draft Redefines MouseEvent from long to double. D...
MouseEvent.shiftKey - Web APIs
eyPressed = instanceOfMouseEvent.shiftKey Return value A Boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. Example This example logs the shiftKey property when you trigger a click event. HTML <p>Click anywhere to test the <code>shiftKey</code> property.</p> <p id="log"></p> JavaScript let log = document.querySelector('#log'); document.addEventListener('click', logKey); function logKey(e) { log.textContent = `The shift key is pressed: ${e.shiftKey}`; } Result Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'MouseEvent.shiftKey' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Events Specification. ...
MouseEvent - Web APIs
Working Draft Redefines MouseEvent from long to double. This means that a PointerEvent whose pointerType is mouse will be a double. Pointer LockThe definition of 'MouseEvent' in that sp...
msPlayToSource - Web APIs
is the source associated with the media element. Example <video id="videoplayer" src="http://www.contoso.com/clip.mp4" controls autoplay /> <script type="text/javascript"> // Step 1: Obtain PlayToManager object for app's current view. var ptm = Windows.Media.PlayTo.PlayToManager.getForCurrentView(); // Step 2: Register for the sourcerequested event (user swipes Devices charm). ptm.addEventListener("sourcerequested", function(e) { // Step 3: Specify the media to be streamed (to filter devices). e.sourceRequest.setSource(document.getElementById("videoplayer").msPlayToSource); // The media will then be streamed to the device chosen by the user in the UI. }); ...
MutationEvent - Web APIs
s. Mutation events list The following is a list of all mutation events, as defined in DOM Level 3 Events specification: DOMAttrModified DOMAttributeNameChanged DOMCharacterDataModified DOMElementNameChanged DOMNodeInserted DOMNodeInsertedIntoDocument DOMNodeRemoved DOMNodeRemovedFromDocument DOMSubtreeModified Usage You can register a listener for mutation events using EventTarget.addEventListener() as follows: element.addEventListener("DOMNodeInserted", function (event) { // ... }, 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. ...
Navigator.getBattery() - Web APIs
t not be explicitly allowed or restricted via Feature-Policy battery feature. Example This example fetches the current charging state of the battery and establishes a handler for the chargingchange event, so that the charging state is recorded whenever it changes. let batteryIsCharging = false; navigator.getBattery().then(function(battery) { batteryIsCharging = battery.charging; battery.addEventListener('chargingchange', function() { batteryIsCharging = battery.charging; }); }); For more examples and details, see Battery Status API. Specifications Specification Status Comment Battery Status APIThe definition of 'Navigator.getBattery()' in that specification. Candidate Recommendation Initial definition ...
Navigator.getGamepads() - Web APIs
The Navigator.getGamepads() method returns an array of Gamepad objects, one for each gamepad connected to the device. Elements in the array may be null if a gamepad disconnects during a session, so that the remaining gamepads retain the same index. Syntax var gamepads = navigator.getGamepads(); Example window.addEventListener("gamepadconnected", function(e) { var gp = navigator.getGamepads()[e.gamepad.index]; console.log( "Gamepad connected at index %d: %s. %d buttons, %d axes.", gp.index, gp.id, gp.buttons.length, gp.axes.length ); }); Specifications Specification Status Comment GamepadThe definition of 'The Gamepad API specification' in that specification. Working Draft Initial definition. ...
Navigator.share() - Web APIs
Web › API › Navigator › share
ode) there is a button which, when clicked, invokes the Web Share API to share MDN's URL. The JavaScript looks like this: const shareData = { title: 'MDN', text: 'Learn web development on MDN!', url: 'https://developer.mozilla.org', } const btn = document.querySelector('button'); const resultPara = document.querySelector('.result'); // Must be triggered some kind of "user activation" btn.addEventListener('click', async () => { try { await navigator.share(shareData) resultPara.textContent = 'MDN shared successfully' } catch(err) { resultPara.textContent = 'Error: ' + err } }); Sharing Files To share files, first test for and call navigator.canShare(). Then include an array of files in the call to navigator.share(): Notice: That the sample handles feature detection by testing ...
NetworkInformation.downlinkMax - Web APIs
Draft Initial definition ...
NetworkInformation.onchange - Web APIs
information changes, and the change is received by the NetworkInformation object. Syntax netInfo.onchange = function() { ... } Examples // Get the connection type. var type = navigator.connection.type; function changeHandler(e) { // Handle change of connection type here. } // Register for event changes: navigator.connection.onchange = changeHandler; // Another way: navigator.connection.addEventListener('change', changeHandler); Specifications Specification Status Comment Network Information APIThe definition of 'onchange' in that specification. Draft Initial definition ...
Network Information API - Web APIs
s Detect connection changes This example watches for changes to the user's connection. var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection; var type = connection.effectiveType; function updateConnectionStatus() { console.log("Connection type changed from " + type + " to " + connection.effectiveType); type = connection.effectiveType; } connection.addEventListener('change', updateConnectionStatus); Preload large resources The connection object is useful for deciding whether to preload resources that take large amounts of bandwidth or memory. This example would be called soon after page load to check for a connection type where preloading a video may not be desirable. If a cellular connection is found, then the preloadVideo flag is set to false. For simp...
Node.cloneNode() - Web APIs
Web › API › Node › cloneNode
t to omit the argument. Starting with Gecko 29.0 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26)), a shallow clone is defaulted instead of a deep clone. Example let p = document.getElementById("para1") let p_prime = p.cloneNode(true) Notes Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties (e.g., node.onclick = someFunction). Additionally, for a <canvas> element, the painted image is not copied. Warning: cloneNode() may lead to duplicate element IDs in a document! If the original node has an id attribute, and the clone will be placed in the same document, then you should modify the clone's ID to be unique. Name attributes may need to be...
NotificationAction - Web APIs
ice worker shows a notification with a single "Archive" action, allowing users to perform this common task from the notification without having to open the website. The user can also click the main body of the notification to open their inbox instead. ...
NotificationEvent.action - Web APIs
mewhere other than an action button, or the notification does not have a button. The notification id is set during the creation of the Notification via the actions array attribute and can't be modified unless the notification is replaced. Returns A DOMString object. Example self.registration.showNotification("New articles available", { actions: [{action: "get", title: "Get now."}] }); self.addEventListener('notificationclick', function(event) { event.notification.close(); if (event.action === 'get') { synchronizeReader(); } else { clients.openWindow("/reader"); } }, false); Specifications Specification Status Comment Notifications APIThe definition of 'action' in that specification. Living Standard Living standard. ...
NotificationEvent.notification - Web APIs
y of the NotificationEvent interface returns the instance of the Notification that was clicked to fire the event. The Notification provides read-only access to many properties that were set at the instantiation time of the Notification such as tag and data attributes that allow you to store information for defered use in the notificationclick event. Returns A Notification object. Example self.addEventListener('notificationclick', function(event) { console.log('On notification click'); // Data can be attached to the notification so that you // can process it in the notificationclick handler. console.log('Notification Tag:', event.notification.tag); console.log('Notification Data:', event.notification.data); event.notification.close(); // This looks to see if the current is already open ...
NotificationEvent - Web APIs
string ID of the notification button the user clicked. This value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button. Methods Inherits methods from its parent, ExtendableEvent. ExtendableEvent.waitUntil() Extends the lifetime of the event. Tells the browser that work is ongoing. ...
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. ...
Performance - Web APIs
urns a DOMHighResTimeStamp representing the number of milliseconds elapsed since a reference instant. Performance.setResourceTimingBufferSize() Sets the browser's resource timing buffer size to the specified number of "resource" type performance entry objects. Performance.toJSON() Is a jsonizer returning a json object representing the Performance object. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. resourcetimingbufferfull Fired when the browser's resource timing buffer is full. Also available via the onresourcetimingbufferfull property. Specifications Specification Status Comment High Resolution Time Level 2The definition of 'Performance' in that specification. Recommendati...
PerformanceEventTiming - Web APIs
can also directly query the first input delay. // Keep track of whether (and when) the page was first hidden, see: // https://github.com/w3c/page-visibility/issues/29 // NOTE: ideally this check would be performed in the document <head> // to avoid cases where the visibility state changes before this code runs. let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity; document.addEventListener('visibilitychange', (event) => { firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp); }, {once: true}); // Sends the passed data to an analytics endpoint. This code // uses `/analytics`; you can replace it with your own URL. function sendToAnalytics(data) { const body = JSON.stringify(data); // Use `navigator.sendBeacon()` if available, falling back to `fetch()`. (navigator.send...
PermissionStatus.onchange - Web APIs
The onchange event handler of the PermissionStatus interface is called whenever the PermissionStatus.state property changes. Syntax PermissionStatus.onchange = function() { ... } PermissionStatus.addEventListener('change', function() { ... }) Example navigator.permissions.query({name:'geolocation'}).then(function(permissionStatus) { console.log('geolocation permission state is ', permissionStatus.state); permissionStatus.onchange = function() { console.log('geolocation permission state has changed to ', this.state); }; }); Specification Specification Status Comment PermissionsThe definition of 'onchange' in that specification. Working Draft Initial definition. ...
PointerEvent.isPrimary - Web APIs
atibility mouse events (see Pointer_events for more information about pointer, mouse and touch interaction). Syntax var isPrimary = pointerEvent.isPrimary; Return value isPrimary Returns true if the pointer for this event is the primary pointer and returns false otherwise. Example This example illustrates using the value of isPrimary to call the appropriate processing function. target.addEventListener('pointerdown', function(event) { if (event.isPrimary) process_primary_pointer(event); else process_secondary_pointer(event); }, false); Specifications Specification Status Comment Pointer Events - Level 2The definition of 'isPrimary' in that specification. Recommendation Non-stable version. Pointer EventsThe definition of 'isPrimary' in t...
PointerEvent.pointerId - Web APIs
y be randomly generated, it is not guaranteed to convey any particular meaning. Syntax var id = pointerEvent.pointerId; Return value id The pointer event's unique identifier number. Example The following code snippet compares a previously saved pointerId with the one of the pointerdown event that was just fired. let id; // Let's assume that this is a previously saved pointerId target.addEventListener('pointerdown', function(event) { // Compare previous event's ID that was cached // to current event's ID and handle accordingly if (id === event.pointerId) process_event(event); }, false); Specifications Specification Status Comment Pointer Events - Level 2The definition of 'pointerId' in that specification. Recommendation Non-stable version. Pointe...
PointerEvent.pointerType - Web APIs
pe cannot be detected by the browser, the value can be an empty string (""). If the browser supports pointer device types other than those listed above, the value should be vendor-prefixed to avoid conflicting names for different types of devices. Example This example illustrates using the value of the pointerType property to call the appropriate pointer type processing function. ...
PointerEvent.pressure - Web APIs
d 1 represent the minimum and maximum pressure the hardware is capable of detecting, respectively. For hardware that does not support pressure, such as a mouse, the value is 0.5 when the pointer is active buttons state and 0 otherwise. Example In this snippet, when a pointerdown event is fired, different functions are called depending on the value of the event's pressure property. ...
PointerEvent.tangentialPressure - Web APIs
ge -1 to 1, inclusive, where 0 is the neutral position of the control. Note that some hardware may only support positive values in the range 0 to 1. For hardware that does not support tangential pressure, the value will be 0. Example In this snippet, when a pointerdown event is fired, different functions are called depending on the value of the event's tangentialPressure property. ...
PointerEvent.tiltX - Web APIs
ax var tiltX = pointerEvent.tiltX; Return value tiltX The angle in degrees between the Y-Z plane of the pointer (stylus) and the screen. The range of values is -90 to 90, inclusive, where a positive value is a tilt to the right. For devices that do not support this property, the value is 0. Example This example illustrates simple accessing of the tiltX and tiltY properties. someElement.addEventListener("pointerdown", function(event) { process_tilt(event.tiltX, event.tiltY); }, false); Specifications Specification Status Comment Pointer Events - Level 2The definition of 'tiltX' in that specification. Recommendation Non-stable version. Pointer EventsThe definition of 'tiltX' in that specification. Obsolete Initial definition. ...
PointerEvent.tiltY - Web APIs
var tiltY = pointerEvent.tiltY; Return value tiltY The angle in degrees between the X-Z plane of the pointer (stylus) and the screen. The range of values is -90 to 90, inclusive, where a positive value is a tilt towards the user. For devices that do not support this property, the value is 0. Example This example illustrates simple accessing of the tiltX and tiltY properties. someElement.addEventListener("pointerdown", function(event) { process_tilt(event.tiltX, event.tiltY); }, false); Specifications Specification Status Comment Pointer Events - Level 2The definition of 'tiltY' in that specification. Recommendation Non-stable version. Pointer EventsThe definition of 'tiltY' in that specification. Obsolete Initial definition. ...
PointerEvent.twist - Web APIs
s. Syntax var twist = pointerEvent.twist; Return value A long value representing the amount of twist, in degrees, applied to the transducer (pointer). The value is in the range 0 to 359, inclusive. For devices that do not report twist, the value is 0. Example When a pointerdown event is fired, different functions are called depending on the value of the event's twist property. someElement.addEventListener('pointerdown', function(event) { if (event.twist == 0) { // No twist process_no_twist(event); } else { // Default process_twist(event); } }, false); Specifications Specification Status Comment Pointer Events - Level 2The definition of 'twist' in that specification. Recommendation ...
PointerEvent.width - Web APIs
produce a different value. If the input hardware cannot report the contact geometry to the browser, the width defaults to 1. Syntax var contactWidth = pointerEvent.width; Return value contactWidth The width of the event's contact area (in CSS pixels). Example This example illustrates using the PointerEvent interface's width and height properties to calculate the contact area. target.addEventListener("pointerdown", function(ev) { // Calculate the contact area var area = ev.width * ev.height; }, false); Specifications Specification Status Comment Pointer Events - Level 2The definition of 'width' in that specification. Recommendation Non-stable version. Pointer EventsThe definition of 'width' in that specification. Obsolete Initial definiti...
Using Pointer Events - Web APIs
ton> <br> Log: <pre id="log" style="border: 1px solid #ccc;"></pre> Setting up the event handlers When the page loads, the startup() function shown below should be called by our <body> element's onload attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system). function startup() { var el = document.getElementsByTagName("canvas")[0]; el.addEventListener("pointerdown", handleStart, false); el.addEventListener("pointerup", handleEnd, false); el.addEventListener("pointercancel", handleCancel, false); el.addEventListener("pointermove", handleMove, false); log("initialized."); } This simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they occur. Tracking new touches We'll keep track of the...
PushManager.subscribe() - Web APIs
g development it often helps to log errors to the // console. In a production environment it might make sense to // also report information about errors back to the // application server. console.log(error); } ); }); Responding to user gestures subscribe() calls should be done in response to a user gesture, such as clicking a button, for example: btn.addEventListener('click', function() { serviceWorkerRegistration.pushManager.subscribe(options) .then(function(pushSubscription) { // handle subscription }); }) This is not only best practice -- you should not be spamming users with notifications they didn't agree to -- but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doin...
PushMessageData.arrayBuffer() - Web APIs
Working Draft Initial definition. ...
PushMessageData.blob() - Web APIs
Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
PushMessageData.json() - Web APIs
The json()method of the PushMessageData interface extracts push message data by parsing it as a JSON string and returning the result. Syntax var myData = PushEvent.data.json(); Parameters None. Returns The result of parsing push event data as JSON. This could be anything that can be represented by JSON -- an object, an array, a string, a number... Examples self.addEventListener('push', function(event) { var myData = event.data.json(); // do something with your data }); Specifications Specification Status Comment Push APIThe definition of 'json()' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check o...
PushMessageData.text() - Web APIs
Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
PushMessageData - Web APIs
s before they are made accessible through the methods of the PushMessageData interface. Properties None. Methods PushMessageData.arrayBuffer() Extracts the data as an ArrayBuffer object. PushMessageData.blob() Extracts the data as a Blob object. PushMessageData.json() Extracts the data as a JSON object. PushMessageData.text() Extracts the data as a plain text string. ...
RTCDTMFSender - Web APIs
nder.insertDTMF() Given a string describing a set of DTMF codes and, optionally, the duration of and inter-tone gap between the tones, insertDTMF() starts sending the specified tones. Calling insertDTMF() replaces any already-pending tones from the toneBuffer. You can abort sending queued tones by specifying an empty string ("") as the set of tones to play. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. tonechange The tonechange event is sent to the RTCDTMFSender instance's event handler to indicate that a tone has either started or stopped playing. Also available using the ontonechange event handler property. Example See the article Using DTMF with WebRTC for a full example. Specifications Spec...
RTCDTMFToneChangeEvent - Web APIs
methods defined in Event. There are no additional methods. Examples This snippet is derived loosely from the full, working example you'll find in When a tone finishes playing in Using DTMF with WebRTC. It appends each tone to a display box as it's played, and, once all tones have been sent, re-enabled a previously-disabled "Send" button, allowing the next DMTF string to be entered. dtmfSender.addEventListener("change", function(event) { if (event.tone !== "") { dialStringBox.innerText += event.tone; } else { sendDTMFButton.disabled = false; } }, false); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDTMFToneChangeEvent' in that specification. Candidate Recommendation Initial definition.
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
utgoing data that is considered "low." The default value is 0. When the number of buffered outgoing bytes, as indicated by the bufferedAmount property, falls to or below this value, a bufferedamountlow event is fired. This event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. Listeners may be added with onbufferedamountlow or addEventListener(). The user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. As messages are actually sent, this value is reduced accordingly. bufferedamountlow events are not fired after the data channel is closed. Syntax var threshold = aDataChannel.bufferedAmountLowThreshold; aDataChannel.buffere...
RTCDataChannel: bufferedamountlow event - Web APIs
e the data channel's buffer falls below the number of bytes specified by bufferedAmountLowThreshold, which we have set to 65536. In other words, we'll try to keep at least 64kB of data in the buffer, reading 64kB at a time from the source. let pc = new RTCPeerConnection(); let dc = pc.createDataChannel("SendFile"); let source = /* source data object */ dc.bufferedAmountLowThreshold = 65536; pc.addEventListener("bufferedamountlow", ev => { if (source.position <= source.length) { dc.send(source.readFile(65536)); } }, false); After creating the RTCPeerConnection, this calls RTCPeerConnection.createDataChannel() to create the data channel. Then a listener is created for bufferedamountlow to refill the incoming data buffer any time its contents fall below 65536 bytes. You can also set up a listen...
RTCDataChannel: close event - Web APIs
Bubbles No Cancelable No Interface Event Event handler property RTCDataChannel.onclose Examples This example sets up a handler for the close event for the RTCDataChannel named dc; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a new call to be started. dc.addEventListener("close", ev => { messageInputBox.disabled = true; sendButton.disabled = true; connectButton.disabled = false; disconnectButton.disabled = true; }, false); All this code does in response to receiving the close event is to disable an input box and its "Send" button, and to enable the button used to start a call (while disabling the one that ends a call). You can also use the onclose even...
RTCDataChannel: error event - Web APIs
"Stale cookie error", "Sender is out of resource (i.e., memory)", "Unable to resolve address", "Unrecognized SCTP chunk type received", "Invalid mandatory parameter", "Unrecognized parameters", "No user data (SCTP DATA chunk has no data)", "Cookie received while shutting down", "Restart of an association with new addresses", "User-initiated abort", "Protocol violation" ]; dc.addEventListener("error", ev => { const err = ev.error; console.error("WebRTC error: ", err.message); // Handle specific error detail types switch(err.errorDetail) { case "sdp-syntax-error": console.error(" SDP syntax error in line ", err.sdpLineNumber); break; case "idp-load-failure": console.error(" Identity provider load failure: HTTP error ", err.
RTCDataChannel: message event - Web APIs
The message event uses as its event object type the MessageEvent interface defined by the HTML specification. Examples For a given RTCDataChannel, dc, created for a peer connection using its createDataChannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new <p> (paragraph) element. dc.addEventListener("message", ev => { let newParagraph = document.createElement("p"); let textNode = document.createTextNode(event.data); newParagraph.appendChild(textNode); document.body.appendChild(newParagraph); }, false); Lines 2-4 create the new paragraph element and add the message data to it as a new text node. Line 6 appends the new paragraph to the end of the document's body. You can also use a...
RTCDataChannel: open event - Web APIs
le adds to the RTCDataChannel dc a handler for the open event that adjusts the user interface to indicate that a chat window is ready to be used after a connection has been established. It enables the message input box and send button as well as enabling the disconnect button and disabling the connect button. Finally, the message input box is focused so the user can immediately begin to type. dc.addEventListener("open", ev => { messageInputBox.disabled = false; sendMessageButton.disabled = false; disconnectButton.disabled = false; connectButton.disabled = true; messageInputBox.focus(); }, false); This can also be done by directly setting the value of the channel's onopen event handler property. dc.onopen = ev => { messageInputBox.disabled = false; sendMessageButton.disabled = false; d...
RTCIceTransport: selectedcandidatepairchange event - Web APIs
ample creates an event handler for selectedcandidatepairchange that updates a display providing the user information about the progress of the ICE negotiation for an RTCPeerConnection called pc. let iceTransport = pc.getSenders[0].transport.iceTransport; let localProtoElem = document.getElementById("local-protocol"); let remoteProtoElem = document.getElementById("remote-protocol"); iceTransport.addEventListener("selectedcandidatepairchange", ev => { let pair = iceTransport.getSelectedCandidatePair(); localProtoElem.innerText = pair.local.protocol.toUpperCase(); remoteProtoElem.innerText = pair.remote.protocol.toUpperCase(); }, false) This can also be done by setting the onselectedcandidatepairchange event handler property directly. let iceTransport = pc.getSenders[0].transport.iceTransport; let ...
RTCIceTransport: statechange event - Web APIs
Bubbles No Cancelable No Interface Event Event handler property RTCIceTransport.onstatechange Examples Given an RTCPeerConnection, pc, the following code creates an event handler that calls a function named handleFailure() if the ICE transport enters a failure state. ...
RTCIceTransport - Web APIs
Returns a RTCIceCandidatePair object that identifies the two candidates--one for each end of the connection--that have been selected so far. It's possible that a better pair will be found and selected later; if you need to keep up with this, watch for the selectedcandidatepairchange event. If no candidate pair has been selected yet, the return value is null. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. gatheringstatechange Sent to the RTCIceTransport object to indicate that the value of the gatheringState property has changed, indicating a change in this transport's ICE candidate negotiation process. Also available through the ongatheringstatechange event handler property. selectedcandidatepairchange Sent ...
RTCPeerConnection: datachannel event - Web APIs
the channel. Bubbles No Cancelable No Interface RTCDataChannelEvent Event handler property ondatachannel Examples This example sets up a function that handles datachannel events by gathering the information needed to communicate with the newly added RTCDataChannel and by adding event handlers for the events that occur on that channel. pc.addEventListener("datachannel", ev => { receiveChannel = ev.channel; receiveChannel.onmessage = myHandleMessage; receiveChannel.onopen = myHandleOpen; receiveChannel.onclose = myHandleClose; }, false); receiveChannel is set to the value of the event's channel property, which specifies the RTCDataChannel object representing the data channel linking the remote peer to the local one. This same code can al...
RTCPeerConnection: icecandidateerror event - Web APIs
gathering. Example The following example establishes a handler for icecandidateerrors that occur on the RTCPeerConnection pc. This handler looks specifically for 701 errors that indicate that candidates couldn't reach the STUN or TURN server. When this happens, the server URL and the error message are passed to a function called reportConnectFail() to log or output the connection failure. pc.addEventListener("icecandidateerror", (event) => { if (event.errorCode === 701) { reportConnectFail(event.url, event.errorText); } }); Note that if multiple STUN and/or TURN servers are provided when creating the connection, this error may happen more than once, if more than one of those servers fails. Each provided server is tried until a connection is established. Specifications Specificati...
RTCPeerConnection.onaddstream - Web APIs
...
RTCPeerConnection.removeStream() - Web APIs
erConnection. ...
RTCPeerConnection.removeTrack() - Web APIs
s not open. Example This example adds a video track to a connection and sets up a listener on a close button which removes the track when the user clicks the button. var pc, sender; navigator.getUserMedia({video: true}, function(stream) { pc = new RTCPeerConnection(); var track = stream.getVideoTracks()[0]; sender = pc.addTrack(track, stream); }); document.getElementById("closeButton").addEventListener("click", function(event) { pc.removeTrack(sender); pc.close(); }, false); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.removeTrack()' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.restartIce() - Web APIs
ew credentials. Existing media transmissions continue uninterrupted during this process. For details about how ICE restart works, see ICE restart in Lifetime of a WebRTC session and RFC 5245, section 9.1.1.1: ICE specification. Example This example creates a handler for the iceconnectionstatechange event that handles a transition to the failed state by restarting ICE in order to try again. ...
RTCPeerConnection.setLocalDescription() - Web APIs
onDescription parameter is invalid. Examples Implicit descriptions One of the advantages of the parameter-free form of setLocalDescription() is that it lets you simplify your negotiation code substantially. This is all your negotiationneeded event handler needs to look like, for the most part. Just add the signaling server code, which here is represented by the call to signalRemotePeer(). pc.addEventListener("negotiationneeded", async (event) => { await pc.setLocalDescription(); signalRemotePeer({ description: pc.localDescription }); }); Other than error handling, that's about it! Providing your own offer or answer The example below shows the implementation of a handler for the negotiationneeded event that explicitly creates an offer, rather than letting setLocalDescription() do it. async fu...
RTCPeerConnection: signalingstatechange event - Web APIs
has changed. Bubbles No Cancelable No Interface Event Event handler property RTCPeerConnection.onsignalingstatechange Examples Given an RTCPeerConnection, pc, and an updateStatus() function that presents status information to the user, this code sets up an event handler to let the user know when the ICE negotiation process finishes up. ...
RTCPeerConnection: track event - Web APIs
ed, the new track has been fully added to the peer connection. See Track event types in RTCTrackEvent for details. Examples This example shows code that creates a new RTCPeerConnection, then adds a new track event handler. pc = new RTCPeerConnection({ iceServers: [ { urls: "turn:fake.turnserver.url", username: "someusername", credential: "somepassword" } ] }); pc.addEventListener("track", e => { videoElement.srcObject = e.streams[0]; hangupButton.disabled = false; }, false); The event handler assigns the new track's first stream to an existing <video> element, identified using the variable videoElement. You can also assign the event handler function to the ontrack property, rather than use addEventListener(). pc.ontrack = e => { videoElement.srcObject = e.streams...
RTCPeerConnection - Web APIs
s of the remote end of the connection, including the media format. Obsolete method The following method was obsoleted long ago and was never implemented in all major browsers. RTCPeerConnection.createDTMFSender() Creates a new RTCDTMFSender, associated to a specific MediaStreamTrack, that will be able to send DTMF phone signaling over the connection. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. connectionstatechange Sent to the RTCPeerConnection object when the overall connectivity status of the RTCPeerConnection changes. Also available through the onconnectionstatechange event handler property. datachannel Sent to the RTCPeerConnection object when the remote peer adds an RTCDataChannel to the conn...
RTCPeerConnectionIceErrorEvent.address - Web APIs
s part of a local candidate, the value of address is null. Examples This example creates a handler for icecandidateerror events which creates human readable messages describing the local network interface for the connection as well as the ICE server that was being used to try to open the connection, then calls a function to display those as well as the event's errorText property's contents. ...
Range.commonAncestorContainer - Web APIs
</li> <li>Woodwinds <ul> <li>Clarinet</li> <li>Oboe</li> </ul> </li> </ul> CSS The .highlight class created below uses a set of CSS @keyframes to animate a fading outline. ...
Range.extractContents() - Web APIs
ap">Swap selected item(s)</button> <p id="list2">abcdef</p> CSS body { pointer-events: none; } p { border: 1px solid; font-size: 2em; padding: .3em; } button { font-size: 1.2em; padding: .5em; pointer-events: auto; } JavaScript const list1 = document.getElementById('list1'); const list2 = document.getElementById('list2'); const button = document.getElementById('swap'); button.addEventListener('click', e => { selection = window.getSelection(); for (let i = 0; i < selection.rangeCount; i++) { const range = selection.getRangeAt(i); if (range.commonAncestorContainer === list1 || range.commonAncestorContainer.parentNode === list1) { const documentFragment = range.extractContents(); list2.appendChild(documentFragment); } else if (range.commonAncestorCon...
Range.selectNodeContents() - Web APIs
="p"><b>Use the buttons below</b> to select or deselect the contents of this paragraph.</p> <button id="select-button">Select paragraph</button> <button id="deselect-button">Deselect paragraph</button> JavaScript const p = document.getElementById('p'); const selectButton = document.getElementById('select-button'); const deselectButton = document.getElementById('deselect-button'); selectButton.addEventListener('click', e => { // Clear any current selection const selection = window.getSelection(); selection.removeAllRanges(); // Select paragraph const range = document.createRange(); range.selectNodeContents(p); selection.addRange(range); }); deselectButton.addEventListener('click', e => { const selection = window.getSelection(); selection.removeAllRanges(); }); Result Specificati...
ReadableStream.ReadableStream() - Web APIs
ut of the stream. ...
ReadableStreamDefaultController.close() - Web APIs
ut of the stream. ...
ReadableStreamDefaultController.enqueue() - Web APIs
ut of the stream. ...
ReadableStreamDefaultController - Web APIs
ut of the stream. ...
ResizeObserver.disconnect() - Web APIs
The disconnect() method of the ResizeObserver interface unobserves all observed Element or SVGElement targets. Syntax resizeObserver.disconnect(); Parameters None. Return value Void. Exceptions None. Examples btn.addEventListener('click', () => { resizeObserver.disconnect(); }) Specifications Specification Status Comment Resize ObserverThe definition of 'disconnect()' in that specification. Editor's Draft Initial definition. ...
ResizeObserver.unobserve() - Web APIs
Editor's Draft Initial definition. ...
SVGAnimationElement: beginEvent event - Web APIs
roke-width="1"> <animateMotion path="M 0 0 H 300 Z" dur="5s" repeatCount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgElem = document.querySelector('svg'); let animateElem = document.querySelector('animateMotion'); let list = document.querySelector('ul'); animateElem.addEventListener('beginEvent', () => { let listItem = document.createElement('li'); listItem.textContent = 'beginEvent 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(listI...
SVGAnimationElement: repeatEvent event - Web APIs
troke-width="1"> <animateMotion path="M 0 0 H 300 Z" dur="5s" repeatCount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgElem = document.querySelector('svg'); let animateElem = document.querySelector('animateMotion'); let list = document.querySelector('ul'); animateElem.addEventListener('beginEvent', () => { let listItem = document.createElement('li'); listItem.textContent = 'beginEvent 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(listI...
SVGAnimationElement - Web APIs
Creates an end instance time for the current time. The new instance time is added to the end instance times list. The behavior of this method is equivalent to endElementAt(0). SVGAnimationElement.endElementAt() Creates a end instance time for the current time plus the specified offset. The new instance time is added to the end instance times list. Events Listen to these events using addEventListener() or by assigning an event listener to the on... handler property of this interface. beginEvent Fired when the element local timeline begins to play. Also available via the onbegin property. endEvent Fired when at the active end of the animation is reached. Also available via the onend property. repeatEvent Fired when the element's local timeline repeats. It will be fired each time the ...
SVGElement: abort event - Web APIs
The abort event is fired when page loading is stopped before an SVG element has been allowed to load completely. This basically implements the standard abort DOM event. Bubbles No Cancelable No Interface SVGEvent Event handler property onabort Examples svgElem.addEventListener('abort', () => { console.log('Load aborted.'); }) Specifications Not really described anywhere specifically, but mentioned in the SVG 2 spec. ...
SVGElement: error event - Web APIs
The error event is fired when an SVG element does not load properly or when an error occurs during script execution. This basically implements the standard error DOM event. Bubbles Yes Cancelable No Interface SVGEvent Event handler property onerror Examples svgElem.addEventListener('error', () => { console.log('SVG not loaded properly.'); }) Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'error' in that specification. Candidate Recommendation Initial definition ...
SVGElement: load event - Web APIs
The load event fires on an SVGElement when it is loaded in the browser, e.g. in the DOM in the case of an embedded <svg>. It is basically the same as the standard load DOM event. Bubbles No Cancelable No Interface SVGEvent Event handler property onload Examples svgElem.addEventListener('load', () => { console.log('SVG loaded.'); }) Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'load' in that specification. Candidate Recommendation Initial definition ...
SVGElement: resize event - Web APIs
The resize event is fired when an SVG document is being resized. This event is only applicable to outermost SVG elements and is dispatched after the resize operation has taken place. This basically implements the standard resize DOM event. Bubbles No Cancelable No Interface SVGEvent Event handler property onresize Examples svgElem.addEventListener('resize', () => { console.log('SVG resized.'); }) Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'event changes in SVG2' in that specification. Candidate Recommendation Initial definition ...
SVGElement: scroll event - Web APIs
The scroll event is fired when an SVG document view is being shifted along the X and/or Y axes. This basically implements the standard scroll DOM event. Bubbles No Cancelable No Interface SVGEvent Event handler property onscroll Examples svgElem.addEventListener('scroll', () => { console.log('SVG scrolled.'); }) Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'event changes in SVG2' in that specification. Candidate Recommendation Initial definition ...
SVGElement: unload event - Web APIs
The unload event is fired when the DOM implementation removes an SVG document from a window or frame. Bubbles No Cancelable No Interface SVGEvent Event handler property onunload Examples svgElem.addEventListener('unload', () => { console.log('SVG unloaded.'); }) Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'unload' in that specification. Candidate Recommendation Initial definition ...
SVGElement: zoom event - Web APIs
r initiates an action which causes the current view of the SVG document fragment to be rescaled. Bubbles Yes Cancelable No Interface SVGEvent Event handler property onzoom Examples svgElem.addEventListener('zoom', () => { console.log('SVG zoomed.'); }) ...
SVGElement - Web APIs
d only The SVGElement, which established the current viewport. Often, the nearest ancestor <svg> element. null if the given element is the outermost <svg> element. Methods This interface has no methods, but inherits methods from: DocumentAndElementEventHandlers, Element, ElementCSSInlineStyle, GlobalEventHandlers, HTMLOrForeignElement, SVGElementInstance Events Listen to these events using addEventListener() or by assigning an event listener to the equivalent on... handler property defined on GlobalEventHandlers or WindowEventHandlers. abort Fired when page loading is stopped before an SVG element has been allowed to load completely. Also available via the onabort property. error Fired when an SVG element does not load properly or when an error occurs during script execution. Also available...
SVGGraphicsElement: copy event - Web APIs
Clipboard API and events Working Draft Ini...
SVGGraphicsElement: paste event - Web APIs
Clipboard API and events Working Draft Initial d...
Screen - Web APIs
Web › API › Screen
le between 0 and 1.0 is expected. Events handler Screen.onorientationchange A handler for the orientationchange event. Methods Screen.lockOrientation Lock the screen orientation (only works in fullscreen or for installed apps) Screen.unlockOrientation Unlock the screen orientation (only works in fullscreen or for installed apps) Methods inherited from EventTarget: 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...
ScreenOrientation.onchange - Web APIs
}) ScreenOrientation.onchange = function(e) { ... } Specifications Specification Status Comment Screen Orientation APIThe definition of 'onchange' in that specification. Working Draft Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
Using the Screen Capture API - Web APIs
stop buttons. const videoElem = document.getElementById("video"); const logElem = document.getElementById("log"); const startElem = document.getElementById("start"); const stopElem = document.getElementById("stop"); // Options for getDisplayMedia() var displayMediaOptions = { video: { cursor: "always" }, audio: false }; // Set event listeners for the start and stop buttons startElem.addEventListener("click", function(evt) { startCapture(); }, false); stopElem.addEventListener("click", function(evt) { stopCapture(); }, false); Logging content To make logging of errors and other issues easy, this example overrides certain Console methods to output their messages to the <pre> block whose ID is log. console.log = msg => logElem.innerHTML += `${msg}<br>`; console.error = msg => logElem.in...
ScriptProcessorNode: audioprocess event - Web APIs
The audioprocess event of the ScriptProcessorNode interface is fired when an input buffer of a script processor is ready to be processed. ...
ScriptProcessorNode - Web APIs
Channel interpretation "speakers" Properties Inherits properties from its parent, AudioNode. ScriptProcessorNode.bufferSize Read only Returns an integer representing both the input and output buffer size. Its value can be a power of 2 value in the range 256-16384. Methods No specific methods; inherits methods from its parent, AudioNode. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface: audioprocess Fired when an input buffer of a ScriptProcessorNode is ready to be processed. Also available via the onaudioprocess event handler property. Examples The following example shows basic usage of a ScriptProcessorNode to take a track loaded via AudioContext.decodeAudioData(), process it, adding a b...
ScrollToOptions.behavior - Web APIs
-- two numbers representing the left and top properties (i.e. the positions to scroll to along the X and Y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. When the form is submitted, an event handler is run that puts the entered values into a ScrollToOptions dictionary, and then invokes the Window.ScrollTo() method, passing the dictionary as a parameter: form.addEventListener('submit', (e) => { e.preventDefault(); var scrollOptions = { left: leftInput.value, top: topInput.value, behavior: scrollInput.checked ? 'smooth' : 'auto' } window.scrollTo(scrollOptions); }); Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'behavior' in that specification. Working Draft ...
ScrollToOptions.left - Web APIs
-- two numbers representing the left and top properties (i.e. the positions to scroll to along the X and Y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. When the form is submitted, an event handler is run that puts the entered values into a ScrollToOptions dictionary, and then invokes the Window.ScrollTo() method, passing the dictionary as a parameter: form.addEventListener('submit', (e) => { e.preventDefault(); var scrollOptions = { left: leftInput.value, top: topInput.value, behavior: scrollInput.checked ? 'smooth' : 'auto' } window.scrollTo(scrollOptions); }); Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'left' in that specification. Working Draft ...
ScrollToOptions.top - Web APIs
-- two numbers representing the left and top properties (i.e. the positions to scroll to along the X and Y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. When the form is submitted, an event handler is run that puts the entered values into a ScrollToOptions dictionary, and then invokes the Window.ScrollTo() method, passing the dictionary as a parameter: form.addEventListener('submit', (e) => { e.preventDefault(); var scrollOptions = { left: leftInput.value, top: topInput.value, behavior: scrollInput.checked ? 'smooth' : 'auto' } window.scrollTo(scrollOptions); }); Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'top' in that specification. Working Draft ...
ScrollToOptions - Web APIs
-- two numbers representing the left and top properties (i.e. the positions to scroll to along the X and Y axes), and a checkbox indicating whether they want smooth scrolling enabled or not. When the form is submitted, an event handler is run that puts the entered values into a ScrollToOptions dictionary, and then invokes the Window.ScrollTo() method, passing the dictionary as a parameter: form.addEventListener('submit', (e) => { e.preventDefault(); var scrollOptions = { left: leftInput.value, top: topInput.value, behavior: scrollInput.checked ? 'smooth' : 'auto' } window.scrollTo(scrollOptions); }); Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'ScrollToOptions' in that specification. Working Draft ...
SecurityPolicyViolationEvent.blockedURI - Web APIs
The blockedURI read-only property of the SecurityPolicyViolationEvent interface is a USVString representing the URI of the resource that was blocked because it violates a policy. Syntax let blockedURI = violationEventInstance.blockedURI; Value A USVString representing the URI of the blocked resource. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.blockedURI); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'blockedURI' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.columnNumber - Web APIs
The columnNumber read-only property of the SecurityPolicyViolationEvent interface is the column number in the document or worker at which the violation occurred. Syntax let colNum = violationEventInstance.columnNumber; Value A number representing the column number where the violation occurred. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.columnNumber); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'columnNumber' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.disposition - Web APIs
osition read-only property of the SecurityPolicyViolationEvent interface indicates how the violated policy is configured to be treated by the user agent. Syntax let disposition = violationEventInstance.disposition; Value A value defined in the SecurityPolicyViolationEventDisposition enum representing the URI of the blocked resource. Possible values are "enforce" or "report" Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.disposition); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'disposition' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.documentURI - Web APIs
The documentURI read-only property of the SecurityPolicyViolationEvent interface is a USVString representing the URI of the document or worker in which the violation was found. Syntax let documentURI = violationEventInstance.documentURI; Value A USVString representing the URI of the document or worker in which the violation was found. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.documentURI); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'documentURI' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.effectiveDirective - Web APIs
The effectiveDirective read-only property of the SecurityPolicyViolationEvent interface is a DOMString representing the directive whose enforcement uncovered the violation. Syntax let effDir = violationEventInstance.effectiveDirective; Value A DOMString representing the directive whose enforcement uncovered the violation. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.effectiveDirective); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'effectiveDirective' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.lineNumber - Web APIs
The lineNumber read-only property of the SecurityPolicyViolationEvent interface is the line number in the document or worker at which the violation occurred. Syntax let lineNumber = violationEventInstance.lineNumber; Value A number representing the line number at which the violation occurred. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.lineNumber); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'lineNumber' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.originalPolicy - Web APIs
The originalPolicy read-only property of the SecurityPolicyViolationEvent interface is a DOMString containing the policy whose enforcement uncovered the violation. Syntax let origPolicy = violationEventInstance.originalPolicy; Value A DOMString representing the policy whose enforcement uncovered the violation. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.originalPolicy); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'originalPolicy' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.referrer - Web APIs
The referrer read-only property of the SecurityPolicyViolationEvent interface is a USVString representing the referrer of the resources whose policy was violated. This will be a URL or null. Syntax let referrer = violationEventInstance.referrer; Value A USVString representing the URL of the referrer of the violating resources. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.referrer); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'referrer' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.sample - Web APIs
a sample of the resource that caused the violation. Syntax let sample = violationEventInstance.sample; Value A DOMString containing a sample of the resource that caused the violation, usually the first 40 characters. This will only be populated if the resource is an inline script, event handler, or style -- external resources causing a violation will not generate a sample. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.sample); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'sample' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.sourceFile - Web APIs
The sourceFile read-only property of the SecurityPolicyViolationEvent interface is a USVString representing the URI of the document or worker in which the violation was found. Syntax let source = violationEventInstance.sourceFile; Value A USVString representing the URI of the document or worker in which the violation was found. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.sourceFile); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'sourceFile' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.statusCode - Web APIs
The statusCode read-only property of the SecurityPolicyViolationEvent interface is a number representing the HTTP status code of the document or worker in which the violation occurred. Syntax let status = violationEventInstance.statusCode; Value A number representing the status code of the document or worker in which the violation occurred. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.statusCode); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'statusCode' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent.violatedDirective - Web APIs
The violatedDirective read-only property of the SecurityPolicyViolationEvent interface is a DOMString representing the directive whose enforcement uncovered the violation. Syntax let violatedDir = violationEventInstance.violatedDirective; Value A DOMString representing the directive whose enforcement uncovered the violation. Example document.addEventListener("securitypolicyviolation", (e) => { console.log(e.violatedDirective); }); Specifications Specification Status Comment Content Security Policy Level 3The definition of 'violatedDirective' in that specification. Working Draft Initial definition ...
SecurityPolicyViolationEvent - Web APIs
ng representing the URI of the document or worker in which the violation was found. SecurityPolicyViolationEvent.statusCodeRead only A number representing the HTTP status code of the document or worker in which the violation occurred. SecurityPolicyViolationEvent.violatedDirectiveRead only A DOMString representing the directive whose enforcement uncovered the violation. Examples document.addEventListener("securitypolicyviolation", (e) => { console.log(e.blockedURI); console.log(e.violatedDirective); console.log(e.originalPolicy); }); Specifications Specification Status Comment Content Security Policy Level 2The definition of 'SecurityPolicyViolationEvent' in that specification. Recommendation Initial definition. Content Security Policy Level 3The def...
Selection.addRange() - Web APIs
added to the Selection. Example Currently only Firefox supports multiple selection ranges, other browsers will not add new ranges to the selection if it already contains one. ...
Selection.deleteFromDocument() - Web APIs
icking a button. Upon clicking the button, the Window.getSelection() method gets the selected text, and the deleteFromDocument() method removes it. HTML <p>Try highlighting some of the text in this paragraph. Once you do, you can remove the selected content by clicking the button below.</p> <button>Delete selected text</button> JavaScript let button = document.querySelector('button'); button.addEventListener('click', deleteSelection); function deleteSelection() { let selection = window.getSelection(); selection.deleteFromDocument(); } Result Specifications Specification Status Comment Selection APIThe definition of 'Selection.deleteFromDocument()' in that specification. Working Draft Current ...
Selection.modify() - Web APIs
Web › API › Selection › modify
...
Selection.selectAllChildren() - Web APIs
will be selected. parentNode itself is not part of the selection. Example HTML <main> <button>Select Footer</button> <p>Welcome to my website.</p> <p>I hope you enjoy your visit.</p> </main> <footer> <address>webmaster@example.com</address> <p>(C) 2019</p> </footer> JavaScript const button = document.querySelector('button'); const footer = document.querySelector('footer'); button.addEventListener('click', (e) => { window.getSelection().selectAllChildren(footer); }); Result Specifications Specification Status Comment Selection APIThe definition of 'Selection.selectAllChildren()' in that specification. Working Draft Current definition ...
Sensor.onactivate - Web APIs
Web › API › Sensor › onactivate
}) Because Sensor is a base class, onactivate may only be used on one of its derived classes. ...
Sensor.onerror - Web APIs
Web › API › Sensor › onerror
}) Because Sensor is a base class, onerror may only be used on one of its derived classes. ...
Sensor.onreading - Web APIs
Web › API › Sensor › onreading
}) Because Sensor is a base class, onreading may only be used on one of its derived classes. ...
ServiceWorker.state - Web APIs
Working Draft Initial definition ...
ServiceWorker - Web APIs
The service-worker.js file // might be unavailable or contain a syntax error. }); } else { // The current browser doesn't support service workers. } Specifications Specification Stat...
ServiceWorkerContainer: message event - Web APIs
Cancelable No Interface MessageEvent Event handler property onmessage Examples In this example the service worker get the client's ID from a fetch event and then sends it a message using Client.postMessage: // in the service worker async function messageClient(clientId) { const client = await clients.get(clientId); client.postMessage('Hi client!'); } addEventListener('fetch', (event) => { messageClient(event.clientId); event.respondWith(() => { // ... }); }); The client can receive the message by listening to the message event: // in the page being controlled navigator.serviceWorker.addEventListener('message', (message) => { console.log(message); }); Specifications Specification Status Service WorkersThe definiti...
ServiceWorkerGlobalScope: activate event - Web APIs
lobalScope interface is fired when a ServiceWorkerRegistration acquires a new ServiceWorkerRegistration.active worker. Bubbles No Cancelable No Interface ExtendableEvent Event handler property ServiceWorkerGlobalScope.onactivate Examples The following snippet shows how you could use an activate event handler to upgrade a cache. globalScope.addEventListener('activate', function(event) { var cacheWhitelist = ['v2']; event.waitUntil( caches.forEach(function(cache, cacheName) { if (cacheWhitelist.indexOf(cacheName) == -1) { return caches.delete(cacheName); } }) ); }); You can also set up the event handler using the ServiceWorkerGlobalScope.onactivate property: globalScope.onactivate = function(event) { ... }; Spe...
ServiceWorkerGlobalScope: contentdelete event - Web APIs
lobalScope interface is fired when an item is removed from the indexed content via the user agent. Bubbles No Cancelable No Interface ContentIndexEvent Event handler property oncontentdelete Examples The following example uses a contentdelete event handler to remove cached content related to the deleted index item. self.addEventListener('contentdelete', event => { event.waitUntil( caches.open('cache-name').then(cache => { return Promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`) ]) }) ); }); You can also set up the event handler using the ServiceWorkerGlobalScope.ondelete property: self.oncontentdelete = (event) => { ... }; Specifications ...
ServiceWorkerGlobalScope: install event - Web APIs
eWorkerRegistration.installing worker. ...
ServiceWorkerGlobalScope.onactivate - Web APIs
erGlobalScope interface is an event handler fired whenever an activate event occurs (when the service worker activates). This happens after installation, when the page to be controlled by the service worker refreshes. Syntax ServiceWorkerGlobalScope.onactivate = function(event) { ... }; Examples The following snippet shows how you could use an activate event handler to upgrade a cache. then.addEventListener('activate', function(event) { var cacheWhitelist = ['v2']; event.waitUntil( caches.forEach(function(cache, cacheName) { if (cacheWhitelist.indexOf(cacheName) == -1) { return caches.delete(cacheName); } }) ); }); Specifications Specification Status Comment Service WorkersThe definition of 'Event Handlers' in that specification. Workin...
ServiceWorkerGlobalScope.oncontentdelete - Web APIs
The oncontentdelete property of the ServiceWorkerGlobalScope interface is an event handler fired when an item is removed from the indexed content via the user agent. Syntax ServiceWorkerGlobalScope.oncontentdelete = function(event) { ... }; Examples The following example uses a contentdelete event handler to remove cached content related to the deleted index item. self.addEventListener('contentdelete', event => { event.waitUntil( caches.open('cache-name').then(cache => { return Promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`) ]) }) ); }); Specifications Specification Status Comment UnknownThe definition of 'contentdelete' in that specification. Unknown Initial definition. ...
ServiceWorkerGlobalScope.onfetch - Web APIs
fired, the code returns a promise that resolves to the first matching request in the Cache object. If no match is found, the code fetches a response from the network. The code also handles exceptions thrown from the fetch() operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set. self.addEventListener('fetch', function(event) { console.log('Handling fetch event for', event.request.url); event.respondWith( caches.match(event.request).then(function(response) { if (response) { console.log('Found response in cache:', response); return response; } console.log('No response found in cache. About to fetch from network...'); return fetch(event.request)...
ServiceWorkerGlobalScope.oninstall - Web APIs
ace is an event handler fired whenever an install event occurs (when the service worker installs). This happens before activation. Syntax ServiceWorkerGlobalScope.oninstall = function(event) { ... ...
ServiceWorkerGlobalScope.onmessage - Web APIs
ssages received from service worker contexts (e.g. as the event object of onmessage) are represented by MessageEvent objects in modern browsers, for consistency with other web messaging features. (They used to be represented by ServiceWorkerMessageEvent objects, which have now been deprecated.) Syntax serviceWorkerGlobalScope.onmessage = function(extendableMessageEvent) { ... }; Example self.addEventListener('message', function(messageEvent) { console.log('Handling message event:', messageEvent); }) Specifications Specification Status Comment Service WorkersThe definition of 'Event Handlers' in that specification. Working Draft Initial definition ...
onnotificationclose - Web APIs
in workers which aren't service workers using the Notification() constructor will instead receive a close event on the Notification object itself. Note: Trying to create a notification inside the ServiceWorkerGlobalScope using the Notification() constructor will throw an error. Syntax ServiceWorkerGlobalScope.onnotificationclose = function(NotificationEvent) { ... }; ServiceWorkerGlobalScope.addEventListener('notificationclose', function(NotificationEvent) { ... }); Example //Inside a service worker. self.onnotificationclose = function(event) { console.log('On notification close: ', event.notification.tag); }; Specifications Specification Status Comment Notifications APIThe definition of 'onnotificationclick' in that specification. Living Standard Initial definiti...
ServiceWorkerGlobalScope.onpushsubscriptionchange - Web APIs
defined as the event interface that is fired whenever a push subscription has been invalidated (or is about to become so). This offers an opportunity to resubscribe in order to continue receiving push messages, if desired. This might happen if, for example, the push service sets an expiration time a subscription. Syntax ServiceWorkerGlobalScope.onpushsubscriptionchange = function() { ... } self.addEventListener('pushsubscriptionchange', function() { ... }) Example self.addEventListener('pushsubscriptionchange', function() { // do something, usually resubscribe to push and // send the new subscription details back to the // server via XHR or Fetch }); Specifications Specification Status Comment Push APIThe definition of 'onpushsubscriptionchange' in that specification. ...
ServiceWorkerGlobalScope.onsync - Web APIs
lScope.onsync event of the ServiceWorkerGlobalScope interface is fired whenever a SyncEvent event occurs. This is triggered when a call to SyncManager.register is made from a service worker client page. The attempt to sync is made either immediately if the network is available or as soon as the network becomes available. Syntax ServiceWorkerGlobalScope.onsync = function(SyncEvent) { ... } self.addEventListener('sync', function(SyncEvent) { ... }) Specifications Specification Web Background Synchronization ...
ServiceWorkerGlobalScope: push event - Web APIs
eWorkerGlobalScope interface) when the service worker has received a push message. Bubbles No Cancelable No Interface PushEvent Event handler property onpush Example This example sets up a handler for push events that takes JSON data, parses it, and dispatches the message for handling based on information contained within the message. self.addEventListener("push", event => { let message = event.data.json(); switch(message.type) { case "init": doInit(); break; case "shutdown": doShutdown(); break; } }, false); Specifications Specification Status Comment Push APIThe definition of 'push' in that specification. Working Draft Initial specification. ...
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
app server, or make sure your code using fetch() is robust enough to handle cases where attempts to exchange data fail. Note: In earlier drafts of the specification, this event was defined to be sent when a PushSubscription has expired. Examples This example, run in the context of a service worker, listens for a pushsubscriptionchange event and re-subscribes to the lapsed subscription. ...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
r's execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the waiting state. Therefore, it's common to call self.skipWaiting() from inside of an InstallEvent handler. The following example causes a newly installed service worker to progress into the activating state, regardless of whether there is already an active service worker. self.addEventListener('install', function(event) { // The promise that skipWaiting() returns can be safely ignored. self.skipWaiting(); // Perform any other actions required for your // service worker to install, potentially inside // of event.waitUntil(); }); Specifications Specification Status Comment Service WorkersThe definition of 'skipWaiting()' in that specification. Wor...
ServiceWorkerGlobalScope - Web APIs
fired, the code returns a promise that resolves to the first matching request in the Cache object. If no match is found, the code fetches a response from the network. The code also handles exceptions thrown from the fetch() operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set. self.addEventListener('fetch', function(event) { console.log('Handling fetch event for', event.request.url); event.respondWith( caches.match(event.request).then(function(response) { if (response) { console.log('Found response in cache:', response); return response; } console.log('No response found in cache. About to fetch from network...'); return fetch(event.request)...
ServiceWorkerRegistration - Web APIs
xt, it adds an updatefound listener in which it uses the service worker registration to listen for further changes to the service worker's state. If the service worker hasn't changed since the last time it was registered, then the updatefound event will not be fired. if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(function(registration) { registration.addEventListener('updatefound', function() { // If updatefound is fired, it means that there's // a new service worker being installed. var installingWorker = registration.installing; console.log('A new service worker is being installed:', installingWorker); // You can listen for changes to the installing service worker's // state via installingWorker.onstatechange ...
SharedWorkerGlobalScope - Web APIs
ry data. WindowTimers.clearInterval() Cancels the repeated execution set using WindowTimers.setInterval(). WindowTimers.clearTimeout() Cancels the repeated execution set using WindowTimers.setTimeout(). WindowTimers.setInterval() Schedules the execution of a function every X milliseconds. WindowTimers.setTimeout() Sets a delay for executing a function. Events Listen to this event using addEventListener() or by assigning an event listener to the oneventname property of this interface. connect Fired on shared workers when a new client connects. Also available via the onconnect property. Specifications Specification Status Comment HTML Living StandardThe definition of 'SharedWorkerGlobalScope' in that specification. Living Standard ...
SourceBuffer.abort() - Web APIs
SE API is fully asynchronous, but this step seems to suggest a synchronous (blocking) operation, which doesn't make sense. Saying that, current implementations can be useful in certain situations, when you want to stop the current append (or whatever) operation occuring on a sourcebuffer, and then immediately start performing operations on it again. For example, consider this code: sourceBuffer.addEventListener('updateend', function (_) { ... }); sourceBuffer.appendBuffer(buf); Let's say that after the call to appendBuffer BUT before the updateend event fires (i.e. a buffer is being appended but the operation has not yet completed) a user "scrubs" the video seeking to a new point in time. In this case you would want to manually call abort() on the source buffer to stop the decoding of the current b...
SourceBuffer - Web APIs
= 'frag_bunny.mp4'; // Need to be specific for Blink regarding codecs // ./mp4info frag_bunny.mp4 | grep Codec var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'; if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) { var mediaSource = new MediaSource(); //console.log(mediaSource.readyState); // closed video.src = URL.createObjectURL(mediaSource); mediaSource.addEventListener('sourceopen', sourceOpen); } else { console.error('Unsupported MIME type or codec: ', mimeCodec); } function sourceOpen (_) { //console.log(this.readyState); // open var mediaSource = this; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); fetchAB(assetURL, function (buf) { sourceBuffer.addEventListener('updateend', function (_) { mediaSource.endOfStream(); vid...
SpeechRecognition: audioend event - Web APIs
The audioend event of the Web Speech API is fired when the user agent has finished capturing audio for speech recognition. Bubbles No Cancelable No Interface Event Event handler onaudioend Examples You can use the audioend event in an addEventListener method: var recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener('audioend', function() { console.log('Audio capturing ended'); }); Or use the onaudioend event handler property: recognition.onaudioend = function() { console.log('Audio capturing ended'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech recognition events' in that specification. Draft ...
SpeechRecognition: audiostart event - Web APIs
tart event of the Web Speech API is fired when the user agent has started to capture audio for speech recognition. Bubbles No Cancelable No Interface Event Event handler onaudiostart Examples You can use the audiostart event in an onaudiostart method: var recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener('audiostart', function() { console.log('Audio capturing started'); }); Or use the onaudiostart event handler property: recognition.onaudiostart = function() { console.log('Audio capturing started'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech recognition events' in that specification. Draft ...
SpeechRecognition: end event - Web APIs
The end event of the Web Speech API SpeechRecognition object is fired when the speech recognition service has disconnected. Bubbles No Cancelable No Interface Event Event handler property onend Examples You can use the end event in an addEventListener method: var recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener('end', function() { console.log('Speech recognition service disconnected'); }); Or use the onend event handler property: recognition.onend = function() { console.log('Speech recognition service disconnected'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech recognition events' in that specification. Draft...
SpeechRecognition: soundstart event - Web APIs
The soundstart event of the Web Speech API is fired when any sound -- recognisable speech or not -- has been detected. Bubbles No Cancelable No Interface Event Event handler property onsoundstart Examples You can use the soundstart event in an addEventListener method: var recognition = new webkitSpeechRecognition() || new SpeechRecognition(); recognition.addEventListener('soundstart', function() { console.log('Some sound is being received'); }); Or use the onsoundstart event handler property: recognition.onsoundstart = function() { console.log('Some sound is being received'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech recognition events' in that specification. ...
SpeechRecognition - Web APIs
sult. SpeechRecognition.start() Starts the speech recognition service listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition. SpeechRecognition.stop() Stops the speech recognition service from listening to incoming audio, and attempts to return a SpeechRecognitionResult using the audio captured so far. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. audiostart Fired when the user agent has started to capture audio. Also available via the onaudiostart property. audioend Fired when the user agent has finished capturing audio. Also available via the onaudioend property. end Fired when the speech recognition service has disconnected. Also available via ...
SpeechSynthesis - Web APIs
current device. SpeechSynthesis.pause() Puts the SpeechSynthesis object into a paused state. SpeechSynthesis.resume() Puts the SpeechSynthesis object into a non-paused state: resumes it if it was already paused. SpeechSynthesis.speak() Adds an utterance to the utterance queue; it will be spoken when any other utterances queued before it have been spoken. Events Listen to this event using addEventListener() or by assigning an event listener to the oneventname property of this interface. voiceschanged Fired when the list of SpeechSynthesisVoice objects that would be returned by the SpeechSynthesis.getVoices() method has changed. Also available via the onvoiceschanged property. Examples First, a simple example: let utterance = new SpeechSynthesisUtterance("Hello world!"); speechSynthesis.sp...
SpeechSynthesisUtterance: mark event - Web APIs
The mark event of the Web Speech API SpeechSynthesisUtterance object is fired when the spoken utterance reaches a named SSML "mark" tag. Bubbles No Cancelable No Interface SpeechSynthesisEvent Event handler property onmark Examples You can use the mark event in an addEventListener method: utterThis.addEventListener('mark', function(event) { console.log('A mark was reached: ' + event.name); }); Or use the onmark event handler property: utterThis.onmark = function(event) { console.log('A mark was reached: ' + event.name); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech synthesis utterance events' in that specification. Draft ...
SpeechSynthesisUtterance: pause event - Web APIs
The pause event of the Web Speech API SpeechSynthesisUtterance object is fired when the utterance is paused part way through. Bubbles No Cancelable No Interface SpeechSynthesisEvent Event handler property onpause Examples You can use the pause event in an addEventListener method: utterThis.addEventListener('pause', function(event) { console.log('Speech paused after ' + event.elapsedTime + ' milliseconds.'); }); Or use the onpause event handler property: utterThis.onpause = function(event) { console.log('Speech paused after ' + event.elapsedTime + ' milliseconds.'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech synthesis utterance events' in that specification. D...
SpeechSynthesisUtterance: resume event - Web APIs
The resume event of the Web Speech API SpeechSynthesisUtterance object is fired when a paused utterance is resumed. Bubbles No Cancelable No Interface SpeechSynthesisEvent Event handler property onresume Examples You can use the resume event in an addEventListener method: utterThis.addEventListener('resume', function(event) { console.log('Speech resumed after ' + event.elapsedTime + ' milliseconds.'); }); Or use the onresume event handler property: utterThis.onresume = function(event) { console.log('Speech resumed after ' + event.elapsedTime + ' milliseconds.'); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech synthesis utterance events' in that specification. Draft ...
SpeechSynthesisUtterance: start event - Web APIs
The start event of the Web Speech API SpeechSynthesisUtterance object is fired when the utterance has begun to be spoken. Bubbles No Cancelable No Interface SpeechSynthesisEvent Event handler property onstart Examples You can use the start event in an addEventListener method: utterThis.addEventListener('start', function(event) { console.log('We have started uttering this speech: ' + event.utterance.text); }); Or use the onstart event handler property: utterThis.onstart = function(event) { console.log('We have started uttering this speech: ' + event.utterance.text); } Specifications Specification Status Comment Web Speech APIThe definition of 'speech synthesis utterance events' in that specification. D...
SpeechSynthesisUtterance - Web APIs
ts the speed at which the utterance will be spoken at. SpeechSynthesisUtterance.text Gets and sets the text that will be synthesised when the utterance is spoken. SpeechSynthesisUtterance.voice Gets and sets the voice that will be used to speak the utterance. SpeechSynthesisUtterance.volume Gets and sets the volume that the utterance will be spoken at. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. boundary Fired when the spoken utterance reaches a word or sentence boundary. Also available via the onboundary property. end Fired when the utterance has finished being spoken. Also available via the onend property. error Fired when an error occurs that prevents the utterance from being succesfully spoke...
Using the Storage Access API - Web APIs
// set a cookie localStorage.setItem("username", "John"); // access a localStorage entry }).catch(_ => { // error obtaining storage access. }); Note that access requests are automatically denied unless the embedded content is currently processing a user gesture such as a tap or click -- so this code needs to be run inside some kind of user gesture-based event handler, for example: btn.addEventListener('click', () => { // run code here }); ...
Using readable streams - Web APIs
ueuing chunks to it. ...
SubmitEvent.submitter - Web APIs
ples In this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. Each of the submit elements' id is used to identify which payment processor the button corresponds to. let form = document.querySelector("form"); form.addEventListener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processOrder(form, handler); } else { showAlertMessage("An unknown or unaccepted payment type was selected. Please try again.", "OK"); } }); The handler ID is obtained by using the submit event's submitter property to get the submit button, from which we then get the ID. With t...
SubmitEvent - Web APIs
ples In this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. Each of the submit elements' id is used to identify which payment processor the button corresponds to. let form = document.querySelector("form"); form.addEventListener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processOrder(form, handler); } else { showAlertMessage("An unknown or unaccepted payment type was selected. Please try again.", "OK"); } }); The handler ID is obtained by using the submit event's submitter property to get the submit button, from which we then get the ID. With t...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
desired chapter, which begins at the cue's start position and ends at the cue's end position. Example In this example, we configure the text track's cues so that every time a cue is finished, the video automatically pauses playback. This is done by setting the pauseOnExit property on each cue to true. However, to ensure that the track's cues are available, we first set mode to showing. window.addEventListener("load", event => { let trackElem = document.querySelector("track"); let track = trackElem.track; track.mode = "showing"; for (let index=0; index < track.cues.length; index++) { let cue = track.cues[index]; cue.pauseOnExit = true; }; }); Specifications Specification Status Comment HTML Living StandardThe definition of 'mode' in that specification. ...
TextTrackList: addtrack event - Web APIs
The addtrack event is fired when a track is added to a TextTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onaddtrack Examples Using addEventListener(): const mediaElement = document.querySelector('video, audio'); mediaElement.textTracks.addEventListener('addtrack', (event) => { console.log(`Text track: ${event.track.label} added`); }); Using the onaddtrack event handler property: const mediaElement = document.querySelector('video, audio'); mediaElement.textTracks.onaddtrack = (event) => { console.log(`Text track: ${event.track.label} added`); }; Specifications Specification Status HTML Living StandardThe definition of 'addtrack' in that specification. Living Standard ...
TextTrackList: change event - Web APIs
The change event is fired when a text track is made active or inactive, or a textTrackList is otherwise changed. Bubbles No Cancelable No Interface Event Event handler property onchange Examples Using addEventListener(): const mediaElement = document.querySelectorAll('video, audio')[0]; mediaElement.textTracks.addEventListener('change', (event) => { console.log(`'${event.type}' event fired`); }); Using the onchange event handler property: const mediaElement = document.querySelector('video, audio'); mediaElement.textTracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; Specifications Specification Status HTML Living StandardThe definition of 'change' in that specification. Living Standar...
TextTrackList.onaddtrack - Web APIs
erty onaddtrack is an event handler which is called when the addtrack event occurs, indicating that a new text track has been added to the media element whose text tracks the TextTrackList represents. The event is passed into the event handler in the form of a TrackEvent object, whose track property identifies the newly-added track. Note: You can also add a handler for the addtrack event using addEventListener(). Syntax TextTrackList.onaddtrack = eventHandler; Value Set onaddtrack to a function that accepts as input a TrackEvent object which indicates in its track property which video track has been added to the media. Usage notes The addtrack event is called whenever a new track is added to the media element whose video tracks are represented by the TextTrackList object. This happens when track...
TextTrackList.onchange - Web APIs
Syntax TextTrackList.onchange = eventHandler; Example This snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. ...
TextTrackList.onremovetrack - Web APIs
alled when the removetrack event occurs, indicating that a text track has been removed from the media element, and therefore also from the TextTrackList. The event is passed into the event handler in the form of a TrackEvent object, whose track property identifies the track that was removed from the media element's TextTrackList. Note: You can also add a handler for the removetrack event using addEventListener(). Syntax TextTrackList.onremovetrack = eventHandler; Value Set onremovetrack to a function that accepts as input a TrackEvent object which indicates in its track property which text track has been removed from the media element. Example This simple example just fetches the current number of text tracks in the first media element whenever a track is removed from the media element. documen...
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
Web › API › Touch › clientX
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
Web › API › Touch › clientY
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
Web › API › Touch › force
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
Web › API › Touch › identifier
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
Web › API › Touch › pageX
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
Web › API › Touch › pageY
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
Web › API › Touch › radiusX
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
Web › API › Touch › screenX
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
Web › API › Touch › target
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
Web › API › TouchEvent › altKey
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
Web › API › TouchList › item
. 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. ...
TouchList.length - Web APIs
Web › API › TouchList › length
The length read-only property indicates the number of items (touch points) in a given TouchList. Syntax var numTouches = touchList.length; Return value numTouches The number of touch points in touchList. Example This code example illustrates the use of the TouchList interface's item method and the length property. ...
Touch events - Web APIs
hod. Create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> Your browser does not support canvas element. </canvas> <br> Log: <pre id="log" style="border: 1px solid #ccc;"></pre> Setting up the event handlers When the page loads, the startup() function shown below will be called. function startup() { var el = document.getElementById("canvas"); el.addEventListener("touchstart", handleStart, false); el.addEventListener("touchend", handleEnd, false); el.addEventListener("touchcancel", handleCancel, false); el.addEventListener("touchmove", handleMove, false); } document.addEventListener("DOMContentLoaded", startup); This simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they occur. Tracking new touch...
VTTCue - Web APIs
Web › API › VTTCue
of all the lines of text within the cue box. VTTCue.text Returns a DOMString with the contents of the cue. Methods getCueAsHTML() Returns the cue text as a DocumentFragment. Example HTML <video controls src="https://udn.realityripple.com/samples/c6/f8a3489533.webm"></video> CSS video { width: 320px; height: 180px; } JavaScript let video = document.querySelector('video'); video.addEventListener('loadedmetadata', () => { const track = video.addTextTrack("captions", "????Subtitles", "zh_CN"); track.mode = "showing"; const cueCn = new VTTCue(0, 2.500, '????0?2.5????'); track.addCue(cueCn); const cueEn = new VTTCue(2.6, 4, 'Subtitles will display between 2.6 and 4 seconds'); track.addCue(cueEn); }); Result Chrome: Please Open in JSFiddle to view the live sample. Embed li...
VideoTrackList: addtrack event - Web APIs
The addtrack event is fired when a track is added to a VideoTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onaddtrack Examples Using addEventListener(): const videoElement = document.querySelector('video'); videoElement.videoTracks.addEventListener('addtrack', (event) => { console.log(`Video track: ${event.track.label} added`); }); Using the onaddtrack event handler property: const videoElement = document.querySelector('video'); videoElement.videoTracks.onaddtrack = (event) => { console.log(`Video track: ${event.track.label} added`); }; Specifications Specification Status HTML Living StandardThe definition of 'addtrack' in that specification. Living Standard ...
VideoTrackList.onaddtrack - Web APIs
y onaddtrack is an event handler which is called when the addtrack event occurs, indicating that a new video track has been added to the media element whose video tracks the VideoTrackList represents. The event is passed into the event handler in the form of a TrackEvent object, whose track property identifies the newly-added track. Note: You can also add a handler for the addtrack event using addEventListener(). Syntax VideoTrackList.onaddtrack = eventHandler; Value Set onaddtrack to a function that accepts as input a TrackEvent object which indicates in its track property which video track has been added to the media. Usage notes The addtrack event is called whenever a new track is added to the media element whose video tracks are represented by the VideoTrackList object. This happens when tra...
VideoTrackList.onchange - Web APIs
ed when the change event occurs, indicating that a VideoTrack in the VideoTrackList has been made active. The event is passed into the event handler in the form of an Event object; the event doesn't provide any additional information. To determine the new state of media's tracks, you'll have to look at their VideoTrack.selected flags. Note: You can also add a handler for the change event using addEventListener(). Syntax VideoTrackList.onchange = eventHandler; Value Set onchange to a function that should be called whenever a track is made active. Example This snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. var trackList = document.quer...
VideoTrackList.onremovetrack - Web APIs
ed when the removetrack event occurs, indicating that a video track has been removed from the media element, and therefore also from the VideoTrackList. The event is passed into the event handler in the form of a TrackEvent object, whose track property identifies the track that was removed from the media element's VideoTrackList. Note: You can also add a handler for the removetrack event using addEventListener(). Syntax VideoTrackList.onremovetrack = eventHandler; Value Set onremovetrack to a function that accepts as input a TrackEvent object which indicates in its track property which video track has been removed from the media element. Example This simple example just fetches the current number of video tracks in the media element whenever a track is removed from the media element. document.q...
VideoTrackList: removetrack event - Web APIs
The removetrack event is fired when a track is removed from a VideoTrackList. Bubbles No Cancelable No Interface TrackEvent Event handler property onremovetrack Examples Using addEventListener(): const videoElement = document.querySelector('video'); videoElement.videoTracks.addEventListener('removetrack', (event) => { console.log(`Video track: ${event.track.label} removed`); }); Using the onremovetrack event handler property: const videoElement = document.querySelector('video'); videoElement.videoTracks.onremovetrack = (event) => { console.log(`Video track: ${event.track.label} removed`); }; Specifications Specification Status HTML Living StandardThe definition of 'removetrack' in that specification. Living Standa...
VisualViewport: resize event - Web APIs
The resize event of the VisualViewport interface is fired when the visual viewport is resized. Bubbles No Cancelable No Interface Event Event handler property onresize Examples You can use the resize event in an addEventListener method: visualViewport.addEventListener('resize', function() { ... }); Or use the onresize event handler property: visualViewport.onresize = function() { ... }; Specifications Specification Status Comment Visual Viewport APIThe definition of 'VisualViewport events' in that specification. Draft Initial definition ...
VisualViewport: scroll event - Web APIs
The scroll event of the VisualViewport interface is fired when the visual viewport is scrolled. Bubbles No Cancelable No Interface Event Event handler property onscroll Examples You can use the scroll event in an addEventListener method: visualViewport.addEventListener('scroll', function() { ... }); Or use the onscroll event handler property: visualViewport.onscroll = function() { ... }; Specifications Specification Status Comment Visual Viewport APIThe definition of 'VisualViewport events' in that specification. Draft Initial definition ...
Visual Viewport API - Web APIs
ight + 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); Specifications Specification Status Comment Visual Viewport APIThe definition of 'VisualViewport' in that specification. Draft Initial definition. ...
WEBGL_lose_context.loseContext() - Web APIs
It triggers the steps described in the WebGL specification for handling context lost. The context will remain lost until WEBGL_lose_context.restoreContext() is called. Syntax gl.getExtension('WEBGL_lose_context').loseContext(); Examples With this method, you can simulate the webglcontextlost event: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').loseContext(); // WebGLContextEvent event with type "webglcontextlost" is logged. Specifications Specification Status Comment WEBGL_lose_contextThe definition of 'WEBGL_lose_context.loseContext' in that specification. Recommendation Initial definition. ...
WEBGL_lose_context.restoreContext() - Web APIs
he WebGL API and allows you to simulate restoring the context of a WebGLRenderingContext object. Syntax gl.getExtension('WEBGL_lose_context').restoreContext(); Errors thrown INVALID_OPERATION if the context was not lost. Examples With this method, you can simulate the webglcontextrestored event: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').restoreContext(); Specifications Specification Status Comment WEBGL_lose_contextThe definition of 'WEBGL_lose_context.loseContext' in that specification. Recommendation Initial definition. ...
WEBGL_lose_context - Web APIs
is available to both, WebGL1 and WebGL2 contexts. Methods WEBGL_lose_context.loseContext() Simulates losing the context. WEBGL_lose_context.restoreContext() Simulates restoring the context. Examples With this extension, you can simulate the webglcontextlost and webglcontextrestored events: const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', (event) => { console.log(event); }); gl.getExtension('WEBGL_lose_context').loseContext(); // WebGLContextEvent event with type "webglcontextlost" is logged. Specifications Specification Status Comment WEBGL_lose_contextThe definition of 'WEBGL_lose_context' in that specification. Recommendation Initial definition. ...
WakeLockSentinel.release() - Web APIs
has been successfully released. Syntax WakeLockSentinel.release().then(...); Parameters None. Return value Returns a Promise that resolves with undefined Exceptions No exceptions are thrown. You should always listen for the onrelease event to check if a wake lock has been released. Examples In this example, when a user clicks a button the WakeLockSentinel is released. wakeLockOffButton.addEventListener('click', () => { WakeLockSentinel.release(); }) Specifications Specification Status Comment Screen Wake Lock APIThe definition of 'release()' in that specification. Unknown Initial definition. ...
WebGLContextEvent.statusMessage - Web APIs
age property contains additional event status information, or is an empty string if no additional information is available. Examples The statusMessage property can contain a platform dependent string with details of an event. This can occur, for example, if the webglcontextcreationerror event is fired. var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextcreationerror', function(e) { console.log('WebGL context creation failed:' + e.statusMessage || 'Unknown error'); }, false); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLContextEvent.statusMessage' in that specification. Recommendation Initial definition. ...
WebGLContextEvent - Web APIs
property containing additional information about the event. Methods This interface doesn't define any own methods, but inherits methods from its parent interface, Event. Examples With the help of the WEBGL_lose_context extension, you can simulate the webglcontextlost and webglcontextrestored events: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').loseContext(); // WebGLContextEvent event with type "webglcontextlost" is logged. Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLContextEvent' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext - Web APIs
g shape, size, and position. ...
A basic 2D WebGL animation example - Web APIs
]; // Vertex information let vertexArray; let vertexBuffer; let vertexNumComponents; let vertexCount; // Rendering data shared with the // scalers. ...
Basic scissoring - Web APIs
rawing command (in this case, clear()) that starts the processing of fragments down the graphics pipeline. <p>Result of of scissoring.</p> <canvas>Your browser does not seem to support HTML5 canvas.</canvas> body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } window.addEventListener("load", function setupWebGL (evt) { "use strict" window.removeEventListener(evt.type, setupWebGL, false); var paragraph = document.querySelector("p"); var canvas = document.querySelector("canvas"); // The following two lines set the size (in CSS pixels) of // the drawing buffer to be identical to the size of the // canvas HTML element, as determined by CSS. canvas.width = canvas.
Canvas size and WebGL - Web APIs
shape, size, and position. ...
Clearing with colors - Web APIs
t : 210px; margin : auto; padding : 0; border : none; background-color : black; } // Run everything inside window load event handler, to make sure // DOM is fully loaded and styled before trying to manipulate it, // and to not mess up the global scope. We are giving the event // handler a name (setupWebGL) so that we can refer to the // function object within the function itself. window.addEventListener("load", function 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); // References to the document elements. var paragraph = document.querySelector("p"), canvas = document.querySelector("canvas"); // Getting the WebGL rendering context. v...
Detect WebGL - Web APIs
each API. <p>[ Here would go the result of WebGL feature detection ]</p> <button>Press here to detect WebGLRenderingContext</button> body { text-align : center; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } // Run everything inside window load event handler, to make sure // DOM is fully loaded and styled before trying to manipulate it. window.addEventListener("load", function() { var paragraph = document.querySelector("p"), button = document.querySelector("button"); // Adding click event handler to button. button.addEventListener("click", detectWebGLContext, false); function detectWebGLContext () { // Create canvas element. The canvas is not added to the // document itself, so it is never displayed in the // browser window. ...
Hello GLSL - Web APIs
t-size : inherit; margin : auto; padding : 0.6em; } <script type="x-shader/x-vertex" id="vertex-shader"> #version 100 void main() { gl_Position = vec4(0.0, 0.0, 0.0, 1.0); gl_PointSize = 64.0; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 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...
Raining rectangles - Web APIs
ng>0</strong>.</p> <canvas>Your browser does not seem to support HTML5 canvas.</canvas> body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } ;(function(){ "use strict" window.addEventListener("load", setupAnimation, false); var gl, timer, rainingRect, scoreDisplay, missesDisplay; function setupAnimation (evt) { window.removeEventListener(evt.type, setupAnimation, false); if (!(gl = getRenderingContext())) return; gl.enable(gl.SCISSOR_TEST); rainingRect = new Rectangle(); timer = setTimeout(drawAnimation, 17); document.querySelector("canvas") .addEventLis...
Textures from code - Web APIs
; } </script> <script type="x-shader/x-fragment" id="fragment-shader"> #version 100 precision mediump float; void main() { vec2 fragmentPosition = 2.0*gl_PointCoord - 1.0; float distance = length(fragmentPosition); float distanceSqrd = distance * distance; gl_FragColor = vec4( 0.2/distanceSqrd, 0.1/distanceSqrd, 0.0, 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...
Signaling and video calling - Web APIs
of strings specifying the user names of every connected user. function handleUserlistMsg(msg) { var i; var listElem = document.querySelector(".userlistbox"); while (listElem.firstChild) { listElem.removeChild(listElem.firstChild); } msg.users.forEach(function(username) { var item = document.createElement("li"); item.appendChild(document.createTextNode(username)); item.addEventListener("click", invite, false); listElem.appendChild(item); }); } After getting a reference to the <ul> which contains the list of user names into the variable listElem, we empty the list by removing each of its child elements. Note: Obviously, it would be more efficient to update the list by adding and removing individual users instead of rebuilding the whole list every time it changes, but t...
A simple RTCDataChannel sample - Web APIs
nction is called. function startup() { connectButton = document.getElementById('connectButton'); disconnectButton = document.getElementById('disconnectButton'); sendButton = document.getElementById('sendButton'); messageInputBox = document.getElementById('message'); receiveBox = document.getElementById('receivebox'); // Set event listeners for user interface widgets connectButton.addEventListener('click', connectPeers, false); disconnectButton.addEventListener('click', disconnectPeers, false); sendButton.addEventListener('click', sendMessage, false); } This is quite straightforward. We grab references to all the page elements we'll need to access, then set event listeners on the three buttons. Establishing a connection When the user clicks the "Connect" button, the connectPeers() m...
WebSocket: close event - Web APIs
terface CloseEvent Event handler property onclose Examples You might want to know when the connection has been closed so that you can update the UI or, perhaps, save data about the closed connection. Given that you have a variable called exampleSocket that refers to an opened WebSocket, this handler would handle the situation where the socket has been closed. ...
WebSocket: error event - Web APIs
The error event is fired when a connection with a WebSocket has been closed due to an error (some data couldn't be sent for example). Bubbles No Cancelable No Interface Event Event handler property onerror Examples // Create WebSocket connection const socket = new WebSocket('ws://localhost:8080'); // Listen for possible errors socket.addEventListener('error', function (event) { console.log('WebSocket error: ', event); }); Specifications Specification Status HTML Living StandardThe definition of 'WebSocket error' in that specification. Living Standard ...
WebSocket: message event - Web APIs
The message event is fired when data is received through a WebSocket. Bubbles No Cancelable No Interface MessageEvent Event handler property onmessage Examples // Create WebSocket connection. const socket = new WebSocket('ws://localhost:8080'); // Listen for messages socket.addEventListener('message', function (event) { console.log('Message from server ', event.data); }); Specifications Specification Status HTML Living StandardThe definition of 'WebSocket message' in that specification. Living Standard ...
WebSocket.onerror - Web APIs
Web › API › WebSocket › onerror
Syntax webSocket.onerror = eventHandler; Value A function or EventHandler which is executed whenever an error event occurs on the WebSocket connection. ...
WebSocket: open event - Web APIs
The open event is fired when a connection with a WebSocket is opened. Bubbles No Cancelable No Interface Event Event handler property onopen Examples // Create WebSocket connection. const socket = new WebSocket('ws://localhost:8080'); // Connection opened socket.addEventListener('open', (event) => { socket.send('Hello Server!'); }); Specifications Specification Status HTML Living StandardThe definition of 'WebSocket open' in that specification. Living Standard ...
Writing a WebSocket server in C# - Web APIs
textarea> <button>send</button> <div id=output></div> <script> // http://www.websocket.org/echo.html var button = document.querySelector("button"), output = document.querySelector("#output"), textarea = document.querySelector("textarea"), // wsUri = "ws://echo.websocket.org/", wsUri = "ws://127.0.0.1/", websocket = new WebSocket(wsUri); button.addEventListener("click", onClickButton); websocket.onopen = function (e) { writeToScreen("CONNECTED"); doSend("WebSocket rocks"); }; websocket.onclose = function (e) { writeToScreen("DISCONNECTED"); }; websocket.onmessage = function (e) { writeToScreen("<span>RESPONSE: " + e.data + "</span>"); }; websocket.onerror = function (e) { writeToScr...
Starting up and shutting down a WebXR session - Web APIs
ext as the source for the XR system by creating an XRWebGLLayer and passing set the value of the session's renderState property baseLayer. Perform calculations for the initial position and scale of your objects as needed. Begin the frame rendering cycle. ...
Web audio spatialization basics - Web APIs
(() => moveBoombox(direction, move)); return move; } Wiring up our controls Wiring up out control buttons is comparatively simple -- now we can listen for a mouse event on our controls and run this function, as well as stop it when the mouse is released: // for each of our controls, move the boombox and change the position values moveControls.forEach(function(el) { let moving; el.addEventListener('mousedown', function() { let direction = this.dataset.control; if (moving && moving.frameId) { window.cancelAnimationFrame(moving.frameId); } moving = moveBoombox(direction); }, false); window.addEventListener('mouseup', function() { if (moving && moving.frameId) { window.cancelAnimationFrame(moving.frameId); } ...
Using the Web Storage API - Web APIs
is made to the Storage object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes -- it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects. ...
Using Web Workers - Web APIs
port object -- an explicit port is opened that the scripts can use to communicate with the worker (this is done implicitly in the case of dedicated workers). The port connection needs to be started either implicitly by use of the onmessage event handler or explicitly with the start() method before any messages can be posted. Calling start() is only needed if the message event is wired up via the addEventListener() method. Note: When using the start() method to open the port connection, it needs to be called from both the parent thread and the worker thread if two-way communication is needed. Sending messages to and from a shared worker Now messages can be sent to the worker as before, but the postMessage() method has to be invoked through the port object (again, you'll see similar constructs in both...
Window: DOMContentLoaded event - Web APIs
has loaded. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Document: DOMContentLoaded event. ...
Window: animationcancel event - Web APIs
Event handler property onanimationcancel The original target for this event is the Element that had the animation applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationcancel. Examples This code adds a listener to the animationcancel event. window.addEventListener('animationcancel', () => { console.log('Animation canceled'); }); The same, but using the onanimationcancel property instead of addEventListener(): window.onanimationcancel = () => { console.log('Animation canceled'); }; See a live example of this event. Specifications Specification Status Comment CSS Animations Working Draft Initial definition ...
Window: animationend event - Web APIs
tionEvent Event handler property onanimationend The original target for this event is the Element that had the animation applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationend. Examples This example listens for the animationend event: window.addEventListener('animationend', () => { console.log('Animation ended'); }); The same, but using the onanimationend event handler property: window.onanimationend = () => { console.log('Animation ended'); }; See a live example of this event. Specifications Specification Status Comment CSS Animations Working Draft Initial definition ...
Window: animationiteration event - Web APIs
for this event is the Element that had the animation applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationiteration. Examples This code uses animationiteration to keep track of the number of iterations an animation has completed: let iterationCount = 0; window.addEventListener('animationiteration', () => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }); The same, but using the onanimationiteration event handler property: let iterationCount = 0; window.onanimationiteration = () => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }; See a live example of this event. Specifications S...
Window: animationstart event - Web APIs
roperty onanimationstart The original target for this event is the Element that had the animation applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: animationstart. Examples This listens for the animationstart event and logs a message when it is fired: window.addEventListener('animationstart', () => { console.log('Animation started'); }); The same, but using onanimationstart: window.onanimationstart = () => { console.log('Animation started'); }; See a live example of this event. Specifications Specification Status Comment CSS Animations Working Draft Initial definition ...
Window: beforeunload event - Web APIs
r WebKit's Page Cache. The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML specification for more details. Examples The HTML specification states that authors should use the Event.preventDefault() method instead of using Event.returnValue. However, this is not supported by all browsers. window.addEventListener('beforeunload', (event) => { // Cancel the event as stated by the standard. event.preventDefault(); // Chrome requires returnValue to be set. event.returnValue = ''; }); Specifications Specification Status Comment HTML Living StandardThe definition of 'beforeunload' in that specification. Living Standard HTML5The definition of 'beforeunload' ...
Window.clearImmediate() - Web APIs
expected to become standard, and is only implemented by recent builds of Internet Explorer and Node.js 0.10+. It meets resistance both from Gecko (Firefox) and Webkit (Google/Apple). Syntax window.clearImmediate( immediateID ) where immediateID is a ID returned by window.setImmediate. Examples let immediateID = setImmediate(() => { // Run some code } document.getElementById("button") .addEventListener(() => { clearImmediate(immediateID); }); Specifications Specification Status Comment Efficient Script Yielding The definition of 'setImmediate' in that specification. Editor's Draft Initial definition. ...
Window: clipboardchange event - Web APIs
The clipboardchange event fires when the system clipboard content changes. Bubbles No Cancelable No Interface ClipboardEvent Event handler property None Examples JavaScript window.addEventListener('clipboardchange', () => { console.log('Clipboard contents changed'); }); Specifications Specification Status Clipboard API and eventsThe definition of 'clipboardchange event' in that specification. Working Draft ...
Window: copy event - Web APIs
Web › API › Window › copy event
ncelable Yes Interface ClipboardEvent Event handler property oncopy The original target for this event is the Element that was the intended target of the copy action. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: copy event. Examples window.addEventListener('copy', (event) => { console.log('copy action initiated') }); Specifications Specification Status Clipboard API and events Working Draft ...
Window: cut event - Web APIs
Web › API › Window › cut event
Cancelable Yes Interface ClipboardEvent Event handler property oncut The original target for this event is the Element that was the intended target of the cut action. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: cut event. Examples window.addEventListener('cut', (event) => { console.log('cut action initiated') }); Specifications Specification Status Clipboard API and events Working Draft ...
Window.devicePixelRatio - Web APIs
px. The updatePixelRatio() function fetches the current value of devicePixelRatio, then sets the innerText of the element pixelRatioBox to a string which displays the ratio both as a percentage and as a raw decimal value with up to two decimal places. Then the updatePixelRatio() function is called once to display the starting value, after which the media query is created using matchMedia() and addEventListener() is called to set up updatePixelRatio() as a handler for the change event. HTML The HTML creates the boxes containing the instructions and the pixel-ratio box that will display the current pixel ratio information. <div class="container"> <div class="inner-container"> <p>This example demonstrates the effect of zooming the page in and out (or moving it to a screen with a different ...
Window: devicemotion event - Web APIs
ailable. Bubbles No Cancelable No Interface DeviceMotionEvent Event handler property Window.ondevicemotion Examples function handleMotionEvent(event) { var x = event.accelerationIncludingGravity.x; var y = event.accelerationIncludingGravity.y; var z = event.accelerationIncludingGravity.z; // Do something awesome. } window.addEventListener("devicemotion", handleMotionEvent, true); Specifications Specification Status DeviceOrientation Event SpecificationThe definition of 'DeviceMotion event' in that specification. Editor's Draft ...
Window: deviceorientation event - Web APIs
tion of the device as compared to the Earth coordinate frame. This data is gathered from a magnetometer inside the device. See Orientation and motion data explained for details. ...
Window: error event - Web APIs
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; } button { height: 2rem; margin: .5rem; } img { width: 0; height: 0; } JS const log = document.querySelector('.event-log-contents'); window.addEventListener('error', (event) => { log.textContent = log.textContent + `${event.type}: ${event.message}\n`; console.log(event) }); const scriptError = document.querySelector('#script-error'); scriptError.addEventListener('click', () => { const badCode = 'const s;'; eval(badCode); }); Result Specifications Specification Status UI Events Working Draft ...
Window: gamepadconnected event - Web APIs
The gamepadconnected event is fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used. ...
Window: gamepaddisconnected event - Web APIs
The gamepaddisconnected event is fired when the browser detects that a gamepad has been disconnected. ...
Window: languagechange event - Web APIs
The languagechange event is fired at the global scope object when the user's preferred language changes. Bubbles No Cancelable No Interface Event Event handler onlanguagechange Examples You can use the languagechange event in an addEventListener method: window.addEventListener('languagechange', function() { console.log('languagechange event detected!'); }); Or use the onlanguagechange event handler property: window.onlanguagechange = function(event) { console.log('languagechange event detected!'); }; Specification Specification Status HTML Living StandardThe definition of 'languagechange' in that specification. Living Standard ...
window.location - Web APIs
Web › API › Window › location
rollY + (_nodeY - _scrollY) * _itFrame / nFrames); document.documentElement.scrollLeft = Math.round(_scrollX + (_nodeX - _scrollX) * _itFrame / nFrames); if (_useHash && _itFrame === nFrames) { location.hash = _bookMark; } _itFrame++; } function _chkOwner () { if (_isBot) { _isBot = false; return; } if (_scrollId > -1) { clearInterval(_scrollId); _scrollId = -1; } } if (window.addEventListener) { window.addEventListener("scroll", _chkOwner, false); } else if (window.attachEvent) { window.attachEvent("onscroll", _chkOwner); } return function (sBookmark, bUseHash) { var oNode = document.querySelector(sBookmark); _scrollY = document.documentElement.scrollTop; _scrollX = document.documentElement.scrollLeft; _bookMark = sBookmark; _useHash = bUseHash === true; _nodeX = oN...
Window: message event - Web APIs
ble No Interface MessageEvent Event handler property onmessage Examples Suppose a script sends a message to a different browsing context, such as another <iframe>, using code like this: const targetFrame = window.top.frames[1]; const targetOrigin = 'https://example.org'; const windowMessageButton = document.querySelector('#window-message'); windowMessageButton.addEventListener('click', () => { targetFrame.postMessage('hello there', targetOrigin); }); The receiver can listen for the message using addEventListener() with code like this: window.addEventListener('message', (event) => { console.log(`Received message: ${event.data}`); }); Alternatively the listener could use the onmessage event handler property: window.onmessage = (event) => { console.log(`Re...
Window: offline event - Web APIs
The offline event of the Window interface is fired when the browser has lost access to the network and the value of Navigator.onLine switches to false. Bubbles No Cancelable No Interface Event Event handler property onoffline Examples // addEventListener version window.addEventListener('offline', (event) => { console.log("The network connection has been lost."); }); // onoffline version window.onoffline = (event) => { console.log("The network connection has been lost."); }; Specifications Specification Status HTML Living StandardThe definition of 'offline event' in that specification. Living Standard ...
window.ondeviceorientation - Web APIs
Summary An event handler for the deviceorientation event, which contains information about a relative device orientation change. Syntax window.ondeviceorientation = function(event) { ... }; window.addEventListener('deviceorientation', function(event) { ... }); Specifications Specification Status Comment DeviceOrientation Event Specification Editor's Draft Initial specification. ...
Window.ondeviceorientationabsolute - Web APIs
Summary An event handler for the deviceorientationabsolute event containing information about an absolute device orientation change. Syntax window.ondeviceorientationabsolute = function(event) { ... }; window.addEventListener('deviceorientationabsolute', function(event) { ... }); Specifications This event handler is not currently part of any specification. ...
Window: online event - Web APIs
ained access to the network and the value of Navigator.onLine switches to true. Note: This event shouldn't be used to determine the availability of a particular website. Network problems or firewalls might still prevent the website from being reached. Bubbles No Cancelable No Interface Event Event handler property ononline Examples // addEventListener version window.addEventListener('online', (event) => { console.log("You are now connected to the network."); }); // ononline version window.ononline = (event) => { console.log("You are now connected to the network."); }; Specifications Specification Status HTML Living StandardThe definition of 'online event' in that specification. Living Standard ...
Window: orientationchange event - Web APIs
The orientationchange event is fired when the orientation of the device has changed. Bubbles No Cancelable No Interface Event Event handler onorientationchange Example You can use the orientationchange event in an addEventListener method: window.addEventListener("orientationchange", function(event) { console.log("the orientation of the device is now " + event.target.screen.orientation.angle); }); Or use the onorientationchange event handler property: window.onorientationchange = function(event) { console.log("the orientation of the device is now " + event.target.screen.orientation.angle); }; Specifications Specification Status Compatibility StandardThe definition of 'orientationchange' in that specification. Li...
Window: pagehide event - Web APIs
e current page receives a pagehide event before the previous page is shown. Bubbles No Cancelable No Interface PageTransitionEvent Event handler property onpagehide Examples In this example, an event handler is established to watch for pagehide events and to perform special handling if the page is being persisted for possible reuse. ...
Window: pageshow event - Web APIs
Try loading new pages into this tab, then navigating forward and backward through history, noting the events' output to the log.</p> Results Specifications Specification Status Comment HTML Living StandardThe definition of 'pageshow' in that specifica...
Window: paste event - Web APIs
lable Yes Interface ClipboardEvent Event handler property onpaste The original target for this event is the Element that was the intended target of the paste action. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: paste event. Examples window.addEventListener('paste', (event) => { console.log('paste action initiated') }); Specifications Specification Status Clipboard API and events Working Draft ...
Window: popstate event - Web APIs
er chooses to do so. If the original and new entry's shared the same document, but had different fragments in their URLs, send the hashchange event to the window. As you can see, the popstate event is nearly the last thing done in the process of navigating pages in this way. ...
Window: rejectionhandled event - Web APIs
n event, which is sent when a promise is rejected but there is no hander for the rejection. Bubbles No Cancelable No Interface PromiseRejectionEvent Event handler property onrejectionhandled Example You can use the rejectionhandled event to log promises that get rejected to the console, along with the reasons why they were rejected: window.addEventListener("rejectionhandled", event => { console.log("Promise rejected; reason: " + event.reason); }, false); Specifications Specification Status Comment HTML Living StandardThe definition of 'rejectionhandled' in that specification. Living Standard Initial definition. ...
Window.sessionStorage - Web APIs
riting is lost. // Get the text field that we're going to track let field = document.getElementById("field"); // See if we have an autosave value // (this will only happen if the page is accidentally refreshed) if (sessionStorage.getItem("autosave")) { // Restore the contents of the text field field.value = sessionStorage.getItem("autosave"); } // Listen for changes in the text field field.addEventListener("change", function() { // And save the results into the session storage object sessionStorage.setItem("autosave", field.value); }); Note: Please refer to the Using the Web Storage API article for a full example. Specifications Specification Status Comment HTML Living StandardThe definition of 'sessionStorage' in that specification. Living Standard ...
Window: storage event - Web APIs
The storage event of the Window interface fires when a storage area (localStorage) has been modified in the context of another document. Bubbles No Cancelable No Interface StorageEvent Event handler property onstorage Examples Log the sampleList item to the console when the storage event fires: window.addEventListener('storage', () => { // When local storage changes, dump the list to // the console. console.log(JSON.parse(window.localStorage.getItem('sampleList'))); }); The same action can be achieved using the onstorage event handler property: window.onstorage = () => { // When local storage changes, dump the list to // the console. console.log(JSON.parse(window.localStorage.getItem('sampleList'))); }; Specifications ...
Window: transitioncancel event - Web APIs
erty GlobalEventHandlers.ontransitioncancel The original target for this event is the Element that had the transition applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitioncancel. Examples This code adds a listener to the transitioncancel event: window.addEventListener('transitioncancel', () => { console.log('Transition canceled'); }); The same, but using the ontransitioncancel property instead of addEventListener(): window.ontransitioncancel = () => { console.log('Transition canceled'); }; See a live example of this event. Specifications Specification Status Comment CSS TransitionsThe definition of 'transitioncancel' in tha...
Window: transitionend event - Web APIs
cel event is fired, the transitionend event will not fire. The original target for this event is the Element that had the transition applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitionend. Examples This code adds a listener to the transitionend event: window.addEventListener('transitionend', () => { console.log('Transition ended'); }); The same, but using the ontransitionend property instead of addEventListener(): window.ontransitionend = () => { console.log('Transition ended'); }; See a live example of this event. Specifications Specification Status Comment CSS TransitionsThe definition of 'transitionend' in that specification. ...
Window: transitionrun event - Web APIs
t Event handler property ontransitionrun The original target for this event is the Element that had the transition applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitionrun. Examples This code adds a listener to the transitionrun event: window.addEventListener('transitionrun', () => { console.log('Transition is running but hasn't necessarily started transitioning yet'); }); The same, but using the ontransitionrun property instead of addEventListener(): window.ontransitionrun = () => { console.log('Transition started running'); }; See a live example of this event. Specifications Specification Status Comment CSS Trans...
Window: transitionstart event - Web APIs
roperty GlobalEventHandlers.ontransitionstart The original target for this event is the Element that had the transition applied. You can listen for this event on the Window interface to handle it in the capture or bubbling phases. For full details on this event please see the page on HTMLElement: transitionstart. Examples This code adds a listener to the transitionstart event: window.addEventListener('transitionstart', () => { console.log('Started transitioning'); }); The same, but using the ontransitionstart property instead of addEventListener(): window.ontransitionrun = () => { console.log('Started transitioning'); }; See a live example of this event. Specifications Specification Status Comment CSS TransitionsThe definition of 'transitionstart' in that ...
WindowClient.focus() - Web APIs
The focus() method of the WindowClient interface gives user input focus to the current client and returns a Promise that resolves to the existing WindowClient. Syntax windowClient.focus().then(function(windowClient) { // do something with your WindowClient once it has been focused }); Parameters None. Return value A Promise that resolves to the existing WindowClient. ...
WindowClient.focused - Web APIs
The focused read-only property of the WindowClient interface is a Boolean that indicates whether the current client has focus. Syntax var myFocused = windowClient.focused; Value A Boolean. ...
WindowClient - Web APIs
ads a specified URL into a controlled client page. Properties WindowClient inherits properties from its parent interface, Client. WindowClient.focused Read only A boolean that indicates whether the current client has focus. WindowClient.visibilityState Read only Indicates the visibility of the current client. This value can be one of "hidden", "visible", or "prerender". ...
WindowEventHandlers.onafterprint - Web APIs
er the user prints, or if they abort the print dialog. The beforeprint and afterprint events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed. In general, you should prefer the use of an @media print CSS at-rule, but it may be necessary to use these events in some cases. Syntax window.addEventListener("afterprint", function(event) { ... }); window.onafterprint = function(event) { ... }; Specification Specification Status Comment HTML Living StandardThe definition of 'onafterprint' in that specification. Living Standard ...
WindowEventHandlers.onbeforeprint - Web APIs
s are raised before the print dialog window is opened. The beforeprint and afterprint events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed. In general, you should prefer the use of an @media print CSS at-rule, but it may be necessary to use these events in some cases. Syntax window.addEventListener("beforeprint", function(event) { ... }); window.onbeforeprint = function(event) { ... }; Polyfill Safari does not implement these events, but you can create an equivalent result to the beforeprint event with window.matchMedia('print'). var mediaQueryList = window.matchMedia('print'); mediaQueryList.addListener(function(mql) { if(mql.matches) { console.log('webkit equivalent of onbeforep...
WindowEventHandlers.onmessage - Web APIs
}) window.onmessage = function(event) { ... ...
WindowEventHandlers.onrejectionhandled - Web APIs
The onrejectionhandled property of the WindowEventHandlers mixin is the EventHandler for processing rejectionhandled events. These events are raised when Promises are rejected. Syntax window.addEventListener("rejectionhandled", function(event) { ... }); window.onrejectionhandled = function(event) { ...}; Example window.onrejectionhandled = function(e) { console.log(e.reason); } Specifications Specification Status Comment HTML Living StandardThe definition of 'onrejectionhandled' in that specification. Living Standard Initial definition. ...
WindowEventHandlers.onunload - Web APIs
The onunload property of the WindowEventHandlers mixin is the EventHandler for processing unload events. These events fire when the window is unloading its content and resources. The resource removal is processed after the unload event occurs. Note: Browsers equipped with pop-up blockers will ignore all Window.open() method calls in onunload event handler functions. Syntax window.addEventListener("unload", function(event) { ... }); window.onunload = function(event) { ... }; Typically, it is better to use window.addEventListener() and the unload event, instead of onunload. Specifications Specification Status Comment HTML Living StandardThe definition of 'onunload' in that specification. Living Standard HTML 5.1The definition of 'GlobalEventHandlers' in...
WindowOrWorkerGlobalScope.caches - Web APIs
returns the CacheStorage object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests. Syntax var myCacheStorage = self.caches; // or just caches Value A CacheStorage object. Example The following example shows how you'd use a cache in a service worker context to store assets offline. ...
Worker.prototype.postMessage() - Web APIs
d code: var myWorker = new ChromeWorker(self.path + 'myWorker.js'); function handleMessageFromWorker(msg) { console.log('incoming message from worker, msg:', msg); switch (msg.data.aTopic) { case 'do_sendMainArrBuff': sendMainArrBuff(msg.data.aBuf) break; default: throw 'no aTopic on incoming message to ChromeWorker'; } } myWorker.addEventListener('message', handleMessageFromWorker); // Ok lets create the buffer and send it var arrBuf = new ArrayBuffer(8); console.info('arrBuf.byteLength pre transfer:', arrBuf.byteLength); myWorker.postMessage( { aTopic: 'do_sendWorkerArrBuff', aBuf: arrBuf // The array buffer that we passed to the transferrable section 3 lines below }, [ arrBuf // The array buffer we ...
WorkerGlobalScope: languagechange event - Web APIs
The languagechange event is fired at the global scope object when the user's preferred language changes. Bubbles No Cancelable No Interface Event Event handler onlanguagechange Examples You can use the languagechange event in an addEventListener method: worker.addEventListener('languagechange', function() { console.log('languagechange event detected!'); }); Or use the onlanguagechange event handler property: worker.onlanguagechange = function(event) { console.log('languagechange event detected!'); }; Specification Specification Status HTML Living StandardThe definition of 'languagechange' in that specification. Living Standard ...
XMLDocument.load() - Web APIs
Web › API › XMLDocument › load
equest is synchronous or asynchronous (the default). As of at least Gecko 1.9, this no longer supports cross-site loading of documents (Use XMLHttpRequest or fetch() instead). Examples var xmlDoc = document.implementation.createDocument("", "test", null); function documentLoaded (e) { alert(new XMLSerializer().serializeToString(e.target)); // Gives querydata.xml contents as string } xmlDoc.addEventListener("load", documentLoaded, false); xmlDoc.load('querydata.xml'); See also the load sample in the XML tests directory. (To test this functionality, create the files on your local disk or on a webserver rather than loading the load.html file from the LXR-generated page, which will serve the text.xml file as HTML.) Specifications Old W3C Working Draft of the DOM Level 3 Load & Save module ...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
gerprint + "\n"); var validity = cert.validity.QueryInterface(Ci.nsIX509CertValidity); dump("\tValid from " + validity.notBeforeGMT + "\n"); dump("\tValid until " + validity.notAfterGMT + "\n"); } } catch(err) { alert(err); } } function test(url) { var req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(); req.open('GET', url, true); req.addEventListener("error", function(e) { var error = createTCPErrorFromFailedXHR(req); dumpSecurityInfo(req, error); }, false); req.onload = function(e) { dumpSecurityInfo(req); }; req.send(); } Then test("https://addons.mozilla.org"); produced the following output in my console: Connection status: succeeded Security Info: Security state: secure Common...
XMLHttpRequest.overrideMimeType() - Web APIs
. Note: If the server doesn't provide a Content-Type header, XMLHttpRequest assumes that the MIME type is "text/xml". If the content isn't valid XML, an "XML Parsing Error: not well-formed" error occurs. You can avoid this by calling overrideMimeType() to specify a different type. // Interpret the received data as plain text req = new XMLHttpRequest(); req.overrideMimeType("text/plain"); req.addEventListener("load", callback, false); req.open("get", url); req.send(); Specifications Specification Status Comment XMLHttpRequestThe definition of 'overrideMimeType()' in that specification. Living Standard WHATWG living standard ...
XMLHttpRequest: timeout event - Web APIs
due to preset time expiring. Bubbles No Cancelable No Interface ProgressEvent Event handler property ontimeout Examples const client = new XMLHttpRequest(); client.open('GET', 'http://www.example.org/example.txt'); client.ontimeout = () => { console.error('Timeout!!') }; client.send(); You could also set up the event handler using the addEventListener() method: client.addEventListener('timeout', () => { console.error("Timeout!!"); }); Specifications Specification Status Comment XMLHttpRequestThe definition of 'timeout event' in that specification. Living Standard ...
XMLHttpRequest - Web APIs
progress events instead. Event handlers onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers. Since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.). See Using XMLHttpRequest. More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener() APIs in addition to setting on* properties to a handler function. Methods XMLHttpRequest.abort() Aborts the request if it has already been sent. XMLHttpRequest.getAllResponseHeaders() Returns all the response headers, separated by CRLF, as a string, or null if no response has been received. XMLHttpRequest.getResponseHeader() Returns the string containing the text of the specified heade...
XRInputSourceEvent() - Web APIs
an ongoing primary squeeze action is disconnected. squeezestart Sent to an XRSession when an input source begins its primary squeeze action, indicating that the user has begun to grab, squeeze, or grip the controller. Examples The code below sets up handlers for primary action events in order to determine when the user clicks on (shoots at/pokes at/whatever) objects in the scene. xrSession.addEventListener("select", event => { let targetRayPose = event.frame.getPose(event.inputSource.targetRaySpace, myRefSpace); if (targetRayPose) { let hit = myHitTest(targetRayPose.transform); if (hit) { /* handle the hit */ } } }); Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSourceEvent' in that specification. Wor...
XRInputSourceEvent - Web APIs
an ongoing primary squeeze action is disconnected. squeezestart Sent to an XRSession when an input source begins its primary squeeze action, indicating that the user has begun to grab, squeeze, or grip the controller. Examples The code below sets up handlers for primary action events in order to determine when the user clicks on (shoots at/pokes at/whatever) objects in the scene. xrSession.addEventListener("select", event => { let targetRayPose = event.frame.getPose(event.inputSource.targetRaySpace, myRefSpace); if (targetRayPose) { let hit = myHitTest(targetRayPose.transform); if (hit) { /* handle the hit */ } } }); Specifications Specification Status Comment WebXR Device APIThe definition of 'XRInputSourceEvent' in that specification. Wor...
XRInputSourcesChangeEvent - Web APIs
from its parent interface, Event. Event types inputsourceschange Delivered to the XRSession when the set of input devices available to it changes. Examples The following example shows how to set up an event handler which uses inputsourceschange events to detect newly-available pointing devices and to load their models in preparation to display them in the next animation frame. ...
XRPose.transform - Web APIs
Web › API › XRPose › transform
then dispatches the event differently depending on the user's handedness; this is done by comparing the value of the XRInputSource property handedness to a value in the variable user.handedness. If the source is a controller in the user's primary hand, a function is called on the targeted object called primaryAction(); otherwise, it calls the targeted object's offHandAction() function. ...
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
gle. First, we add an event handler for mousemove events, which calls our code to perform the rotation if the right mouse button is down. Note also that we set oncontextmenu up to be ignored by calling preventDefault() on those events. This prevents the right-clicks from causing the context menu from appearing in the browser. canvas.oncontextmenu = (event) => { event.preventDefault(); }; canvas.addEventListener("mousemove", (event) => { if (event.buttons & 2) { rotateViewBy(event.movementX, event.movementY); } }); Next, the rotateViewBy() function, which updates the mouse look direction's yaw and pitch based on the mouse delta values from the mousemove event. The pitch is restricted so that you can't look beyond straight up and straight down. Each time this is called, the new offsets are used ...
XRReferenceSpace - Web APIs
objects. reset The reset event is sent to an XRReferenceSpace object when the browser detects a discontinuity has occurred wherein the tracked object's origin relative to the user's environment or location. This can happen, for example, after the user recalibrates their XR device, or if the device automatically adjusts its origin after losing and regaining tracking. In addition to using addEventListener(), you can establish a reset event handler by setting the onreset event handler property. Reference space types The reference space returned by XRSession.requestReferenceSpace() is either XRReferenceSpace or XRBoundedReferenceSpace. The "Interface" column in the table below indicates which of the two types is returned for each reference space type constant.. Reference space descriptors The...
XRReferenceSpaceEvent.transform - Web APIs
For details on what causes a reset event and how to respond, see the reset event's documentation. Examples This example handles the reset event by walking through all the objects in a scene, updating each object's position by multiplying it with the event's given transform. The scene is represented by a scene object, with all the objects in an array called objects within it. xrReferenceSpace.addEventListener("reset", event => { for (let obj of scene.objects) { mat4.multiply(obj.transform, obj.transform, event.transform); } }); Specifications Specification Status Comment WebXR Device APIThe definition of 'XRReferenceSpaceEvent.transform' in that specification. Working Draft Initial definition. ...
XRRigidTransform.position - Web APIs
rm. Syntax let pos = xrRigidTransform.position; Value A read-only DOMPointReadOnly indicating the 3D position component of the transform matrix. The units are meters. Note: The w component of the point is always 1.0. ...
XRSession.requestAnimationFrame() - Web APIs
function onXRAnimationFrame(time, xrFrame) { xrSession.requestAnimationFrame(onXRAnimationFrame) renderFrame(time, xrFrame) } function renderFrame(time, xrFrame) { // Shared rendering logic. } // Assumed to be called by a user gesture event elsewhere in code. function startXRSession() { navigator.xr.requestSession('immersive-vr').then((session) => { xrSession = session xrSession.addEventListener('end', onXRSessionEnded) // Do necessary session setup here. // Begin the session's animation loop. xrSession.requestAnimationFrame(onXRAnimationFrame) }) } function onXRSessionEnded() { xrSession = null } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSession.requestAnimationFrame' in that specification. Working ...
XRSessionEvent() - Web APIs
e Fired at the session whenever its visibility state changes. Examples This example creates a listiener that watches for the visibility state of the session to change. It reacts by calling a function mySessionVisible() with a Boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfigure a worker that handles rendering the scene. xrSession.addEventListener("visibilitystate", e => { switch(e.session.visibilitystate) { case "visible": case "visible-blurred": mySessionVisible(true); break; case "hidden": mySessionVisible(false); break; } }); Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSessionEvent() constructor' in that specification. Working...
XRSessionEvent.session - Web APIs
The read-only XRSessionEvent interface's session property indicates which XRSession the event is about. Syntax xrSession = xrSessionEvent.session; Value An XRSession object indicating which WebXR session the event refers to. Examples In this example, the session property is used to obtain the session object to manage when an event is received. xrSession.addEventListener("visibilitychange", e => { switch(e.session.visibilityState) { case "hidden": myEnableRendering(true); break; case "visible": case "visible-blurred": myEnableRendering(false); break; } }); This calls a function that reacts to the session's visibility state change. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSessionEvent.s...
XRSessionEvent - Web APIs
e Fired at the session whenever its visibility state changes. Examples This example creates a listiener that watches for the visibility state of the session to change. It reacts by calling a function mySessionVisible() with a Boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfigure a worker that handles rendering the scene. xrSession.addEventListener("visibilitystate", e => { switch(e.session.visibilitystate) { case "visible": case "visible-blurred": mySessionVisible(true); break; case "hidden": mySessionVisible(false); break; } }); Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSessionEvent' in that specification. Working Draft Init...
XRSystem: devicechange event - Web APIs
r for the availability of a WebXR-compatible device so that you can enable a UI element which the user can use to activate immersive mode. This is shown in the example below. Example The example shown here handles the devicechange event by toggling the availability of the "Enter XR" button based on whether or not any immersive devices are currently available. ...
XRSystem: isSessionSupported() - Web APIs
underway, we request the VR session and, if successful, set up the session in a method called onSessionStarted(), not shown. If a session is already underway when the button is clicked, we call the xrSession object's end() method to shut down the WebXR session. if (navigator.xr) { navigator.xr.isSessionSupported('immersive-vr') .then((isSupported) => { if (isSupported) { userButton.addEventListener('click', onButtonClicked); userButton.innerHTML = 'Enter XR'; userButton.disabled = false; } }); } function onButtonClicked() { if (!xrSession) { navigator.xr.requestSession('immersive-vr') .then((session) => { xrSession = session; // onSessionStarted() not shown for reasons of brevity and clarity. onSessionStarted(xrSession); }); } else { ...
XRSystem - Web APIs
Web › API › XRSystem
as changed. Also available using the ondevicechange event handler. Usage notes Thsi interface was previously known as simply XR in earlier versions of the specification; if you see references to XR in code or documentation, simply replace that with XRSystem. Examples The following example shows how to use both isSessionSupported() and requestSession(). ...
mssitemodejumplistitemremoved - Web APIs
incompatibilities between implementations and the behavior may change in the future. The mssitemodejumplistitemremoved event occurs when msSiteModeShowJumpList is called and an item has been removed from a Jump List by the user. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax Event Property object.oncandidatewindowhide = handler; addEventListener Method object.addEventListener("mssitemodejumplistitemremoved", handler, useCapture) General info Synchronous No Bubbles No Cancelable No Note This event is raised once for every item that has been removed since the last time msSiteModeShowJumpList was called. This event is not triggered if msSiteModeClearJumpList has been called. Parameters pEvtObj [in] Type: IHTMLEve...
ARIA live regions - Accessibility
Because the live region has aria-live="polite", the screen reader will wait until the user pauses...
ARIA: switch role - Accessibility
r" class="switch"> <span>off</span> <span>on</span> </button> <label for="speakerPower" class="switch">Speaker power</label> JavaScript This JavaScript code defines and applies a function to handle click events on switch widgets. The function changes the aria-checked attribute from true to false, or vice versa. document.querySelectorAll(".switch").forEach(function(theSwitch) { theSwitch.addEventListener("click", handleClickEvent, false); }); function handleClickEvent(evt) { let el = evt.target; if (el.getAttribute("aria-checked") == "true") { el.setAttribute("aria-checked", "false"); } else { el.setAttribute("aria-checked", "true"); } } CSS The purpose of the CSS is to establish a look and feel for the switch that's reminiscent of the power switch paradigm. button.switch...
Web applications and ARIA FAQ - Accessibility
{ // HTML5 <progress> is supported, so update the value attribute instead. progressBar.setAttribute("value", percentComplete); } progressBar.textContent = percentComplete + "% complete"; } function initDemo() { setupProgress(); // Setup the progress bar. // Bind a click handler to the button, which will update the progress bar to 75%. document.getElementById("update-button").addEventListener("click", function (e) { updateProgress(75); e.preventDefault(); }, false); } initDemo(); How do assistive technologies work? Assistive technologies use an API built into each operating system specifically designed to describe the roles, states, and structure of an application's user interface. For example, a screen reader uses this API to read the user interface with a text-to-speech...
-webkit-text-stroke-color - CSS: Cascading Style Sheets
Living Standard Initial standardization Safari CSS Reference '-webkit-text-stroke-color' in tha...
::before (:before) - CSS: Cascading Style Sheets
Web › CSS › ::before
Note that there are no icons used, and the check-mark is actually the ::before that has been styled in CSS. Go ahead and get some stuff done. Result Special characters As this is CSS; not HTML, you can not use markup entities in co...
:disabled - CSS: Cascading Style Sheets
Web › CSS › :disabled
shipping address:</label> <input type="checkbox" id="billing-checkbox" checked> <br> <input type="text" placeholder="Name" disabled> <input type="text" placeholder="Address" disabled> <input type="text" placeholder="Zip Code" disabled> </fieldset> </form> CSS input[type="text"]:disabled { background: #ccc; } JavaScript // Wait for the page to finish loading document.addEventListener('DOMContentLoaded', function () { // Attach `change` event listener to checkbox document.getElementById('billing-checkbox').onchange = toggleBilling; }, false); function toggleBilling() { // Select the billing text fields var billingItems = document.querySelectorAll('#billing input[type="text"]'); // Toggle the billing text fields for (var i = 0; i < billingItems.length; i++) { ...
:first - CSS: Cascading Style Sheets
Web › CSS › :first
widows, and page breaks of the document. Furthermore, you may only use absolute-length units when defining the margins. All other properties will be ignored. Syntax :first Examples HTML <p>First Page.</p> <p>Second Page.</p> <button>Print!</button> CSS @page :first { margin-left: 50%; margin-top: 50%; } p { page-break-after: always; } JavaScript document.querySelector("button").addEventListener('click', () => { window.print(); }); Result Press the "Print!" button to print the example. The words on the first page should be somewhere around the center, while other pages will have their contents at the default position. Specifications Specification Status Comment CSS Paged Media Module Level 3The definition of ':first' in that specification. Working ...
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
Web › CSS › :is
For example, the following CSS: /* 3-deep (or more) unordered lists use a square */ ol ol ul, ol ul ul, ol menu ul, ol dir ul, ol ol menu, ol ul menu, ol menu menu, ol dir menu, ol ...
Using CSS animations - CSS: Cascading Style Sheets
slidein { from { margin-left:100%; width:300% } to { margin-left:0%; width:100%; } } Adding the animation event listeners We'll use JavaScript code to listen for all three possible animation events. This code configures our event listeners; we call it when the document is first loaded in order to set things up. var element = document.getElementById("watchme"); element.addEventListener("animationstart", listener, false); element.addEventListener("animationend", listener, false); element.addEventListener("animationiteration", listener, false); element.className = "slidein"; This is pretty standard code; you can get details on how it works in the documentation for eventTarget.addEventListener(). The last thing this code does is set the class on the element we'll be animating t...
<blend-mode> - CSS: Cascading Style Sheets
Candidate Recommendation Initial definition. ...
border-image-repeat - CSS: Cascading Style Sheets
Candidate Recommendation Initial definition ...
border-image-slice - CSS: Cascading Style Sheets
ice: 30; border-image-repeat: round; } li { display: flex; place-content: center; } JavaScript const widthSlider = document.getElementById('width'); const sliceSlider = document.getElementById('slice'); const widthOutput = document.getElementById('width-output'); const sliceOutput = document.getElementById('slice-output'); const divElem = document.querySelector('div > div'); widthSlider.addEventListener('input', () => { const newValue = widthSlider.value + 'px'; divElem.style.borderWidth = newValue; widthOutput.textContent = newValue; }) sliceSlider.addEventListener('input', () => { const newValue = sliceSlider.value; divElem.style.borderImageSlice = newValue; sliceOutput.textContent = newValue; }) Result Specifications Specification Status Comment C...
clip-path - CSS: Cascading Style Sheets
Web › CSS › clip-path
Candidate Recommendation Extends its application to HTML elements. The clip-path property replaces the deprecated clip proper...
<color> - CSS: Cascading Style Sheets
...
display - CSS: Cascading Style Sheets
Web › CSS › display
Specifications Specification Status Comment CSS Display Module Level 3The definition of 'display' in that specification. Candidate Recommendation Added run-in, flow, flow-root, contents, and multi-keyword valu...
<easing-function> - CSS: Cascading Style Sheets
animation: 1.5s infinite alternate; } @keyframes move-right { from { left: 10%; } to { left: 90%; } } li { display: flex; align-items: center; justify-content: center; margin-bottom: 20px; } JavaScript const selectElem = document.querySelector('select'); const startBtn = document.querySelector('button'); const divElem = document.querySelector('div > div'); startBtn.addEventListener('click', () => { if(startBtn.textContent === 'Start animation') { divElem.style.animationName = 'move-right'; startBtn.textContent = 'Stop animation'; divElem.style.animationTimingFunction = selectElem.value; } else { divElem.style.animationName = 'unset'; startBtn.textContent = 'Start animation'; } }); selectElem.addEventListener('change', () => { divElem.style.anima...
<filter-function> - CSS: Cascading Style Sheets
: 20px; } input { width: 60% } output { width: 5%; text-align: center; } select { width: 40%; margin-left: 2px; } JavaScript const selectElem = document.querySelector('select'); const divElem = document.querySelector('div'); const slider = document.querySelector('input'); const output = document.querySelector('output'); const curValue = document.querySelector('p code'); selectElem.addEventListener('change', () => { setSlider(selectElem.value); setDiv(selectElem.value); }); slider.addEventListener('input', () => { setDiv(selectElem.value); }); function setSlider(filter) { if(filter === 'blur') { slider.value = 0; slider.min = 0; slider.max = 30; slider.step = 1; slider.setAttribute('data-unit', 'px'); } else if(filter === 'brightness' || filter === 'contrast'...
flex - CSS: Cascading Style Sheets
Web › CSS › flex
"block" : "none"; }); #flex-container { width: 100%; font-family: Consolas, Arial, sans-serif; } #flex-container > div { border: 1px solid #f00; padding: 1rem; } #flex-container > .raw-item { border: 1px solid #000; } Result Specifications Specification Status Comment CSS Fle...
font-kerning - CSS: Cascading Style Sheets
d disabling kerning HTML <div id="kern"></div> <div id="nokern"></div> <textarea id="input">AV T. ij</textarea> CSS div { font-size: 2rem; font-family: serif; } #nokern { font-kerning: none; } #kern { font-kerning: normal; } JavaScript let input = document.getElementById('input'); let kern = document.getElementById('kern'); let nokern = document.getElementById('nokern'); input.addEventListener('keyup', function() { kern.textContent = input.value; /* Update content */ nokern.textContent = input.value; }); kern.textContent = input.value; /* Initialize content */ nokern.textContent = input.value; Specifications Specification Status Comment CSS Fonts Module Level 3The definition of 'font-kerning' in that specification. Candidate Recommendation In...
font-style - CSS: Cascading Style Sheets
MDN Understanding WCAG, Guideline 1.4 explanations W3C Understanding WCAG 2.1 Formal definition Initial valuenormalApplies toall elements. It also applies to ::first-letter and ::first-line.Inherit...
font-weight - CSS: Cascading Style Sheets
MDN Understanding WCAG, Guideline 1.4 explanations Understanding Success Criterion 1.4.8 | W3C Understanding WCAG 2.0 Formal definiti...
image-orientation - CSS: Cascading Style Sheets
Candidate Recommendation Initial definition. ...
justify-content - CSS: Cascading Style Sheets
Working Draft Adds the [ first | last ]? baseline, self-start, self-end, start, end, left, right, u...
<length> - CSS: Cascading Style Sheets
Web › CSS › length
gin-left: 20px; } .results { margin-top: 10px; } .input-container { position: absolute; display: flex; justify-content: flex-start; align-items: center; height: 50px; } label { margin: 0 10px 0 20px; } JavaScript const inputDiv = document.querySelector('.inner'); const inputElem = document.querySelector('input'); const resultsDiv = document.querySelector('.results'); inputElem.addEventListener('change', () => { inputDiv.style.width = inputElem.value; const result = document.createElement('div'); result.className = 'result'; result.style.width = inputElem.value; result.innerHTML = `<code>width: ${inputElem.value}</code>`; resultsDiv.appendChild(result); inputElem.value = ''; inputElem.focus(); }) Result Specifications Specification Status Comment ...
mask-clip - CSS: Cascading Style Sheets
Web › CSS › mask-clip
Candidate Recommendation Initial definition ...
mask-composite - CSS: Cascading Style Sheets
Candidate Recommendation Initial definition ...
mask-mode - CSS: Cascading Style Sheets
Web › CSS › mask-mode
Candidate Recommendation Initial definition ...
mask-origin - CSS: Cascading Style Sheets
Candidate Recommendation Initial definition ...
mask-position - CSS: Cascading Style Sheets
Candidate Recommendation Initial definition ...
mask-repeat - CSS: Cascading Style Sheets
d"> </div> <select id="repetition"> <option value="repeat-x">repeat-x</option> <option value="repeat-y">repeat-y</option> <option value="repeat" selected>repeat</option> <option value="space">space</option> <option value="round">round</option> <option value="no-repeat">no-repeat</option> </select> JavaScript Content var repetition = document.getElementById("repetition"); repetition.addEventListener("change", function (evt) { document.getElementById("masked").style.maskRepeat = evt.target.value; }); Result Multiple mask image support You can specify a different <repeat-style> for each mask image, separated by commas: .examplethree { mask-image: url('mask1.png'), url('mask2.png'); mask-repeat: repeat-x, repeat-y; } Each image is matched with the corresponding repeat style, fro...
mask-size - CSS: Cascading Style Sheets
Web › CSS › mask-size
Candidate Recommendation Initial definition ...
place-items - CSS: Cascading Style Sheets
al</option> <option value="first baseline auto">first baseline auto</option> <option value="last baseline normal">last baseline normal</option> <option value="stretch auto">stretch auto</option> </select> </div> JavaScript var values = document.getElementById('values'); var display = document.getElementById('display'); var container = document.getElementById('container'); values.addEventListener('change', function (evt) { container.style.placeItems = evt.target.value; }); display.addEventListener('change', function (evt) { container.className = evt.target.value; }); CSS #container { height:200px; width: 240px; place-items: center; /* You can change this value by selecting another option in the list */ background-color: #8c8c8c; } .flex { display: flex; flex-wrap: wr...
<transform-function> - CSS: Cascading Style Sheets
rm: rotateY(-90deg) translateZ(50px); } .top { background: rgba(210,210,0,.7); transform: rotateX(90deg) translateZ(50px); } .bottom { background: rgba(210,0,210,.7); transform: rotateX(-90deg) translateZ(50px); } .select-form { margin-top: 50px; } JavaScript const selectElem = document.querySelector('select'); const example = document.querySelector('#example-element'); selectElem.addEventListener('change', () => { if(selectElem.value === 'Choose a function') { return; } else { example.style.transform = `rotate3d(1, 1, 1, 30deg) ${selectElem.value}`; setTimeout(function() { example.style.transform = 'rotate3d(1, 1, 1, 30deg)'; }, 2000) } }) Result Specifications Specification Status Comment CSS Transforms Level 2The definition of...
transform-style - CSS: Cascading Style Sheets
Editor's Draft Initial definition. ...
Used value - CSS: Cascading Style Sheets
Then, CSS 2.1 introduced the distinct definition of used value. An element could then explicitly inherit a width/height of a parent, whose computed value is a percentage. For CSS properties that don't depend on layout (e.g., display, font-si...
white-space - CSS: Cascading Style Sheets
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum...
Getting Started - Developer guides
ocument, test.html, which contains the text "I'm a test." Then we'll alert() the contents of the response. Note that this example uses vanilla JavaScript -- no jQuery is involved. Also, the HTML, XML and PHP files should be placed in the same directory. ...
Web Audio playbackRate explained - Developer guides
Note: Try out this example live, and try adjusting the playback rate control to see the effect. defaultPlaybackRate and ratechange In addition to playbackRate, we al...
Media events - Developer guides
lumechange Sent when the audio volume changes (both when the volume is set and when the muted attribute is changed). waiting Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). You can easily watch for these events, using code such as the following: var v = document.getElementsByTagName("video")[0]; v.addEventListener("seeked", function() { v.play(); }, true); v.currentTime = 10.0; This example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes. The listener simply calls the element's play() method, which starts playback. Then, in line 3, the example sets the element's currentTime attribute t...
Event developer guide - Developer guides
Web › Guide › Events
rything you need to know about events will go under here. Docs Creating and triggering eventsThis article demonstrates how to create and dispatch DOM events. Such events are commonly called synthetic events, as opposed to the events fired by the browser itself.DOM on-event handlersThe Web platform provides several ways to get notified of DOM events. Two common styles are: the generalized addEventListener() and a set of specific on-event handlers.Media eventsVarious events are sent when handling media that are embedded in HTML documents using the <audio> and <video> elements; this section lists them and provides some helpful information about using them.Mouse gesture eventsGecko 1.9.1 added support for several Mozilla-specific DOM events used to handle mouse gestures. These are special movements t...
Index - Developer guides
Web › Guide › Index
, NeedsContent, events This article demonstrates how to create and dispatch DOM events. Such events are commonly called synthetic events, as opposed to the events fired by the browser itself. 19 DOM onevent handlers Beginner, DOM, DOM Beginner, NeedsBeginnerUpdate, NeedsUpdate The Web platform provides several ways to be notified of DOM events. Two common approaches are addEventListener() and the specific onevent handlers. 20 Media events Intermediate, Media Various events are sent when handling media that are embedded in HTML documents using the <audio> and <video> elements; this section lists them and provides some helpful information about using them. 21 Mouse gesture events Advanced, DOM Gecko 1.9.1 added support for several Mozilla-...
Printing - Developer guides
Internet Explorer) send beforeprint and afterprint events to let content determine when printing may have occurred. You can use this to adjust the user interface presented during printing (such as by displaying or hiding user interface elements during the print process). Note: You can also use window.onbeforeprint and window.onafterprint to assign handlers for these events, but using EventTarget.addEventListener() is preferred. Examples Here are some common examples. Open and automatically close a popup window when finished If you want to be able to automatically close a popup window (for example, the printer-friendly version of a document) after the user prints its contents, you can use code like this: <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <input type="color"> element. let colorPicker = document.getElementById("colorPicker"); let box = document.getElementById("box"); let output = document.getElementById("output"); box.style.borderColor = colorPicker.value; colorPicker.addEventListener("input", function(event) { box.style.borderColor = event.target.value; }, false); colorPicker.addEventListener("change", function(event) { output.innerText = "Color set to " + colorPicker.value + "."; }, false); The input event is sent every time the value of the element changes; that is, every time the user adjusts the color in the color picker. Each time this event arrives, we set the box...
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
hen trying to download the image data. Starting the download The code that starts the download (say, when the user clicks a "Download" button), looks like this: function startDownload() { let imageURL = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2Fmdn_logo-only_color.svg?1535749917189"; downloadedImg = new Image; downloadedImg.crossOrigin = "Anonymous"; downloadedImg.addEventListener("load", imageReceived, false); downloadedImg.src = imageURL; } We're using a hard-coded URL here (imageURL), but that could easily come from anywhere. To begin downloading the image, we create a new HTMLImageElement object by using the Image() constructor. The image is then configured to allow cross-origin downloading by setting its crossOrigin attribute to "Anonymous" (that is, allow non-auth...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
t.onaddtrack = function(event) { trackEditor.addTrack(event.track); }; elem.audioTrackList.onremovetrack = function(event) { trackEditor.removeTrack(event.track); }; This code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor's list of available tracks. You can also use addEventListener() to listen for the addtrack and removetrack events. Examples Basic usage The following example shows simple usage of the <audio> element to play an OGG file. It will autoplay due to the autoplay attribute--if the page has permission to do so--and also includes fallback content. <!-- Simple audio playback --> <audio src="AudioTest.ogg" autoplay> Your browser does not support the <code>a...
<details>: The Details disclosure element - HTML: Hypertext Markup Language
Web › HTML › Element › details
orts the toggle event, which is dispatched to the <details> element whenever its state changes between open and closed. It is sent after the state is changed, although if the state changes multiple times before the browser can dispatch the event, the events are coalesced so that only one is sent. You can use an event listener for the toggle event to detect when the widget changes state: details.addEventListener("toggle", event => { if (details.open) { /* the element was toggled open */ } else { /* the element was toggled closed */ } }); Examples A simple disclosure example This example shows a <details> element with no provided summary. <details> <p>Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An i...
<input type="file"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › file
y is used to hide the file input instead of visibility: hidden or display: none, because assistive technology interprets the latter two styles to mean the file input isn't interactive. Next, we add an event listener to the input to listen for changes to its selected value changes (in this case, when files are selected). The event listener invokes our custom updateImageDisplay() function. input.addEventListener('change', updateImageDisplay); Whenever the updateImageDisplay() function is invoked, we: Use a while loop to empty the previous contents of the preview <div>. Grab the FileList object that contains the information on all the selected files, and store it in a variable called curFiles. Check to see if no files were selected, by checking if curFiles.length is equal to 0. If so, print a messag...
<input type="number"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › number
5px; } And finally, the JavaScript: let metersInputGroup = document.querySelector('.metersInputGroup'); let feetInputGroup = document.querySelector('.feetInputGroup'); let metersInput = document.querySelector('#meters'); let feetInput = document.querySelector('#feet'); let inchesInput = document.querySelector('#inches'); let switchBtn = document.querySelector('input[type="button"]'); switchBtn.addEventListener('click', function() { if(switchBtn.getAttribute('class') === 'meters') { switchBtn.setAttribute('class', 'feet'); switchBtn.value = 'Enter height in meters'; metersInputGroup.style.display = 'none'; feetInputGroup.style.display = 'block'; feetInput.setAttribute('required', ''); inchesInput.setAttribute('required', ''); metersInput.removeAttribute('required'); ...
<input type="radio"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › radio
Additional attributes In addition to the common attributes shared by ...
<input type="time"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › time
/a</span>"</code>. </p> </form> The JavaScript code adds code to the time input to watch for the input event, which is triggered every time the contents of an input element change. When this happens, the contents of the <span> are replaced with the new value of the input element. var startTime = document.getElementById("startTime"); var valueSpan = document.getElementById("value"); startTime.addEventListener("input", function() { valueSpan.innerText = startTime.value; }, false); When a form including a time input is submitted, the value is encoded before being included in the form's data. The form's data entry for a time input will always be in the form name=hh%3Amm, or name=hh%3Amm%3ass if seconds are included (see Using the step attribute). Additional attributes In addition to the attributes...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
ic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern. If you wanted to instead display custom error messages, you could use JavaScript like the following: const nameInput = document.querySelector('input'); const form = document.querySelector('form'); nameInput.addEventListener('input', () => { nameInput.setCustomValidity(''); nameInput.checkValidity(); }); nameInput.addEventListener('invalid', () => { if(nameInput.value === '') { nameInput.setCustomValidity('Enter your username!'); } else { nameInput.setCustomValidity('Usernames can only contain upper and lowercase letters. Try again!'); } }); The example renders like so: In brief: We check th...
<p>: The Paragraph element - HTML: Hypertext Markup Language
Web › HTML › Element › p
</i>. ...
<template>: The Content Template element - HTML: Hypertext Markup Language
Web › HTML › Element › template
s within it. Consider the following HTML and JavaScript: HTML <div id="container"></div> <template id="template"> <div>Click me</div> </template> JavaScript const container = document.getElementById("container"); const template = document.getElementById("template"); function clickHandler(event) { alert("Clicked a div"); } const firstClone = template.content.cloneNode(true); firstClone.addEventListener("click", clickHandler); container.appendChild(firstClone); const secondClone = template.content.firstElementChild.cloneNode(true); secondClone.addEventListener("click", clickHandler); container.appendChild(secondClone); Result firstClone is a DocumentFragment instance, so while it gets appended inside the container as expected, clicking on it does not trigger the click event. secondClone is an...
<track>: The Embed Text Track element - HTML: Hypertext Markup Language
Web › HTML › Element › track
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. ...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
t.onaddtrack = function(event) { trackEditor.addTrack(event.track); }; elem.audioTrackList.onremovetrack = function(event) { trackEditor.removeTrack(event.track); }; This code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor's list of available tracks. You can also use addEventListener() to listen for the addtrack and removetrack events. Examples Simple video example This example plays a video when activated, providing the user with the browser's default video controls to control playback. <!-- Simple video example --> <!-- 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org --> <!-- Poster from peach.blender.org --> <video controls s...
Using the application cache - HTML: Hypertext Markup Language
dates to the cache manifest You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test window.applicationCache.status. function onUpdateReady() { console.log('found new version!'); } window.applicationCache.addEventListener('updateready', onUpdateReady); if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { onUpdateReady(); } To manually start testing for a new manifest file, you can use window.applicationCache.update(). Gotchas Never access cached files by using traditional GET parameters (like other-cached-page.html?parameterName=value). This will make the browser bypass the cache and...
CSP: script-src - HTTP
included in the violation report. Examples Violation case Given this CSP header: Content-Security-Policy: script-src https://example.com/ the following script is blocked and won't be loaded or executed: <script src="https://not-example.com/js/library.js"></script> Note that inline event handlers are blocked as well: <button id="btn" onclick="doSomething()"> You should replace them with addEventListener calls: document.getElementById("btn").addEventListener('click', doSomething); Unsafe inline script Note: Disallowing inline styles and inline scripts is one of the biggest security wins CSP provides. However, if you absolutely have to use it, there are a few mechanisms that will allow them. To allow inline scripts and inline event handlers, 'unsafe-inline', a nonce-source or a hash-source t...
Loops and iteration - JavaScript
A do...while statement looks as follows: do statement while (condition); statement is always executed once before the condition is checked. (To execute multiple stateme...
JavaScript modules - JavaScript
to our index.html and main.js files -- the module exports remain the same as before. ...
Using Promises - JavaScript
One case of special usefulness: when writing code for Node.js, it's common that modules you include in your project may have unhandled rejected promises. These get logged to the console by the Node runtime. You can capture these for analysis and handling by your code--or just to avoid having them cluttering up your output--by adding a handler for the unhandledrejection event, like this: window.addEventListener("unhandledrejection", event => { /* You might start here by adding code to examine the promise specified by event.promise and the reason in event.reason */ event.preventDefault(); }, false); By calling the event's preventDefault() method, you tell the JavaScript runtime not to do its default action when rejected promises go unhandled. That default action usually involves logging ...
Memory Management - JavaScript
var d = new Date(); // allocates a Date object var e = document.createElement('div'); // allocates a DOM element Some methods allocate new values or objects: var s = 'azerty'; var s2 = s.substr(0, 3); // s2 is a new string // Since st...
Error.prototype.lineNumber - JavaScript
The lineNumber property contains the line number in the file that raised this error. Examples Using lineNumber var e = new Error('Could not parse input'); throw e; console.log(e.lineNumber) // 2 Alternative example using error event window.addEventListener('error', function(e) { console.log(e.lineNumber); // 5 }); var e = new Error('Could not parse input'); throw e; This is not a standard feature and lacks widespread support. See the browser compatability table below. Specifications Not part of any standard. ...
Promise - JavaScript
(You need a browser that supports Promise. ) By clicking the button several times in a short amount of time, you'll even see the different promises being fulfi...
eval() - JavaScript
snippets of code JavaScript has first-class functions, which means you can pass functions as arguments to other APIs, store them in variables and objects' properties, and so on. Many DOM APIs are designed with this in mind, so you can (and should) write: // instead of setTimeout(" ... ", 1000) use: setTimeout(function() { ... }, 1000); // instead of elt.setAttribute("onclick", "...") use: elt.addEventListener('click', function() { ... } , false); Closures are also helpful as a way to create parameterized functions without concatenating strings. Parsing JSON (converting strings to JavaScript objects) If the string you're calling eval() on contains data (for example, an array: "[1, 2, 3]"), as opposed to code, you should consider switching to JSON, which allows the string to use a subset of JavaScri...
Function expression - JavaScript
true console.log(typeof baz); // undefined console.log(bar === baz); // false (errors because baz == undefined) Examples Creating an unnamed function The following example defines an unnamed function and assigns it to x. The function returns the square of its argument: var x = function(y) { return y * y; }; Using a function as a callback More commonly it is used as a callback: button.addEventListener('click', function(event) { console.log('button is clicked!') }) Using an immediately executed function expression An anonymous function is created and called: (function() { console.log('Code runs!') })(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Function definitions' in that specification. ...
import - JavaScript
ul(data); }); Dynamic Import This example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. This is not the only way to implement this functionality. The import() function also supports await. const main = document.querySelector("main"); for (const link of document.querySelectorAll("nav > a")) { link.addEventListener("click", e => { e.preventDefault(); import('/modules/my-module.js') .then(module => { module.loadPageInto(main); }) .catch(err => { main.textContent = err.message; }); }); } Specifications Specification ECMAScript (ECMA-262)The definition of 'Imports' in that specification. ECMAScript (ECMA-262)The definition of '...
Codecs used by WebRTC - Web media technologies
ability objects, each describing one codec configuration. Also present in the list will be entries for retransmission (RTX), redundant coding (RED), and forward error correction (FEC). If the connection is in the process of starting up, you can use the icegatheringstatechange event to watch for the completion of ICE candidate gathering, then fetch the list. ...
pointer-events - SVG: Scalable Vector Graphics
rcle cx="5" cy="5" r="4" fill="white" pointer-events="visiblePoint" /> <!-- The circle below will never catch a mouse event. ...
restart - SVG: Scalable Vector Graphics
Web › SVG › Attribute › restart
whenNotActive This value indicates that the animation can only be res...
visibility - SVG: Scalable Vector Graphics
Recommendation CSS definition of the property ...
SVG documentation index - SVG: Scalable Vector Graphics
Web › SVG › Index
ont The <vkern> SVG element allows to fine-tweak the vertical distance between two glyphs in top-to-bottom fonts. This process is known as kerning. 379 Scripting Graphics, SVG, Scripting, default, eventListeners, preventing, setProperty 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. 380 Server Configuration SVG See http://wiki.svg.org/Server_Configuration 381 Sizing SVG This page was auto-generated because a user created a sub-page to this page. ...
Types of attacks - Web security
POST endpoints should not interchangeably accept GET requests with paramete...
Using custom elements - Web Components
rs such as HTMLElement and others, and return a different instance from the one just created. If you need a constructor and a mandatory super call, remember to pass along optional arguments and return the result of such a super call operation. class CustomElement extends HTMLElement { constructor(...args) { const self = super(...args); // self functionality written in here // self.addEventListener(...) // return the right context return self; } } If you don't need to perform any operation in the constructor, you can simply omit it so that its native behavior (see following) will be preserved. constructor(...args) { return super(...args); } Transpilers vs. classes Please note that ES2015 classes cannot reliably be transpiled in Babel 6 or TypeScript targeting legacy browsers...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
ted in the processing. Rather than modifying the DOM it is recommended to use stylesheet parameters which are usually easier and can give better performance. var testTransform = document.implementation.createDocument("", "test", null); // just an example to get a transform into a script as a DOM // XMLDocument.load is asynchronous, so all processing happens in the // onload handler testTransform.addEventListener("load", onload, false); testTransform.load("test-transform.xml"); function onload() { processor.importStylesheet(testTransform); } XSLTProcessor.importStylesheet() requires one argument, a DOM Node. If that node is a document node, you can pass in a full XSL Transform or a literal result element transform, otherwise it must be an xsl:stylesheet or xsl:transform element. Transforming the docu...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
d to run our new myFunction() function from JavaScript. First of all, open up your hello3.html file in a text editor. Add a <button> element as shown below, just above the first opening <script type='text/javascript'> tag. <button class="mybutton">Run myFunction</button> Now add the following code at the end of the first <script> element: document.querySelector('.mybutton') .addEventListener('click', function() { alert('check console'); var result = Module.ccall( 'myFunction', // name of C function null, // return type null, // argument types null // arguments ); }); This illustrates how ccall() is used to call the exported function. ...