Search completed in 1.30 seconds.
Document.getElementById() - Web APIs
The ID is case-sensitive string which is unique within the document; only one element may have any given ID. Return value An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document. ...
...entById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly. If you need to get access to an element which doesn't have an ID, you can use querySelector() to find the element using any selector. ...
...x var element = document.
getElementById(id); Parameters id The ID of the element to locate. The ID is case-sensitive string which is unique within the document; only one element may have any given ID. Return value An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document. ...
...And 9 more matches
Applying styles and colors - Web APIs
too spectacular happening here. We use the two variables i and j to generate a unique RGB color for each square, and only modify the red and green values. The blue channel has a fixed value. By modifying the channels, you can generate all kinds of palettes. By increasing the steps, you can achieve something that looks like the color palettes Photoshop uses. ...
..., i * 25, 25, 25); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); The result looks like this: ScreenshotLive sample A strokeStyle example This example is similar to the one above, but uses the strokeStyle property to change the colors of the shapes' outlines. We use the arc() method to draw circles instead of squares. ...
...s a set of circles with an increasing radius. The final result is a radial gradient. By overlaying ever more circles on top of each other, we effectively reduce the transparency of the circles that have already been drawn. By increasing the step count and in effect drawing more circles, the background would completely disappear from the center of the image. ...
...And 15 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
r is to abstract out functionality. Rather than multiple if() else() blocks, you increase efficiency by taking common tasks and abstracting them out into their own functions. Not only does this make the code easier to read, it simplifies adding support for new clients: var elm = getElmById("myID"); function getElmById(aID){ var element = null; if (isMozilla || isIE5) element = document.
getElementById(aID); else if (isNetscape4) element = document.layers[aID]; else if (isIE4) element = document.all[aID]; return element; } The above code still has the issue of browser sniffing, or detecting which browser the user is using. Browser sniffing is usually done through the useragent, such as: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.5) Gecko/20031016 While using the useragent ...
...mation on the browser in use, code that handles useragents often can make mistakes when new browser versions arrive, thus requiring code changes. It is much better and more reliable to sniff by browser capability or object feature support. You can usually do this by testing the required functionality in JavaScript. For example, rather than: if (isMozilla || isIE5) You would use: if (document.
getElementById) This would allow other browsers that support that W3C standard method, such as Opera or Safari, to work without any changes. Useragent sniffing makes sense in very limited cases where you really do want to know the exact browser in use, such as when you need to work around a bug in a specific version of a specific browser. For all other purposes you should check for the feature you need rat...
...specific browser. For all other purposes you should check for the feature you need rather than the browsers you think will support that feature. JavaScript also allows inline conditional statements, which can help with code readability: var foo = (condition) ? conditionIsTrue : conditionIsFalse; For example, to retrieve an element, you would use: function getElement(aID){ return (document.
getElementById) ? document.
getElementById(aID) : document.all[aID]); } Differences between Mozilla and Internet Explorer First, I'll discuss the differences in the way HTML behaves between Mozilla and Internet Explorer. Tooltips Legacy browsers introduced tooltips into HTML by showing them on links and using the value of the alt attribute as a tooltip's content. The lates...
...And 10 more matches
Examples of web and XML development using the DOM - Web APIs
mples use common APIs, tricks, and patterns in JavaScript for manipulating the document object. ...
...cript for manipulating the document object. ...
... 1: height and width The following example shows the use of the height and width properties alongside images of varying dimensions: <!DOCTYPE html> <html lang="en"> <head> <title>width/height example</title> <script> function init() { var arrImages = new Array(3); arrImages[0] = document.
getElementById("image1"); arrImages[1] = document.
getElementById("image2"); arrImages[2] = document.
getElementById("image3"); var objOutput = document.
getElementById("output"); var strHtml = "<ul>"; for (var i = 0; i < arrImages.length; i++) { strHtml += "<li>image" + (i+1) + ": height=" + arrImages[i].height + ", width=" + arrImages[i].width + ", style.height=" + arrImages[i].style.height + ", style.width=" + arrImages[i].style.width + "...
...And 10 more matches
Using files from web applications - Web APIs
s. Accessing selected file(s) Consider this HTML: <input type="file" id="input" multiple> The File API makes it possible to access a FileList containing File objects representing the files selected by the user. The multiple attribute on the input element allows the user to select multiple files. ...
...e 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. 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 th...
... let sOutput = nBytes + " bytes"; // optional code for multiples approximation const aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]; for (nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) { sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)"; } // end of optional code document.
getElementById("fileNum").innerHTML = nFiles; document.
getElementById("fileSize").innerHTML = sOutput; } document.
getElementById("uploadInput").addEventListener("change", updateSize, false); </script> </body> </html> Using hidden file input elements using the click() method You can hide the admittedly ugly file <input> element and present your own interface for opening the file picker and displayi...
...And 8 more matches
Using images - Web APIs
rces are collectively referred to by the type CanvasImageSource. There are several ways to get images for use on a canvas. Using images from the same page We can obtain a reference to images on the same page as the canvas by using one of: The document.images collection The document.getElementsByTagName() method If you know the ID of the specific image you wish to use, you can use document.
getElementById() to retrieve that specific image Using images from other domains Using the crossorigin attribute of an <img> element (reflected by the HTMLImageElement.crossOrigin property), you can request permission to load an image from another domain for use in your call to drawImage(). If the hosting domain permits cross-domain access to the image, the image can be used in your canvas without tainting i...
...ion to load an image from another domain for use in your call to drawImage(). If the hosting domain permits cross-domain access to the image, the image can be used in your canvas without tainting it; otherwise using the image will taint the canvas. Using other canvas elements Just as with normal images, we access other canvas elements using either the document.getElementsByTagName() or document.
getElementById() method. Be sure you've drawn something to the source canvas before using it in your target canvas. One of the more practical uses of this would be to use a second canvas element as a thumbnail view of the other larger canvas. Creating an image from scratch Another option is to create new HTMLImageElement objects in our script. To do this, you can use the convenient Image() constructor: var ...
...Some disadvantages of this method are that your image is not cached, and for larger images the encoded url can become quite long. Using frames from a video You can also use frames from a video being presented by a <video> element (even if the video is not visible). For example, if you have a <video> element with the ID "myvideo", you can do this: function getMyVideo() { var canvas = document.
getElementById('canvas'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); return document.
getElementById('myvideo'); } } This returns the HTMLVideoElement object for the video, which, as covered earlier, is one of the objects that can be used as a CanvasImageSource. Drawing images Once we have a reference to our source image object we can use the drawImage() method to render it to t...
...And 7 more matches
Closures - JavaScript
er(size) { return function() { document.body.style.fontSize = size + 'px'; }; } var size12 = makeSizer(12); var size14 = makeSizer(14); var size16 = makeSizer(16); size12, size14, and size16 are now functions that resize the body text to 12, 14, and 16 pixels, respectively. You can attach them to buttons (in this case hyperlinks) as demonstrated in the following code example. document.
getElementById('size-12').onclick = size12; document.
getElementById('size-14').onclick = size14; document.
getElementById('size-16').onclick = size16; <a href="#" id="size-12">12</a> <a href="#" id="size-14">14</a> <a href="#" id="size-16">16</a> Run the code using JSFiddle. Emulating private methods with closures Languages such as Java allow you to declare methods as private, meaning that they can be call...
...CMAScript 2015, a common problem with closures occurred when you created them inside a loop. To demonstrate, consider the following example code. ...
... The helpText array defines three helpful hints, each associated with the ID of an input field in the document. ...
...And 7 more matches
Drawing shapes with canvas - Web APIs
(relative to the origin) of the top-left corner of the rectangle. width and height provide the rectangle's size. Below is the draw() function from the previous page, but now it is making use of these three functions. Rectangular shape example <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var canvas = document.
getElementById('canvas'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.fillRect(25, 25, 100, 100); ctx.clearRect(45, 45, 60, 60); ctx.strokeRect(50, 50, 50, 50); } } This example's output is shown below. ScreenshotLive sample The fillRect() function draws a large black square 100 pixels on each side. The clearRect() function then erases a 60x60 pixel square from the ce...
...When you call fill(), any open shapes are closed automatically, so you don't have to call closePath(). This is not the case when you call stroke(). ...
... the starting point somewhere else. We could also use moveTo() to draw unconnected paths. Take a look at the smiley face below. To try this for yourself, you can use the code snippet below. Just paste it into the draw() function we saw earlier. ...
...And 6 more matches
Displaying Places information using views
the tree's place attribute: var histServ = Cc["@mozilla.org/browser/nav-history-service;1"]. getService(Ci.nsINavHistoryService); var query = histServ.getNewQuery(); query.searchTerms = "mozilla"; query.onlyBookmarked = true; var opts = histServ.getNewQueryOptions(); opts.queryType = opts.QUERY_TYPE_BOOKMARKS; var uri = histServ.queriesToQueryString([query], 1, opts); var tree = document.
getElementById("mytree"); tree.place = uri; These two examples use the built-in tree view, but the point is to demonstrate the use of the place attribute and property. In this regard the built-in menu and toolbar views are no different. When a view's underlying data changes, the view will automatically update itself so that it displays the new data. This update is handled by logic between the view and its res...
...thods and properties implemented directly on the view are very specific, while the interface provided by nsITreeView is very general. Tasks sometimes require you to use more than one of these points of interaction, going from one layer of generality to another. To put it in terms of JavaScript, say you have a variable named treeView that references your Places tree view: var treeView = document.
getElementById("myPlacesTreeView"); Points 1 and 2 apply to this variable. The tree view's view is the object at treeView.view. Points 3 and 4 apply to this object. var treeViewView = treeView.view; Convenience methods Because the built-in tree view is both widely used and complex, several convenience methods are implemented directly on it to make common tasks easier. Warning: Until bug 476952 is fixed...
... nsINavHistoryResultNode argument named aContainer. You can QueryInterface aContainer to an nsINavHistoryContainerResultNode. showRoot boolean If true the root nsINavHistoryContainerResultNode is shown as the first row in the tree. At least one of showRoot and flatList must be false. ...
...And 5 more matches
Capabilities, constraints, and settings - Web APIs
ack have constrainable properties. Determining if a constraint is supported If you need to know whether or not a given constriant is supported by the user agent, you can find out by calling navigator.mediaDevices.getSupportedConstraints() to get a list of the constrainable properties which the browser knows, like this: let supported = navigator.mediaDevices.getSupportedConstraints(); document.
getElementById("frameRateSlider").disabled = !supported["frameRate"]; In this example, the supported constraints are fetched, and a control that lets the user configure the frame rate is disabled if the frameRate constraint isn't supported. How constraints are defined A single constraint is an object whose name matches the constrainable property whose desired value or range of values is being specified. This...
... variables which will hold the MediaTrackConstraints objects for the video and audio tracks, as well as the variables which will hold references to the video and audio tracks themselves, to null. let videoConstraints = null; let audioConstraints = null; let audioTrack = null; let videoTrack = null; And we get references to all of the elements we'll need to access. ...
...s objects for the video and audio tracks, as well as the variables which will hold references to the video and audio tracks themselves, to null. let videoConstraints = null; let audioConstraints = null; let audioTrack = null; let videoTrack = null; And we get references to all of the elements we'll need to access. ...
...And 5 more matches
Cubic Bezier Generator - CSS: Cascading Style Sheets
ge="updateCanvas();return true;" type="text" maxlength=6 id="x2" value="0.14" class='field'> <label for="y2">y2 = </label><input onchange="updateCanvas();return true;" type="text" maxlength=6 id="y2" value="0.53" class='field'> <br> <output id="output">Log</output> </form> </html> .field { width: 40px; } function updateCanvas() { var x1 = document.
getElementById('x1').value; var y1 = document.
getElementById('y1').value; var x2 = document.
getElementById('x2').value; var y2 = document.
getElementById('y2').value; drawBezierCurve(x1, y1, x2, y2); } const radius = 4; // Place needed to draw the rulers const rulers = 30.5; const margin = 10.5; const basic_scale_size = 5; // Size of 0.1 tick on the rulers var scaling; //LIMITATION: scaling is ...
...lers const rulers = 30.5; const margin = 10.5; const basic_scale_size = 5; // Size of 0.1 tick on the rulers var scaling; //LIMITATION: scaling is computed once: if canvas.height/canvas.width change it won't be recalculated var dragSM = 0; // Drag state machine: 0 = nodrag, others = object being dragged function initCanvas() { // get the canvas element using the DOM var canvas = document.
getElementById('bezier'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); scaling = Math.min(canvas.height - rulers - margin, canvas.width - rulers - margin); canvas.onmousedown = mouseDown; canvas.onmouseup = mouseUp; } else { alert...
...{ return (1 - y) * scaling + margin; } function reverseY(y) { return (margin - y) / scaling + 1; } function lY(y) { // Used when drawing horizontal lines to prevent subpixel blur var result = cY(y); return Math.round(result) == result ? ...
...And 5 more matches
Sidebar - Archive of obsolete content
xul script The sidebar content is always in a document separate from the main browser document (the sidebar is actually implemented as a XUL browser element). This means you can't directly access the sidebar content from a script referenced from a browser.xul overlay. ...
...r element). This means you can't directly access the sidebar content from a script referenced from a browser.xul overlay. To access your sidebar's window or document objects, you need to use the contentWindow or contentDocument properties of document.
getElementById("sidebar") respectively. ...
....yourNotificationFunction(anyArguments); } Testing which sidebar is open The sidebar content may contain different panels (bookmarks, history, webpanel, etc.) and sometimes one wants to only act on the sidebar when it contains a specific panel. ...
...And 4 more matches
Using the W3C DOM - Archive of obsolete content
llection) Scripts that use these properties will throw errors in most standards-compliant browsers. Instead, use the W3C DOM properties and methods (examples in the next section). These are supported by Internet Explorer too so there is no need to use MSIE-specific attributes and methods. ...
...erencing elements in an HTML page is document.
getElementById(). All modern browsers support it. The method returns a reference to the uniquely identified element, which can then be used to script the element. For example, the following short sample dynamically sets the left margin of a <div> element with an id of "inset" to half an inch: // in the HTML: <div id="inset">Sample Text</div> document.
getElementById("inset").style.marginLeft = ".5in"; Note: Internet Explorer 5 through 7 have a flawed implementation of
getElementById(), which returns the first element with a matching NAME or ID (Id versus name when using
getElementById, MSDN:
getElementById Method). ...
...document.
getElementById("inset").style.marginLeft = ".5in"; Note: Internet Explorer 5 through 7 have a flawed implementation of
getElementById(), which returns the first element with a matching NAME or ID (Id versus name when using
getElementById, MSDN:
getElementById Method). ...
...And 4 more matches
Basic animations - Web APIs
olar system. ...
... ctx.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit ctx.stroke(); ctx.drawImage(sun, 0, 0, 300, 300); window.requestAnimationFrame(draw); } init(); <canvas id="canvas" width="300" height="300"></canvas> ScreenshotLive sample An animated clock This example draws an animated clock, showing your current time. ...
.../ image larger than canvas x = CanvasXSize - imgW; } if (imgW > CanvasXSize) { // image width larger than canvas clearX = imgW; } else { clearX = CanvasXSize; } if (imgH > CanvasYSize) { // image height larger than canvas clearY = imgH; } else { clearY = CanvasYSize; } // get canvas context ctx = document.
getElementById('canvas').getContext('2d'); // set refresh rate return setInterval(draw, speed); } function draw() { ctx.clearRect(0, 0, clearX, clearY); // clear the canvas // if image is <= Canvas Size if (imgW <= CanvasXSize) { // reset, start from beginning if (x > CanvasXSize) { x = -imgW + x; } // draw additional image1 if (x > 0) {...
...And 4 more matches
EventTarget.addEventListener() - Web APIs
about EventListenerOptions from the Web Incubator Community Group. Examples Add a simple listener This example demonstrates how to use addEventListener() to watch for mouse clicks on an element. HTML <table id="outside"> <tr><td id="t1">one</td></tr> <tr><td id="t2">two</td></tr> </table> JavaScript // Function to change the content of t2 function modifyText() { const t2 = document.
getElementById("t2"); if (t2.firstChild.nodeValue == "three") { t2.firstChild.nodeValue = "two"; } else { t2.firstChild.nodeValue = "three"; } } // Add event listener to table const el = document.
getElementById("outside"); el.addEventListener("click", modifyText, false); In this code, modifyText() is a listener for click events registered using addEventListener(). A click anywhere in the table ...
...o the handler and runs modifyText(). Result Event listener with anonymous function Here, we'll take a look at how to use an anonymous function to pass parameters into the event listener. ...
...an anonymous function to pass parameters into the event listener. HTML <table id="outside"> <tr><td id="t1">one</td></tr> <tr><td id="t2">two</td></tr> </table> JavaScript // Function to change the content of t2 function modifyText(new_text) { const t2 = document.
getElementById("t2"); t2.firstChild.nodeValue = new_text; } // Function to add event listener to table const el = document.
getElementById("outside"); el.addEventListener("click", function(){modifyText("four")}, false); Notice that the listener is an anonymous function that encapsulates code that is then, in turn, able to send parameters to the modifyText() function, which is responsible for actually responding to the event. Result Event listener with an arrow function This example demonstrates a simple event listener impleme...
...And 4 more matches
Signaling and video calling - Web APIs
have one open!"); } else { var clickedUsername = evt.target.textContent; if (clickedUsername === myUsername) { alert("I'm afraid I can't let you talk to yourself. That would be weird."); return; } targetUsername = clickedUsername; createPeerConnection(); navigator.mediaDevices.getUserMedia(mediaConstraints) .then(function(localStream) { document.
getElementById("local_video").srcObject = localStream; localStream.getTracks().forEach(track => myPeerConnection.addTrack(track, localStream)); }) .catch(handleGetUserMediaError); } } This begins with a basic sanity check: is the user already connected? If there's already a RTCPeerConnection, they obviously can't make a call. Then the name of the user that was clicked upon is obtained from the ...
...ing and sending its answer. ...
...mat--a track event is set to the RTCPeerConnection for each track added to the connection. Making use of newly added media requires implementing a handler for the track event. A common need is to attach the incoming media to an appropriate HTML element. In our example, we add the track's stream to the <video> element that displays the incoming video: function handleTrackEvent(event) { document.
getElementById("received_video").srcObject = event.streams[0]; document.
getElementById("hangup-button").disabled = false; } The incoming stream is attached to the "received_video" <video> element, and the "Hang Up" <button> element is enabled so the user can hang up the call. Once this code has completed, finally the video being sent by the other peer is displayed in the local browser window! Handling the ...
...And 4 more matches
Interacting with page scripts - Archive of obsolete content
pported API, so it could be removed or changed in a 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 pag...
...t; The "page.html" file adds two buttons and assigns an event listener to each: one listener displays a property of the cloned object, and the other listener displays a property of the assigned object: <html> <head> </head> <body> <input id="works" type="button" value="I will work"/> <input id="fails" type="button" value="I will not work"/> <script> var works = document.
getElementById("works"); works.addEventListener("click", function() { alert(clonedContentScriptObject.greeting); }, false); var fails = document.
getElementById("fails"); fails.addEventListener("click", function() { alert(assignedContentScriptObject.greeting); }, false); </script> </body> </html> If you run the example, clicking "I will work" displays the va...
...Since structured cloning doesn't work for functions, this means that you can't export functions that take functions as argu...
...And 3 more matches
Document Object Model - Archive of obsolete content
tively. Obviously, it is this latter type of document used for XUL. The three document types are very similar, in fact they all share the same base implementation. However, there are a few functions that are specific to one document type or the other. Retrieving Elements The most common method to retrieve an element in a document is to give the element an id attribute and the use the document's
getElementById() method. We've added the id attribute to a number of elements in the find file dialog. For example, we could get the state of a check box by using the code below: var state = document.
getElementById('casecheck').checked; The value casecheck corresponds to the id of the case sensitive checkbox. Once we have an indication of whether it is checked or not, we can use the state to perform the sear...
...alled findfile.js in the same directory as findfile.xul. We'll add the doFind() function is this file. The script tag does allow code to be contained directly inside of it. However, for various reasons, including better performance, you should always put scripts in separate files, except for short fragments which can be put directly in the event handler. function doFind(){ var meter = document.
getElementById('progmeter'); meter.hidden = false; } This function first gets a reference to the progress meter using its id, progmeter. The second line of the function body changes the hidden state so that the element is visible again. Finally, let's have an alert box pop up that displays what will be searched for. Of course, we wouldn't want this in the final version but we'll add it to reassure us that ...
...ts a reference to the progress meter using its id, progmeter. The second line of the function body changes the hidden state so that the element is visible again. Finally, let's have an alert box pop up that displays what will be searched for. Of course, we wouldn't want this in the final version but we'll add it to reassure us that something would happen. function doFind(){ var meter=document.
getElementById('progmeter'); meter.hidden = false; var searchtext=document.
getElementById('find-text').value; alert("Searching for \"" + searchtext + "\""); } Now, with that alert box in there, we know what should happen when we click the Find button. We could add additional code to get the selections from the drop-down boxes too. XUL Element DOM Every XUL element has a set of attributes, a set of pr...
...And 3 more matches
Manipulating Lists - Archive of obsolete content
d instead when possible. These functions are bit simpler and will do the right thing. The appendItem() function is used to append a new item to the end a list. Similar to the DOM appendChild() function except that it takes a string label, and you do not have to worry about where to add it in the list structure. Here is an example: Example 1 : Source View <script> function addItem(){ document.
getElementById('thelist').appendItem("Thursday", "thu"); } </script> <listbox id="thelist"/> <button label="Add" oncommand="addItem();"/> The appendItem() takes two arguments, the label, in this case 'Thursday', and a value 'thu'. The two arguments correspond to the label attribute and the value attribute on the listitem element. The value is used only as an extra optional value associated with an item whic...
...lue to change the selection. In the next example, the selectedIndex property of a radiogroup element is changed based on the value entered in a textbox. This code isn't foolproof though; for example it doesn't check if the value entered is out of range. You will want to make sure that you add this kind of error checking. ...
...iogroup element is changed based on the value entered in a textbox. This code isn't foolproof though; for example it doesn't check if the value entered is out of range. You will want to make sure that you add this kind of error checking. ...
...And 3 more matches
Developing cross-browser and cross-platform pages - Archive of obsolete content
t detection, you only implement those features whose support you have first tested and verified on the visiting browser. This method has the advantage of not requiring you to test for anything except whether the particular features you code are supported in the visiting browser. Let's see a basic, simple object support detection example. ...
...hose features whose support you have first tested and verified on the visiting browser. This method has the advantage of not requiring you to test for anything except whether the particular features you code are supported in the visiting browser. Let's see a basic, simple object support detection example. ...
... verified on the visiting browser. This method has the advantage of not requiring you to test for anything except whether the particular features you code are supported in the visiting browser. Let's see a basic, simple object support detection example. ...
...And 3 more matches
CanvasRenderingContext2D.arcTo() - Web APIs
magine two straight segments: one from the starting point to a first control point, and another from there to a second control point. Without arcTo(), these two segments would form a sharp corner: arcTo() creates a circular arc that fits this corner and smooths is out. In other words, the arc is tangential to both segments. ...
...></canvas> JavaScript The arc begins at the point specified by moveTo(): (230, 20). It is shaped to fit control points at (90, 130) and (20, 20), and has a radius of 50. The lineTo() method connects the arc to (20, 20) with a straight line. Note that the arc's second control point and the point specified by lineTo() are the same, which produces a totally smooth corner. ...
... Result of a large radius If you use a relatively large radius, the arc may appear in a place you didn't expect. In this example, the arc's connecting line goes above, instead of below, the coordinate specified by moveTo(). This happens because the radius is too large for the arc to fit entirely below the starting point. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(180, 90); ctx.arcTo(180,130, 110,130, 130); ctx.lineTo(110, 130); ctx.stroke(); Result Live demo More sophisticated demo of the method. You can play around with range input to see how arc changes. HTML <div> <label for="radius">Radius: </label> <input name="radius" type="range" id="radius" min=0 max=100 valu...
...And 3 more matches
Advanced animations - Web APIs
. Drawing a ball We are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. The following code will set us up. <canvas id="canvas" width="600" height="300"></canvas> As usual, we need a drawing context first. To draw the ball, we will create a ball object which contains properties and a draw() method to paint it on the canvas. ...
...e arc() method. Adding velocity Now that we have a ball, we are ready to add a basic animation like we have learned in the last chapter of this tutorial. Again, window.requestAnimationFrame() helps us to control the animation. The ball gets moving by adding a velocity vector to the position. For each frame, we also clear the canvas to remove old circles from prior frames. ...
...method: 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; } First demo Let's see how it looks in action so far. Move your mouse into the canvas to start the animation. ...
...And 3 more matches
Pixel manipulation with canvas - Web APIs
ixel array that getImageData() provides us. Finally, we use the array data to set a background color and a text in the <div> to display the color. ...
...width="300" height="227" style="float:left"></canvas> <div id="color" style="width:200px;height:50px;float:left"></div> var img = new Image(); img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg'; var canvas = document.
getElementById('canvas'); var ctx = canvas.getContext('2d'); img.onload = function() { ctx.drawImage(img, 0, 0); img.style.display = 'none'; }; var color = document.
getElementById('color'); function pick(event) { var x = event.layerX; var y = event.layerY; var pixel = ctx.getImageData(x, y, 1, 1); var data = pixel.data; var rgba = 'rgba(' + data[0] + ', ' + data[1] + ', ' + data[2] + ', ' + (data[3] / 255) + ')'; color.style.background = rgba; color.textContent = rgba; } canvas.addEventListener('mousemove', pick); Painting pixel data into a ...
...le on Wikipedia for more information. ...
...And 3 more matches
Node.removeChild() - Web APIs
ild of this node. If the child doesn't exist on the DOM of the page, the method throws the following exception: Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'. ...
...ist on the DOM of the page, the method throws the following exception: Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'. ...
... 'Node'. ...
...And 3 more matches
Using the Web Animations API - Web APIs
JavaScript keyword Infinity. And instead of timing-function we use easing. We aren't listing an easing value here because, unlike CSS Animations where the default animation-timing-function is ease, in the Web Animations API the default easing is linear -- which is what we want here. ...
....
getElementById("alice").animate( aliceTumbling, aliceTiming ) And boom: the animation starts playing (see the finished version on Codepen). The animate() method can be called on any DOM element that could be animated with CSS. And it can be written in several ways. ...
...te3D(-50%, -50%, 0)', color: '#000' }, { color: '#431236', offset: 0.3}, { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' } ], { duration: 3000, iterations: Infinity } ); What's more, if we only wanted to specify the duration of the animation and not its iterations (by default, animations iterate once), we could pass in the milliseconds alone: document.
getElementById("alice").animate( [ { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' }, { color: '#431236', offset: 0.3}, { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' } ], 3000); Controlling playback with play(), pause(), reverse(), and updatePlaybackRate() While we can write CSS Animations with the Web Animations API, where the API really comes in h...
...And 3 more matches
Audio and video manipulation - Developer guides
480" height="270"></canvas> JavaScript This code handles altering the frames. ...
...handles altering the frames. ...
... playbackRate property works with both <audio> and <video>, but in both cases, it changes the playback speed but not the pitch. To manipulate the audio's pitch you need to use the Web Audio API. See the AudioBufferSourceNode.playbackRate property. ...
...And 3 more matches
Constraint validation - Developer guides
\d{5}$' , "France ZIPs must have exactly 5 digits: e.g. F-75012 or 75012" ], de : [ '^(D-)?\\d{5}$' , "Germany ZIPs must have exactly 5 digits: e.g. ...
... : [ '^(D-)?\\d{5}$' , "Germany ZIPs must have exactly 5 digits: e.g. ...
... Limiting the size of a file before its upload Another common constraint is to limit the size of a file to be uploaded. Checking this on the client side before the file is transmitted to the server requires combining the Constraint Validation API, an...
...And 3 more matches
Example - SVG: Scalable Vector Graphics
<p> This is done completely in W3C Standards-XHTML, SVG and JavaScript-no flash or any vendor specific extensions. Currently, this will work in Mozilla Firefox version 1.5 and above. </p> <div> (C) 2006 <a id='emailme' href='#'>Nick Johnson</a> <script type='text/javascript'> <![CDATA[ // foil spam bots var email = '@riovia.net'; email ='nick' + email; document.
getElementById('emailme').href = 'mailto:'+email; ]]> </script> This software is free for you to use in any way whatsoever, and comes with no warranty at all. </div> <form action="" onsubmit="return false;"> <p> <label>Number of motes:</label> <input id='num_motes' value='5'/> <br/> <label>Max. Velocity:</label> <input id='max_velocity' value='15'/> <br/> <label>Attrac...
...ut id='max_velocity' value='15'/> <br/> <label>Attraction to cursor:</label> <input id='attract_cursor' value='6'/> <br/> <label>Repulsion from peers:</label> <input id='repel_peer' value='5'/> <br/> </p> </form> <script type='text/javascript'> <![CDATA[ // Array of motes var motes; // Get the display element. function Display() { return document.
getElementById('display'); } // Determine dimensions of the display element. // Return this as a 2-tuple (x,y) in an array function Dimensions() { // Our Rendering Element var display = Display(); var width = parseInt( display.getAttributeNS(null,'width') ); var height = parseInt( display.getAttributeNS(null,'height') ); return [width,height]; } // This is called by mouse move ev...
...ur Rendering Element var display = Display(); var width = parseInt( display.getAttributeNS(null,'width') ); var height = parseInt( display.getAttributeNS(null,'height') ); return [width,height]; } // This is called by mouse move events var mouse_x = 200, mouse_y = 150; function OnMouseMove(evt) { mouse_x = evt.clientX; mouse_y = evt.clientY; var widget = document.
getElementById('cursor'); widget.setAttributeNS(null,'cx',mouse_x); widget.setAttributeNS(null,'cy',mouse_y); } document.onmousemove = OnMouseMove; // Determine (x,y) of the cursor function Cursor() { return [mouse_x, mouse_y]; } // Determine average (x,y) of the swarm function AverageMotePosition() { if( !motes ) return [0,0]; if( motes.length == 0 ) return [0,0]; ...
...And 3 more matches
widget - Archive of obsolete content
ng" id="pause-button"> <img src="stop.png" id="stop-button"> </body> </html> We just include three icons, and assign an ID to each one. This HTML file, and the icon files it references, are saved in the add-on's data directory. ...
... an ID to each one. This HTML file, and the icon files it references, are saved in the add-on's data directory. Next, we write a content script that listens for click events on each icon and sends the corresponding message to the main add-on code: var play_button = document.
getElementById("play-button"); play_button.onclick = function() { self.port.emit("play"); } var pause_button = document.
getElementById("pause-button"); pause_button.onclick = function() { self.port.emit("pause"); } var stop_button = document.
getElementById("stop-button"); stop_button.onclick = function() { self.port.emit("stop"); } We save this file in the add-on's data directory as "button-script.js". Finally. in the add-on's "main.js" file, we create the widget, assign it the HTML file and the content script, and listen ...
...difference is that these scripts access the postMessage and port objects through the addon object, whereas content scripts access them through the self object. To show the difference, convert the player add-on above to use normal page scripts instead of content scripts. ...
...And 2 more matches
ui/frame - Archive of obsolete content
der: // listen for messages from the add-on, and send a reply window.addEventListener("message", function(event) { event.source.postMessage("pong", event.origin) }, false); This frame script listens to change events on the "city-selector" <select> element, and sends a message to the add-on containing the value for the newly selected element. // city-info.js var citySelector = window.document.
getElementById("city-selector"); citySelector.addEventListener("change", cityChanged); function cityChanged() { window.parent.postMessage(citySelector.value, "*"); } To listen for these messages in the main add-on code, you can assign a listener to the frame's message event. The data property of the event is the message payload. var { Frame } = require("sdk/ui/frame"); var { Toolbar } = require("sdk/ui/too...
...In this way you can customize the frame for each browser window. To do this, you call postMessage() not on the Frame itself but on the source attribute of the object passed into an event listener. For targetOrigi...
... also provide access to source and origin. To receive such messages in the frame script, listen for the window's message event: window.addEventListener("message", handlePong, false); Sending JSON In all cases, you can send a string as a message or a JSON object. ...
...And 2 more matches
HTML to DOM - Archive of obsolete content
See Using a hidden iframe element to parse HTML to a window's DOM below. Parsing Complete HTML to DOM Loading an HTML document seems much simpler if it's loaded using the XMLHttpRequest object. For that matter, we're going to load our HTML document first: var request = XMLHttpReq...
...xample"); doc.documentElement.innerHTML = request.responseText; after this any manipulation that we might want to do will be something as simple as the following: doc.body.textContent = "This is inside the body!"; Using a hidden iframe element to parse HTML to a window's DOM Sample code may need more work. Create your own function using unique name, ID, and so forth. ...
...function using unique name, ID, and so forth. ...
...And 2 more matches
PopupEvents - Archive of obsolete content
own event will be fired when the UI is updated 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. ...
...ple, 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. ...
...cause you cannot open a submenu directly without first opening the parent menu. ...
...And 2 more matches
Modifying a XUL Interface - Archive of obsolete content
s using the createElement() function of the document. It takes one argument, the tag name of the element to create. You can then set attributes of the element using the setAttribute() function and append it to the XUL document using the appendChild() function. For example, the following will add a button to a XUL window: Example 1 : Source View <script> function addButton(){ var aBox = document.
getElementById("aBox"); var button = document.createElement("button"); button.setAttribute("label","A new Button"); aBox.appendChild(button); } </script> <box id="aBox" width="200"> <button label="Add" oncommand="addButton();"/> </box> This example has two parts a box container element in XUL. Notice that this is NOT the same as a vbox or an hbox. (This is discussed more in the Box Model...
...re in the Box Model pages.) the box element has two attributes "id" and "width". the box element contains a button element. the button element has two attributes "label" and "oncommand" a Javascript function named "addButton()" This script first gets a reference to the box with
getElementById(), which is the container to add a new button to. The function
getElementbyID() does not know that the box it is looking for happens to be containing the tag that has the oncommand attribute that referenced it.
getElementById() only knows the box it is looking to find has an id with the value "aBox". This is a subtle dependency between the function and the XUL element to which you should pay atte...
...ction and the XUL element to which you should pay attention. addButton() the calls the createElement() function to create a new button. Note this button is not visible, nor is it attached to anything yet. addButton() then assigns the label 'A new Button' to the button using the setAttribute() function. Finally the appendChild() function of the particular box found by
getElementbyID() is called to add the button to it. At this point, the button is attached to a visible box, so it becomes visible as well. The button with the label "Add" can be pressed multiple times and it will continue to add new buttons, each of which will have the label "A new Button", and will only be distinguishable by their place as children in the box element with the id "abox". ...
...And 2 more matches
XUL Questions and Answers - Archive of obsolete content
UL code to use for popup - alternatively it can send generic XML describing the attributes of the items in the menu and you generate the XUL on client by applying an XSLT transform.) Can I change a XUL tree cell/row/item background color with JavaScript? To set the background color you need to set the property for the cell/row and not for the item. ...
...} The person can get the titles too using the .contentTitle tag. ...
...Python has full support for variants. Pass a Python string/int/etc to the method requiring an nsIVariant. A Python object is convered when implmenting an interface taking an nsIVariant. How do I close the "showPopup" which is automatically opened when the "oncontextmenu" event is called? If you have a similar code base as the following: onBookmarkContextMenu: function(event, id) { document.
getElementById("bookmarkPopup").showPopup(document.
getElementById(id), event.screenX + 6, event.screenY + 6, "popup", "bottomright", "bottomright"); } Use the hidePopup() function to solve this issue. What is an example of addProgressListener? An example of this is this: // Associate the progress listener for a "browser" to a listener object browserObject.addProgressListener( listObj, Components.
...And 2 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
ype of detection which originally was written to support only Netscape Navigator 4 and Internet Explorer 4 might look like: // WRONG APPROACH - do not use! ...
...
getElementById became available in Internet Explorer 5 and later in Netscape 6 (Gecko). Many web authors decided that the easiest way to add support for Netscape Gecko was to add another code fork as follows: // WRONG APPROACH - do not use! if (document.all) { // IE4 height = document.body.offsetHeight; } else if (document.layers) { // NN4 height = window.innerHeight; } else if (document.
getElementById) { // They think this is Gecko // but could be wrong! height = window.innerHeight; } else { // other height = 0; } The approach is incorrect since it assumes that the only other browser besides Internet Explorer 5+ that implements document.
getElementById is Gecko. This is not true today and will become even less true as more browsers which support the W3C DOM Standards are introduced ...
...ample 2 - object based feature detection Cross Browser Support This example also illustrates the use of feature detection and shows the complications that can arise from the non standard implementations in other browsers. ...
...And 2 more matches
HTML text fundamentals - Learn web development
rried to a fish.</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.
getElementById('code'); var reset = document.
getElementById('reset'); var solution = document.
getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = ht...
...ggs bread hummus</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.
getElementById('code'); var reset = document.
getElementById('reset'); var solution = document.
getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = ht...
...ters up the road</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.
getElementById('code'); var reset = document.
getElementById('reset'); var solution = document.
getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = ht...
...And 2 more matches
Transformations - Web APIs
next section. You can call the save() method as many times as you like. Each time the restore() method is called, the last saved state is popped off the stack and all saved settings are restored. A save and restore canvas state example This example tries to illustrate how the stack of drawing states functions by drawing a set of consecutive rectangles. ...
...sier to understand and use. In the draw() function, we call the fillRect() function nine times using two for loops. In each loop, the canvas is translated, the rectangle is drawn, and the canvas is returned back to its original state. Note how the call to fillRect() uses the same coordinates each time, relying on translate() to adjust the drawing position. ...
...eed to move the canvas by using the translate() method. A rotate example In this example, we'll use the rotate() method to first rotate a rectangle from the canvas origin and then from the center of the rectangle itself with the help of translate(). Reminder: Angles are in radians, not degrees. To convert, we are using: radians = (Math.PI/180)*degrees. ...
...And 2 more matches
MediaDevices.ondevicechange - Web APIs
width: 48%; margin-right: 2% } .right { float:right; width: 48%; margin-left: 2% } .deviceList { border: 1px solid black; list-style-type: none; margin-top: 2px; padding: 6px; } JavaScript content Other code Below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail. ...
...right; width: 48%; margin-left: 2% } .deviceList { border: 1px solid black; list-style-type: none; margin-top: 2px; padding: 6px; } JavaScript content Other code Below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail. ...
...type: none; margin-top: 2px; padding: 6px; } JavaScript content Other code Below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail. ...
...And 2 more matches
Pointer events - Web APIs
nt) { } function enter_handler(event) { } function down_handler(event) { } function move_handler(event) { } function up_handler(event) { } function cancel_handler(event) { } function out_handler(event) { } function leave_handler(event) { } function gotcapture_handler(event) { } function lostcapture_handler(event) { } function init() { var el=document.
getElementById("target"); // Register pointer event handlers el.onpointerover = over_handler; el.onpointerenter = enter_handler; el.onpointerdown = down_handler; el.onpointermove = move_handler; el.onpointerup = up_handler; el.onpointercancel = cancel_handler; el.onpointerout = out_handler; el.onpointerleave = leave_handler; el.gotpointercapture = gotc...
...</div> </body> </html> Determining the Primary Pointer In some scenarios there may be multiple pointers (for example a device with both a touchscreen and a mouse) or a pointer supports multiple contact points (for example a tou...
... be re-targeted to a particular element instead of the normal hit test at a pointer's location. This can be used to ensure that an element continues to receive pointer events even if the pointer device's contact moves off the element (for example by scrolling). The following example shows pointer capture being set on an element. <html> <script> function downHandler(ev) { let el = document.
getElementById("target"); // Element 'target' will receive/capture further events el.setPointerCapture(ev.pointerId); } function init() { let el = document.
getElementById("target"); el.onpointerdown = downHandler; } </script> <body onload="init();"> <div id="target"> Touch me ... </div> </body> </html> The following example shows a pointer capture being released (when a pointercancel ...
...And 2 more matches
Touch events - Web APIs
e a stylus or other contact method. 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. ...
...r <canvas> element so we can handle the touch events as they occur. Tracking new touches We'll keep track of the touches in-progress. var ongoingTouches = []; When a touchstart event occurs, indicating that a new touch on the surface has occurred, the handleStart() function below is called. ...
...how up neatly. Drawing as the touches move Each time one or more fingers move, a touchmove event is delivered, resulting in our handleMove() function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch. ...
...And 2 more matches
Writing WebSocket client applications - Web APIs
end reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data: // Send text to all users through the server function sendText() { // Construct a msg object containing the data the server needs to process the message from the chat client. ...
...To handle it, add an event listener for the message event, or use the onmessage event handler. ...
...eceiving and interpreting JSON objects Let's consider the chat client application first alluded to in Using JSON to transmit objects. ...
...And 2 more matches
Window.pageYOffset - Web APIs
elis. Mauris efficitur tellus massa, id ullamcorper ipsum fermentum eu. Aenean mollis dignissim ultrices. Nunc gravida, sem sit amet lobortis iaculis, dolor ligula convallis nibh, id condimentum metus libero nec odio. Quisque nec ante pretium, viverra neque nec, facilisis risus. Duis condimentum sapien non felis cursus blandit. Integer euismod lectus a ipsum pellentesque lacinia.</p> `; document.
getElementById("frame").contentDocument .body.innerHTML = contentHTML; In this example, an <iframe> is created and filled with content, then a specific element within the document is scrolled into view in the frame. Once that's done, the vertical scroll position is checked by looking at the value of pageYOffset in the frame's contentWindow. HTML The HTML is extremely simple and has just two element...
...oll position is checked by looking at the value of pageYOffset in the frame's contentWindow. HTML The HTML is extremely simple and has just two elements: an <iframe> that contains the document we're going to scroll, and a <div> into which we'll output the value of pageYOffset when we've finished the scroll. ...
...ntWindow. HTML The HTML is extremely simple and has just two elements: an <iframe> that contains the document we're going to scroll, and a <div> into which we'll output the value of pageYOffset when we've finished the scroll. ...
...And 2 more matches
Getting Started - Developer guides
Script will request an HTML document, 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. ...
...We'll change the request method from GET to POST, and include our data as a parameter in the call to httpRequest.send(): function makeRequest(url, userName)...
...We'll change the request method from GET to POST, and include our data as a parameter in the call to httpRequest.send(): function makeRequest(url, userName) { ... httpRequest.onreadystatechange = alertContents; httpRequest.o...
...And 2 more matches
Dialogs and Prompts - Archive of obsolete content
// Notice if user clicks cancel, window.arguments[0].out remains null // be...
... // Notice if user clicks cancel, window.arguments[0].out remains null // because this function is never called window.arguments[0].out = {name:d...
..."center"><spacer/><checkbox id="enabled" label="Check to Enable"/></row> </rows> </grid> </dialog> mydialog.js: // Called once when the dialog displays function onLoad() { // Use the arguments passed to us by the caller document.
getElementById("name").value = window.arguments[0].inn.name; document.
getElementById("description").value = window.arguments[0].inn.description; document.
getElementById("enabled").checked = window.arguments[0].inn.enabled; } // Called once if and only if the user clicks OK function onOK() { // Return the changed arguments. // Notice if user clicks cancel, window.arguments[0].out remains null // because this function is never called window.arguments[0].out = {name:document.
getElementById("name").value, description:document.
getElementById("des...
...nn.enabled; } // Called once if and only if the user clicks OK function onOK() { // Return the changed arguments. // Notice if user clicks cancel, window.arguments[0].out remains null // because this function is never called window.arguments[0].out = {name:document.
getElementById("name").value, description:document.
getElementById("description").value, enabled:document.
getElementById("enabled").checked}; return true; } See also Passing parameter to a dialog and getting return values from it. Displaying the standard "Open File"/"Save File"/"Select Folder" dialogs nsIFilePicker Prompts and the prompt service Now that you understand dialogs, let's examine prompts. Prompts differ from dialogs in that they don't require custom XUL. Because of this, however, they are less ...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
manually trigger an event handler that is defined directly in the XUL document. Consider the following XUL fragment throughout the rest of this section. <menuitem id="mymenu" oncommand="executeSomething(); executeSomethingElse();"/> <label id="mylabel" onclick="executeSomething(); executeSomethingElse();"/> Add-on authors commonly use eval to trigger the handlers. // DO NOT USE eval(document.
getElementById("mymenu").getAttribute("oncommand")); eval(document.
getElementById("mylabel").getAttribute("onclick")); Alternative: Dispatch real events Dispatching real events has the added bonus that all other event listeners for that Element (and the corresponding bubbling/capturing chain) will fire as well, so this method will have the closed resemblance to a real user event. // Fake a command event var...
...e("onclick")); Alternative: Dispatch real events Dispatching real events has the added bonus that all other event listeners for that Element (and the corresponding bubbling/capturing chain) will fire as well, so this method will have the closed resemblance to a real user event. // Fake a command event var event = document.createEvent("Events"); event.initEvent("command", true, true); document.
getElementById("mymenu").dispatchEvent(event); // Fake a mouse click var mouseEvent = document.createEvent("MouseEvents"); event.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); document.
getElementById("mylabel").dispatchEvent(mouseEvent); Please see the corresponding documentation on how to use and initialize particular event types. Alternative: Element.click...
...nt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); document.
getElementById("mylabel").dispatchEvent(mouseEvent); Please see the corresponding documentation on how to use and initialize particular event types. Alternative: Element.click() XUL and HTML elements have a pre-defined .click() method that will fire a synthesized click event. document.
getElementById("mybutton").click(); Alternative: Element.doCommand() XUL elements that have a command (oncommand or command attribute) assigned will also have a working doCommand method. ...
...tation on how to use and initialize particular event types. Alternative: Element.click() XUL and HTML elements have a pre-defined .click() method that will fire a synthesized click event. document.
getElementById("mybutton").click(); Alternative: Element.doCommand() XUL elements that have a command (oncommand or command attribute) assigned will also have a working doCommand method. document.
getElementById("mymenu").doCommand(); Alternative: Just hard-code what should happen If you know that the current version of the application will call { executeSomething(); executeSomethingElse();} then just do the same in your code. Of course, you'll need to update your add-on if the application changes. Accessing properties via computed names Not that common anymore, but still existing, are Add-Ons or ot...
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
eCallBack function is called in the context of the parent document (the originator). Here, iframeCallback is considered the Data Binder, so it is responsible for getting the content from the IFRAME and putting it in the proper repository in the page's context. Note the following piece of code: function iframeCallback(doc) { /* Copies the data in the iframe to the main page */ myData = doc.
getElementById("mydata"); tickerDiv.innerHTML = myData.innerHTML; } The callback is called with the parameter doc, which is a reference to the IFRAME's document). The code locates element with ID mydata then copies the content of mydata (myData.innerHTML) into the tickerDiv element (DIV element that is the container of elements into the Ticker). The above example is a simplified version of the inner-browsin...
...owing code snippet shows a simplified version of the logic that happens in the actual sample: // doc is the DOM to the document returned articles=doc.getElementsByTagName("article"); for(i=0;i<articles.length;i++) { // acquiring the data from the DOM... articleTitle=article.getElementsByTagName("article").item(0).firstChild.nodeValue; // inserting the content into the container.. ...
...n. * Portions created by the Initial Developer are Copyright (C) 2003 * the Initial Developer. All Rights Reserved. ...
...em(0).firstChild.nodeValue; tagname="summary"; // ie fix if(document.all) tagname="nde:"+tagname; paraa=article.getElementsByTagName(tagname).item(0).firstChild.nodeValue; linkk=article.getAttribute("url"); strvalue="<div class='nde-blurb'><h3><a href='"+linkk+"'>"+valuee+"</a></h3><p>"+paraa+"</p></div>"; document.
getElementById("container").innerHTML+=strvalue; } } if(previousEle) { previousEle.style.backgroundColor="white"; } ele.style.backgroundColor="#ddeeff"; previousEle=ele; } var previousEle=null; </script> <style> .tab { position:relative;top:1px; border: 1px solid #dddddd; color:white; background-color:white; padding-left: 5px; border-bottom:white;padding-right: 5px; padding-top:3px; text-dec...
Introducing the Audio API extension - Archive of obsolete content
Once the buffer is full, the event MozAudioAvailable is triggered. This event ther...
...Conte...
...Content scripts can specify the audio stream's characte...
...am Since the MozAudioAvailable event and the mozWriteAudio() method both use Float32Array values, it is possible to take the output of one audio stream and pass it directly (or process first and then pass) to a second. The first audio stream needs to be muted so that only the second audio element is heard. <audio id="a1" src="song.ogg" controls> </audio> <script> var a1 = document.
getElementById('a1'), a2 = new Audio(), buffers = []; function loadedMetadata() { // Mute a1 audio. a1.volume = 0; // Setup a2 to be identical to a1, and play through there. a2.mozSetup(a1.mozChannels, a1.mozSampleRate); } function audioAvailable(event) { // Write the current framebuffer var frameBuffer = event.frameBuffer; writeAudio(frameBuffer); } a1.addEventListener('MozAudioAvailab...
ContextMenus - Archive of obsolete content
hen the label is right-clicked for instance, 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 migh...
...ing to images, whereas clicking on a link would display items pertaining to links. In many cases, it may be easier to use a single context menu containing every possible item, and show and hide the necessary items when needed. To hide an item, set its hidden property to true. To show an item, set its hidden property to false. <script> function showHideDeleteItem() { var deleteItem = document.
getElementById("delete"); var rows = document.
getElementById("rows"); deleteItem.hidden = (rows.childNodes.length == 0); } </script> <menupopup id="inssel-menu" onpopupshowing="showHideDeleteItem()"> <menuitem label="Insert"/> <menuitem id="delete" label="Delete"/> </menupopup> In this example, the showHideDeleteItem function is called when the popupshowing event is fired. This function checks if th...
... triggerNode property is checked for a popup attached to a browser to determine whether an image is clicked: <script> function showHideItems(aEvent) { // aEvent.target is the popup for which the popupshowing event fired. ...
... a browser to determine whether an image is clicked: <script> function showHideItems(aEvent) { // aEvent.target is the popup for which the popupshowing event fired. ...
Tree Box Objects - Archive of obsolete content
let boxobject = tree.boxObject; boxobject.queryInterface("Components.interfaces.nsITreeBoxObject"); Scrolling the Tree You can also scroll the tree using four different methods, similar to those available for listboxes. The scrollToRow() function may be used to scroll to a particular row. Here is a simple example. ...
...erface("Components.interfaces.nsITreeBoxObject"); Scrolling the Tree You can also scroll the tree using four different methods, similar to those available for listboxes. The scrollToRow() function may be used to scroll to a particular row. Here is a simple example. ...
...t thing to note is that the coordinates are measured from the upper left corner of the containing document, not the edge of the tree itself. This makes it easy to pass event coordinates directly to these functions, as in the following example of the getCellAt() function. ...
...> function updateFields(event){ var row = {}, column = {}, part = {}; var tree = document.
getElementById("thetree"); var boxobject = tree.boxObject; boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject); boxobject.getCellAt(event.clientX, event.clientY, row, column, part); if (column.value && typeof column.value != "string") column.value = column.value.id; document.
getElementById("row").value = row.value; document.
getElementById("column").value = column.value; document.
getElementById("part").value = part.value; } </script> <tree id="thetree" flex="1" onmousemove="updateFields(event);"> <treecols> <treecol id="utensil" label="Utensil" primary="true" flex="1"/> <treecol id="count" label="Count" flex="1"/> </treecols> <treechildren> <treeitem> <t...
Extentsions FAQ - Archive of obsolete content
s to the toolbars." Option #4 Install Toolbar Control <http://webdesigns.ms11.net/chromeditp.html> Asking for help with getting an extension to process Windows messages. use WM_COPYDATA How to creating an extension that can replace HTML code on a specific page that does not use Greasemonkey? var newNode = document.createElement(" ... html content here ... ...
... the size of the stack. <image left="0" top="0"> would seem to suffice. Could there be more than two images to reflect more than two states?Does the rules in the CSS file have to be in any particular order (if two rules match, which is chosen)? I have two states switching images in the tool bar and would have no problem implementing a third, so yes it's possible. ...
...e be more than two images to reflect more than two states?Does the rules in the CSS file have to be in any particular order (if two rules match, which is chosen)? I have two states switching images in the tool bar and would have no problem implementing a third, so yes it's possible. ...
...Take a look at the bottom of http://svn.dojotoolkit.org/dojo/trunk/dojo.js see what it's trying to load and wr...
Browser Feature Detection - Archive of obsolete content
ateEntityReference()Obsolete since Gecko 7 true false false Document.getElementsByTagName() true true true Document.importNode() true false true Document.createElementNS() true false true Document.createAttributeNS() true false true Document.getElementsByTagNameNS() true false true Document.
getElementById() true true true DOM Level 1 HTML Support for properties/methods in document name Firefox 1.5 IE 6 & 7 Opera 8.54 - 9.01 Document.documentElement true true true Document.createElement() true true true Document.createDocumentFragment() true true true Document.createTextNode() true true tru...
...ent.links true true true Document.forms true true true Document.anchors true true true Document.cookie true true true Document.open() true true true Document.close() true true true Document.write() true true true Document.writeln() true true true Document.
getElementById() true true true Document.getElementsByName() true true true DOM CSS 1 Support for properties/methods in document.body.style name Firefox 1.5 IE 6 & 7 Opera 8.54 - 9.01 background true true true backgroundattachment true true true backgroundcolor true true true backgroundimage t...
...: 'images', 'supported': false}, {name: 'applets', 'supported': false}, {name: 'links', 'supported': false}, {name: 'forms', 'supported': false}, {name: 'anchors', 'supported': false}, {name: 'cookie', 'supported': false}, {name: 'open', 'supported': false}, {name: 'close', 'supported': false}, {name: 'write', 'supported': false}, {name: 'writeln', 'supported': false}, {name: '
getElementById', 'supported': false}, {name: 'getElementsByName', 'supported': false} ], 'DOMCORE2': [ {name: 'doctype', 'supported': false}, {name: 'implementation', 'supported': false}, {name: 'documentElement', 'supported': false}, {name: 'createElement', 'supported': false}, {name: 'createDocumentFragment', 'supported': false}, {name: 'createTextNode', 'supported': false}, {name: 'createC...
...ruction', 'supported': false}, {name: 'createAttribute', 'supported': false}, {name: 'createEntityReference', 'supported': false}, {name: 'getElementsByTagName', 'supported': false}, {name: 'importNode', 'supported': false}, {name: 'createElementNS', 'supported': false}, {name: 'createAttributeNS', 'supported': false}, {name: 'getElementsByTagNameNS', 'supported': false}, {name: '
getElementById', 'supported': false} ], 'DOMCSS1': [ {name: 'background', 'supported': false}, {name: 'backgroundAttachment', 'supported': false}, {name: 'backgroundColor', 'supported': false}, {name: 'backgroundImage', 'supported': false}, {name: 'backgroundRepeat', 'supported': false}, {name: 'border', 'supported': false}, {name: 'borderSpacing', 'supported': false}, {name: 'borderStyle', '...
Sending forms through JavaScript - Learn web development
onseText ); } ); // Define what happens in case of error XHR.addEventListener( "error", function( event ) { alert( 'Oops! Something went wrong.' ); } ); // Set up our request XHR.open( "POST", "https://example.com/cors.php" ); // The data sent is what the user provided in the form XHR.send( FD ); } // Access the form element... const form = document.
getElementById( "myForm" ); // ...and take over its submit event. form.addEventListener( "submit", function ( event ) { event.preventDefault(); sendData(); } ); } ); Here's the live result: You can even get more involved with the process by using the form's elements property to get a list of all of the data elements in the form and manually manage them one at a time. To learn more about that...
..."theFile" name="myFile" type="file"> </p> <button>Send Me!</button> </form> As you see, the HTML is a standard <form>. There's nothing magical going on. The "magic" is in the JavaScript: // Because we want to access DOM nodes, // we initialize our script at page load. ...
...</form> As you see, the HTML is a standard <form>. There's nothing magical going on. The "magic" is in the JavaScript: // Because we want to access DOM nodes, // we initialize our script at page load. window.addEventListener( 'load', function () { // These variables are used to store the form data const text = document.
getElementById( "theText" ); const file = { dom : document.
getElementById( "theFile" ), binary : null }; // Use the FileReader API to access file content const reader = new FileReader(); // Because FileReader is asynchronous, store its // result when it finishes to read the file reader.addEventListener( "load", function () { file.binary = reader.result; } ); // At page load, if a file is already selected, read it. if( file.dom.files...
... Something went wrong.' ); } ); // Set up our request XHR.open( 'POST', 'https://example.com/cors.php' ); // Add the required HTTP header to handle a multipart form data POST request XHR.setRequestHeader( 'Content-Type','multipart/form-data; boundary=' + boundary ); // And finally, send our data. XHR.send( data ); } // Access our form... const form = document.
getElementById( "theForm" ); // ...to take over the submit event form.addEventListener( 'submit', function ( event ) { event.preventDefault(); sendData(); } ); } ); Here's the live result: Conclusion Depending on the browser and the type of data you are dealing with, sending form data through JavaScript can be easy or difficult. The FormData object is generally the answer, and you can use a ...
Add to iPhoto
the core of the extension itself. This is done in the iPhoto object in the extension's code. Hooking 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. ...
...Photo object in the extension's code. Hooking 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. ...
...e user has right-clicked on an image. if (document.
getElementById("contentAreaContextMenu")) { document.
getElementById("contentAreaContextMenu").addEventListener("popupshowing", iPhoto.onPopup, false); } Responding when the context menu is clicked When the user right-clicks an image, our handler gets called: onPopup: function() { var node = iPhoto.getCurrentNode(); var item = document.
getElementById("add-to-iphoto_menuitem"); if (item) { item.hidden = (node == null); // Hide it if we're not on an image } } This code finds the image node the user right-clicked in by calling our getCurrentNode() method, then sets the hidden state of the "Add Image to iPhoto" menu item based on whether or not an image node was found. The code to identify the node looks like this: getCurrentNode: fu...
...l, null, null, null); var appstr = "file:///Applications/iPhoto.app"; var appstrCF = CoreFoundation.CFStringCreateWithCharacters(null, appstr, appstr.length); var appurl = CoreFoundation.CFURLCreateWithString(null, appstrCF, null); CoreFoundation.CFRelease(appstrCF); var b = CoreFoundation.CFURLGetFSRef(appurl, ref.address()); if (!b) { var stringsBundle = document.
getElementByID("string-bundle"); alert(stringsBundle.getString('alert_download_error_string')); } else { var array = ctypes.cast(mutableArray, CoreFoundation.CFArrayRef); AppServices.LSOpenURLsWithRole(array, 0, null, appParams.address(), null, 0); } CoreFoundation.CFRelease(appurl); // Clean up CoreFoundation.CFRelease(array); } AppServices.shutdown(); Carbon.shu...
Using dynamic styling information - Web APIs
clarations for that element's styles, such as padding or margin or font, for example. To change a particular element's style, you can adapt the following example for the element(s) you want to style. <html> <head> <title>simple style example</title> <script type="text/javascript"> function alterStyle(elem) { elem.style.background = 'green'; } function resetStyle(elemId) { elem = document.
getElementById(elemId); elem.style.background = 'white'; } </script> <style type="text/css"> #p1 { border: solid blue 2px; } </style> </head> <body> <!-- passes a reference to the element's object as parameter 'this'. --> <p id="p1" onclick="alterStyle(this);"> Click here to change background color. </p> <!-- passes the 'p1' id of another element's style to modify. --> <button onclick="resetStyle('p1')...
...ed. It represents the in-line styles on a particular element. ...
... Using the setAttribute method Note that you can also change style of an element by...
...="stilo()">Click here to change text color</button> <button onclick="resetStyle()">Reset text color</button> </body> </html> The media and type of the style may or may not be given. Using the setAttribute method Note that you can also change style of an element by getting a reference to it and then use its setAttribute method to specify the CSS property and its value. var el = document.
getElementById('some-element'); el.setAttribute('style', 'background-color:darkblue;'); Be aware, however, that setAttribute removes all other style properties that may already have been defined in the element's style object. If the some-element element above had an in-line style attribute of say style="font-size: 18px", that value would be removed by the use of setAttribute. ...
Basic usage of canvas - Web APIs
k. To display something, a script first needs to access the rendering context and draw on it. The <canvas> element has a method called getContext(), used to obtain the rendering context and its drawing functions. getContext() takes one parameter, the type of context. For 2D graphics, such as those covered by this tutorial, you specify "2d" to get a CanvasRenderingContext2D. var canvas = document.
getElementById('tutorial'); var ctx = canvas.getContext('2d'); The first line in the script retrieves the node in the DOM representing the <canvas> element by calling the document.
getElementById() method. Once you have the element node, you can access the drawing context using its getContext() method. Checking for support The fallback content is displayed in browsers which do not support <canvas>. Scripts ...
...thod. Once you have the element node, you can access the drawing context using its getContext() method. Checking for support The fallback content is displayed in browsers which do not support <canvas>. Scripts can also check for support programmatically by simply testing for the presence of the getContext() method. Our code snippet from above becomes something like this: var canvas = document.
getElementById('tutorial'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); // drawing code here } else { // canvas-unsupported code here } A skeleton template Here is a minimalistic template, which we'll be using as a starting point for later examples. Note: it is not good practice to embed a script inside HTML. We do it here to keep the example concise. <!DOCTYPE html> <html> <he...
...on template Here is a minimalistic template, which we'll be using as a starting point for later examples. Note: it is not good practice to embed a script inside HTML. We do it here to keep the example concise. ...
...on. As shown here, it is initially blank. A simple example To begin, let's take a look at a simple example that draws two intersecting rectangles, one of which has alpha transparency. We'll explore how this works in more detail in later examples. ...
Drawing text - Web APIs
vides two methods to render text: fillText(text, x, y [, maxWidth]) Fills a given text at the given (x,y) position. Optionally with a maximum width to draw. strokeText(text, x, y [, maxWidth]) Strokes a given text at the given (x,y) position. Optionally with a maximum width to draw. A fillText example The text is filled using the current fillStyle. ...
... fillText example The text is filled using the current fillStyle. function draw() { var ctx = document.
getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.fillText('Hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw(); A strokeText example The text is filled using the current strokeStyle. function draw() { var ctx = document.
getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.strokeText('Hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw(); Styling text In the examples above we are already making use of the font property to make the text a bit larger than the default size. There are some more properties which let you adjust the way the text gets displayed on the canv...
...able code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.font = "48px serif"; ctx.textBaseline = "hanging"; ctx.strokeText("Hello world", 0, 100);</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()...
...ed 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. function draw() { var ctx = document.
getElementById('canvas').getContext('2d'); var text = ctx.measureText('foo'); // TextMetrics object text.width; // 16; } Gecko-specific notes In Gecko (the rendering engine of Firefox, Firefox OS and other Mozilla based applications), some prefixed APIs were implemented in earlier versions to draw text on a canvas. These are now deprecated and removed, and are no longer guaranteed to work. << Previ...
GlobalEventHandlers.onanimationend - Web APIs
ll get to that shortly. JavaScript content Before we get to the animation code, we define a function which logs information to a box on the user's screen. We'll use this to show information about the events we receive. Note the use of AnimationEvent.animationName and AnimationEvent.elapsedTime to get information about the event which occurred. ...
...d. ...
...For information about why, and how to support r...
...tart and animationend events: let box = document.
getElementById("box"); box.onanimationstart = function(event) { log("Animation started", event); } box.onanimationend = function(event) { log("Animation stopped", event); }; Finally, we set up a handler for a click on the button that runs the animation: document.
getElementById("play").addEventListener("click", function(event) { document.
getElementById("box").className = "slideAnimation"; event.target.style.display = "none"; }, false); This sets the class of the box we want to animate to the class that contains the animation description, then hides the play button because this example will only run the animation once. For information about why, and how to support running an animation more than once, see Run an animation again in CSS Animatio...
GlobalEventHandlers.onanimationstart - Web APIs
ll get to that shortly. JavaScript content Before we get to the animation code, we define a function which logs information to a box on the user's screen. We'll use this to show information about the events we receive. Note the use of AnimationEvent.animationName and AnimationEvent.elapsedTime to get information about the event which occurred. ...
...d. ...
...For information about why, and how to support r...
...tart and animationend events: let box = document.
getElementById("box"); box.onanimationstart = function(event) { log("Animation started", event); } box.onanimationend = function(event) { log("Animation stopped", event); }; Finally, we set up a handler for a click on the button that runs the animation: document.
getElementById("play").addEventListener("click", function(event) { document.
getElementById("box").className = "slideAnimation"; event.target.style.display = "none"; }, false); This sets the class of the box we want to animate to the class that contains the animation description, then hides the play button because this example will only run the animation once. For information about why, and how to support running an animation more than once, see Run an animation again in CSS Animatio...
GlobalEventHandlers.oninvalid - Web APIs
ole argument. Example This example demonstrates oninvalid and onsubmit event handlers on a form. HTML <form id="form"> <p id="error" hidden>Please fill out all fields.</p> <label for="city">City</label> <input type="text" id="city" required> <button type="submit">Submit</button> </form> <p id="thanks" hidden>Your data has been received. ...
...es oninvalid and onsubmit event handlers on a form. HTML <form id="form"> <p id="error" hidden>Please fill out all fields.</p> <label for="city">City</label> <input type="text" id="city" required> <button type="submit">Submit</button> </form> <p id="thanks" hidden>Your data has been received. ...
...orm. HTML <form id="form"> <p id="error" hidden>Please fill out all fields.</p> <label for="city">City</label> <input type="text" id="city" required> <button type="submit">Submit</button> </form> <p id="thanks" hidden>Your data has been received. ...
...den>Please fill out all fields.</p> <label for="city">City</label> <input type="text" id="city" required> <button type="submit">Submit</button> </form> <p id="thanks" hidden>Your data has been received. ...
GlobalEventHandlers.onsubmit - Web APIs
ole argument. Example This example demonstrates oninvalid and onsubmit event handlers on a form. HTML <form id="form"> <p id="error" hidden>Please fill out all fields.</p> <label for="city">City</label> <input type="text" id="city" required> <button type="submit">Submit</button> </form> <p id="thanks" hidden>Your data has been received. ...
...es oninvalid and onsubmit event handlers on a form. HTML <form id="form"> <p id="error" hidden>Please fill out all fields.</p> <label for="city">City</label> <input type="text" id="city" required> <button type="submit">Submit</button> </form> <p id="thanks" hidden>Your data has been received. ...
...orm. HTML <form id="form"> <p id="error" hidden>Please fill out all fields.</p> <label for="city">City</label> <input type="text" id="city" required> <button type="submit">Submit</button> </form> <p id="thanks" hidden>Your data has been received. ...
...den>Please fill out all fields.</p> <label for="city">City</label> <input type="text" id="city" required> <button type="submit">Submit</button> </form> <p id="thanks" hidden>Your data has been received. ...
Using the Media Capabilities API - Web APIs
tion> <option>2500</option> <option>800</option> </select> </li> </ul> <p><input type="button" value="Test this Video Configuration" id="tryit"></p> </form> <ul id="results"></ul> JavaScript let mc = { videoConfiguration : new Object(), tryit: function () { mc.createConfiguration(); mc.testit(); }, createConfiguration: function () { var size = document.
getElementById('size').value.split('x'); mc.videoConfiguration = { type: 'file', video: { contentType: document.
getElementById('codec').value, width: size[0], height: size[1], bitrate: document.
getElementById('bitrate').value, framerate: document.
getElementById('framerate').value, } } }, testit: function () { let content = ''; naviga...
...ion.video; content = 'A ' + mcv.width + 'x' + mcv.height + ', ' + mcv.contentType + ' at ' + mcv.framerate + 'fps and ' + mcv.bitrate + ' bps video ' + (result.supported ? ' IS ' : 'IS NOT ') + ' supported, ' + (result.smooth ? ' IS ' : ' is NOT ') + ' smooth, and' + (result.powerEfficient ? ...
...lt.supported ? ' IS ' : 'IS NOT ') + ' supported, ' + (result.smooth ? ' IS ' : ' is NOT ') + ' smooth, and' + (result.powerEfficient ? ...
...ficient.'; var ul = 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 ...
Node.insertBefore() - Web APIs
browser versions. Return value Returns the added child (unless newNode is a DocumentFragment, in which case the empty DocumentFragment is returned). ...
...gment is returned). ...
...It can be emulated by combining the insertBefore method with Node.nextSibling. In the previous example, sp1 could be inserted after sp2 using: parentDiv.insertBefore(sp1, sp2.nextSibling) If sp...
...serted after sp2 using: parentDiv.insertBefore(sp1, sp2.nextSibling) If sp2 does not have a next sibling, then it must be the last child -- sp2.nextSibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2). Example 3 Insert an element before the first child element, using the firstChild property. // Get the parent element let parentElement = document.
getElementById('parentElement') // Get the parent's first child let theFirstChild = parentElement.firstChild // Create a new element let newElement = document.createElement("div") // Insert the new element before the first child parentElement.insertBefore(newElement, theFirstChild) When the element does not have a first child, then firstChild is null. The element is still appended to the parent, after the l...
ParentNode.replaceChildren() - Web APIs
s, we give each of the buttons a click event handler, which collects together the selected options you want to transfer in one constant, and the existing options in the list you 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. ...
...ler, which collects together the selected options you want to transfer in one constant, and the existing options in the list you 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. ...
...ons you want to transfer in one constant, and the existing options in the list you 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. ...
... existing options in the list you 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. ...
RTCIceTransport: selectedcandidatepairchange event - Web APIs
Interface Event Event handler property onselectedcandidatepairchange Examples This example 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. ...
...ectedcandidatepairchange Examples This example 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 iceTransp...
...nge", 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. ...
...); 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. ...
Using the Screen Capture API - Web APIs
getDisplayMedia(); here, the cursor property is set to always, indicating that the mouse cursor should always be included in the captured media. Note: Some properties are not widely implemented and might not be used by the engine. cursor, for example, has limited support. Finally, event listeners are established to detect user clicks on the start and stop buttons. ...
...et to always, indicating that the mouse cursor should always be included in the captured media. Note: Some properties are not widely implemented and might not be used by the engine. cursor, for example, has limited support. Finally, event listeners are established to detect user clicks on the start and stop buttons. ...
...uld always be included in the captured media. Note: Some properties are not widely implemented and might not be used by the engine. cursor, for example, has limited support. Finally, event listeners are established to detect user clicks on the start and stop buttons. ...
...e: Some properties are not widely implemented and might not be used by the engine. cursor, for example, has limited support. Finally, event listeners are established to detect user clicks on the start and stop buttons. ...
Storage - Web APIs
n called setStyles() that grabs the data items using Storage.getItem() and uses those values to update page styles. If it doesn't, we run another function, populateStorage(), which uses Storage.setItem() to set the item values, then runs setStyles(). ...
... uses those values to update page styles. If it doesn't, we run another function, populateStorage(), which uses Storage.setItem() to set the item values, then runs setStyles(). ...
...function, populateStorage(), which uses Storage.setItem() to set the item values, then runs setStyles(). ...
...setItem('bgcolor', document.
getElementById('bgcolor').value); localStorage.setItem('font', document.
getElementById('font').value); localStorage.setItem('image', document.
getElementById('image').value); } function setStyles() { var currentColor = localStorage.getItem('bgcolor'); var currentFont = localStorage.getItem('font'); var currentImage = localStorage.getItem('image'); document.
getElementById('bgcolor').value = currentColor; document.
getElementById('font').value = currentFont; document.
getElementById('image').value = currentImage; htmlElem.style.backgroundColor = '#' + currentColor; pElem.style.fontFamily = currentFont; imgElem.setAttribute('src', currentImage); } Note: To see this running as a complete working example, see our Web Storage Demo. Specifications ...
A simple RTCDataChannel sample - Web APIs
eps of the connection process together; if you haven't already read up on this functionality of ECMAScript 2015, you should read up on them. Similarly, this example uses arrow functions to simplify syntax. Starting up When the script is run, we set up an load event listener, so that once the page is fully loaded, our startup() function is called. ...
...read up on this functionality of ECMAScript 2015, you should read up on them. Similarly, this example uses arrow functions to simplify syntax. Starting up When the script is run, we set up an load event listener, so that once the page is fully loaded, our startup() function is called. ...
... read up on them. Similarly, this example uses arrow functions to simplify syntax. Starting up When the script is run, we set up an load event listener, so that once the page is fully loaded, our startup() function is called. ...
...ons to simplify syntax. Starting up When the script is run, we set up an load event listener, so that once the page is fully loaded, our startup() function 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 n...
Taking still photos with WebRTC - Web APIs
n'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. ...
...am, 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. ...
...ate, 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. ...
...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. ...
Cross-browser audio basics - Developer guides
modern browsers. Manipulating the Audio Element with JavaScript In addition to being able to specify various attributes in HTML, the <audio> element comes complete with several properties and methods that you can manipulate via JavaScript. Given the following HTML: <audio id="my-audio" src="audiofile.mp3"> ... </audio> You can grab the <audio> element like this: var myAudio = document.
getElementById('my-audio'); Alternatively, you can create a new element. Here's an example of creating an <audio> element, setting the media to play, playing and pausing, and then playing from 5 seconds into the audio: var myAudio = document.createElement('audio'); if (myAudio.canPlayType('audio/mpeg')) { myAudio.setAttribute('src','audiofile.mp3'); } if (myAudio.canPlayType('audio/ogg')) { myAudio.setA...
...le.ogg" type="audio/ogg"> <!-- place fallback here as <audio> supporting browsers will ignore it --> <p>Download<a href="audiofile.mp3">audiofile.mp3</a></p> </audio> <!-- custom play and pause buttons --> <button id="play">play</button> <button id="pause">pause</button> Next, we attach some functionality to the player using JavaScript: window.onload = function(){ var myAudio = document.
getElementById('my-audio'); var play = document.
getElementById('play'); var pause = document.
getElementById('pause'); // associate functions with the 'onclick' events play.onclick = playAudio; pause.onclick = pauseAudio; function playAudio() { myAudio.play(); } function pauseAudio() { myAudio.pause(); } } Media loading events Above we have shown how you can create a very simple a...
...ause" style="display:none" >pause</button> </div> <div id="progress"> <div id="bar"></div> </div> Styled like so: #controls { width: 80px; float: left; } #progress { margin-left: 80px; border: 1px solid black; } #bar { height: 20px; background-color: green; width: 0; } Now let's wire this thing up with JavaScript: window.onload = function(){ var myAudio = document.
getElementById('my-audio'); var play = document.
getElementById('play'); var pause = document.
getElementById('pause'); var loading = document.
getElementById('loading'); var bar = document.
getElementById('bar'); function displayControls() { loading.style.display = "none"; play.style.display = "block"; } // check that the media is ready before displaying the controls if (myAud...
...navigate the audio using the progress bar. Fortunately this isn't too difficult to implement. ...
Media buffering, seeking, and time ranges - Developer guides
ns a TimeRanges object, which will tell us which chunks of media have been downloaded. This is usually contiguous but if the user jumps about while media is buffering, it may contain holes. This will work with <audio> or <video>; for now let's consider a simple audio example: <audio id="my-audio" controls src="music.mp3"> </audio> We can access these attributes like so: var myAudio = document.
getElementById('my-audio'); var bufferedTimeRanges = myAudio.buffered; TimeRanges Object TimeRanges are a series of non-overlapping ranges of time, with start and stop times. (learn more about TimeRanges). A TimeRanges Object consists of the following properties: length: The number of time ranges in the object. start(index): The start time, in seconds, of a time range. end(index): The end time, in seco...
.../ returns 15 myAudio.buffered.end(1); // returns 19 To try out and visualize buffered time ranges we can write a little bit of HTML: <p> <audio id="my-audio" controls> <source src="music.mp3" type="audio/mpeg"> </audio> </p> <p> <canvas id="my-canvas" width="300" height="20"> </canvas> </p> and a little bit of JavaScript: window.onload = function(){ var myAudio = document.
getElementById('my-audio'); var myCanvas = document.
getElementById('my-canvas'); var context = myCanvas.getContext('2d'); context.fillStyle = 'lightgray'; context.fillRect(0, 0, myCanvas.width, myCanvas.height); context.fillStyle = 'red'; context.strokeStyle = 'white'; var inc = myCanvas.width / myAudio.duration; // display TimeRanges myAudio.addEventListener('seeked', fu...
...300px; } #buffered-amount { display: block; height: 100%; background-color: #777; width: 0; } .progress { margin-top: -20px; height: 20px; position: relative; width: 300px; } #progress-amount { display: block; height: 100%; background-color: #595; width: 0; } And the following JavaScript provides our functionality: window.onload = function(){ var myAudio = document.
getElementById('my-audio'); myAudio.addEventListener('progress', function() { var duration = myAudio.duration; if (duration > 0) { for (var i = 0; i < myAudio.buffered.length; i++) { if (myAudio.buffered.start(myAudio.buffered.length - 1 - i) < myAudio.currentTime) { document.
getElementById("buffered-amount").style.width = (myAudio.buffered.end(myAudio.buffered.leng...
...Audio.buffered.length - 1 - i) < myAudio.currentTime) { document.
getElementById("buffered-amount").style.width = (myAudio.buffered.end(myAudio.buffered.length - 1 - i) / duration) * 100 + "%"; break; } } } }); myAudio.addEventListener('timeupdate', function() { var duration = myAudio.duration; if (duration > 0) { document.
getElementById('progress-amount').style.width = ((myAudio.currentTime / duration)*100) + "%"; } }); } The progress event is fired as data is downloaded, this is a good event to react to if we want to display download or buffering progress. The timeupdate event is fired 4 times a second as the media plays and that's where we increment our playing progress bar. This should give you results similar to the...
Creating a cross-browser video player - Developer guides
ethod, which any supported HTML5 <video> element should. var supportsVideo = !!document.createElement('video').canPlayType; if (supportsVideo) { // set up custom controls // ... } Once it has been confirmed that the browser does indeed support HTML5 video, it's time to set up the custom controls. ...
.... var supportsVideo = !!document.createElement('video').canPlayType; if (supportsVideo) { // set up custom controls // ... } Once it has been confirmed that the browser does indeed support HTML5 video, it's time to set up the custom controls. ...
...').canPlayType; if (supportsVideo) { // set up custom controls // ... } Once it has been confirmed that the browser does indeed support HTML5 video, it's time to set up the custom controls. ...
...etElementById('video-controls'); As mentioned earlier, the browser's default controls now need to be disabled, and the custom controls need to be displayed: // Hide the default controls video.controls = false; // Display the user defined video controls videoControls.style.display = 'block'; With that done, a variable pointing to each of the buttons is now required: var playpause = document.
getElementById('playpause'); var stop = document.
getElementById('stop'); var mute = document.
getElementById('mute'); var volinc = document.
getElementById('volinc'); var voldec = document.
getElementById('voldec'); var progress = document.
getElementById('progress'); var progressBar = document.
getElementById('progress-bar'); var fullscreen = document.
getElementById('fs'); Using these handles, events can now be a...
TypeError: "x" is not a function - JavaScript
In this example, Array.prototype.map() is used, which will work with Array objects only. let obj = {a...
...In this example, Array.prototype.map() is used, which will work with Array objects only. let obj = {a: 13, b: 37, c: 42}; obj.map(function(num) { ...
...In this example, Array.prototype.map() is used, which will work with Array objects only. let obj = {a: 13, b: 37, c: 42}; obj.map(function(num) { return num * 2; }); // TypeError: obj.map is not a function ...
...In this example, Array.prototype.map() is used, which will work with Array objects only. let obj = {a: 13, b: 37, c: 42}; obj.map(function(num) { return num * 2; }); // TypeError: obj.map is not a function Use an array instead: let numbers...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
ns -- they can work without push, but are 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 act...
... Now let's move to the subscription part -- the app first sends the subscription details as JSON to the server using Fetch. ...
...iption details as JSON to the server using Fetch. ...
... method: 'post', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ subscription: subscription }), }); Then the GlobalEventHandlers.onclick function on the Subscribe button is defined: document.
getElementById('doIt').onclick = function() { const payload = document.
getElementById('notification-payload').value; const delay = document.
getElementById('notification-delay').value; const ttl = document.
getElementById('notification-ttl').value; fetch('./sendNotification', { method: 'post', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ subscription: subscription, payload: payload, delay: delay, ttl: ttl, }), })...
textLength - SVG: Scalable Vector Graphics
idthDisplay"></span> </div> The <input> element, of type "range", is used to create the slider control the user will manipulate to change the width of the text. A <span> element of ID "widthDisplay" is provided to display the current width value. JavaScript Finally, let's have a look at the JavaScript code. ...
..., of type "range", is used to create the slider control the user will manipulate to change the width of the text. A <span> element of ID "widthDisplay" is provided to display the current width value. JavaScript Finally, let's have a look at the JavaScript code. ...
...ser will manipulate to change the width of the text. A <span> element of ID "widthDisplay" is provided to display the current width value. JavaScript Finally, let's have a look at the JavaScript code. ...
... element of ID "widthDisplay" is provided to display the current width value. JavaScript Finally, let's have a look at the JavaScript code. ...
Using templates and slots - Web Components
ern browsers). This element and its contents are not rendered in the DOM, but it can still be referenced using JavaScript. Let's look at a trivial quick example: <template id="my-paragraph"> <p>My paragraph</p> </template> This won't appear in your page until you grab a reference to it with JavaScript and then append it to the DOM, using something like the following: let template = document.
getElementById('my-paragraph'); let templateContent = template.content; document.body.appendChild(templateContent); Although trivial, you can already start to see how this could be useful. Using templates with web components Templates are useful on their own, but they work even better with web components. Let's define a web component that uses our template as the content of its shadow DOM. We'll call it <my-...
...see how this could be useful. Using templates with web components Templates are useful on their own, but they work even better with web components. Let's define a web component that uses our template as the content of its shadow DOM. We'll call it <my-paragraph>: customElements.define('my-paragraph', class extends HTMLElement { constructor() { super(); let template = document.
getElementById('my-paragraph'); let templateContent = template.content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(templateContent.cloneNode(true)); } } ); The key point to note here is that we append a clone of the template content to the shadow root, created using the Node.cloneNode() method. And because we are appending its contents to a shadow DOM, we can ...
... custom element named <element-details> and use Element.attachShadow to attach to it, as its shadow root, that document fragment we created with our <template> element above. This uses exactly the same pattern as we saw in our earlier trivial example. ...
...echanism for holding client- side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.</span> </element-details> <script> customElements.define('element-details', class extends HTMLElement { constructor() { super(); const template = document .
getElementById('element-details-template') .content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(template.cloneNode(true)); } }) </script> </body> </html> ...
Cross-domain Content Scripts - Archive of obsolete content
Cross-domain XMLHttpR...
... Cross-domain XMLHttpRequest The following add-on creates a panel whose content is the summary weather forec...
.../ panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=YOUR-API-KEY"; self.port.on("show", function () { var request = new XMLHttpRequest(); request.open("GET", url, true); request.onload = function () { var jsonResponse = JSON.parse(request.responseText); var summary = getSummary(jsonResponse); var element = document.
getElementById("forecast_summary"); element.textContent = summary; }; request.send(); }); function getSummary(forecast) { return forecast.RegionalFcst.FcstPeriods.Period[0].Paragraph[0].$; } Finally, we need to add the "cross-domain-content" key to "package.json": "permissions": { "cross-domain-content": ["http://datapoint.metoffice.gov.uk"] } Content Permissions and unsafeWindow If you use "...
dev/panel - Archive of obsolete content
y-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/heritage"); const MyPanel = Class({ extends: Panel, label: "My Panel",...
... }, dispose: function() { this.debuggee = null; }, onReady: function() { this.debuggee.start(); this.postMessage("port", [this.debuggee]); } }); // export the constructor exports.MyPanel = MyPanel; // create a new tool, initialized // with the new constructor const myTool = new Tool({ panels: { myPanel: MyPanel } }); In my-panel.js: // my-panel.js var content = document.
getElementById("content"); window.addEventListener("message", function(event) { var debuggee = event.ports[0]; console.log(debuggee); debuggee.onmessage = function(event) { content.textContent = JSON.stringify(event.data); } debuggee.postMessage({ "to":"root", "type":"listTabs" }); }); If you do this, don't forget to call start() on the port before passing it over to the panel docum...
... then(listTabs). then(writeTabList); }); function listTabs(root) { return root.listTabs(); } function writeTabList(tabList) { content.textContent = tabList.tabs[tabList.selected].url; } We don't have detailed documentation for volcan.js, but it's coming soon...
Canvas code snippets - Archive of obsolete content
canvas, x, y) { var cx = canvas.getContext('2d'); var pixel = cx.getImageData(x, y, 1, 1); return { r: pixel.data[0], g: pixel.data[1], b: pixel.data[2], a: pixel.data[3] }; } Chaining methods This class provides jQuery-style chained access to 2D context methods and properties. ...
...ethods) { let method = m; Canvas2DContext.prototype[method] = function() { return this.ctx[method].apply(this.ctx, arguments); }; } for (let p of props) { let prop = p; Canvas2DContext.prototype[prop] = function(value) { if (value === undefined) return this.ctx[prop]; this.ctx[prop] = value; return this; }; } }; var canvas = document.
getElementById('canvas'); // Use context to get access to underlying context var ctx = Canvas2DContext(canvas) .strokeStyle('rgb(30, 110, 210)') .transform(10, 3, 4, 5, 1, 0) .strokeRect(2, 10, 15, 20) .context; // Use property name as a function (but without arguments) to get the value var strokeStyle = Canvas2DContext(canvas) .strokeStyle('rgb(50, 110, 210)') .strokeStyle(); Code usable only f...
... iframe.src = this.url; // Here is where the magic happens... ...
HTML in XUL for rich tooltips - Archive of obsolete content
<html:div id="myHTMLTipDiv" type="content"/> </tooltip> </popupset> </overlay> Insert your version of the following into the JavaScript overlay. Our customized tooltipHTML attribute for each element can be set at any time. ...
...y> Insert your version of the following into the JavaScript overlay. Our customized tooltipHTML attribute for each element can be set at any time. ...
... document.
getElementById("htmltip2").setAttribute("tooltipHTML", "<font color='green'>green foo</font>") }, onMouseTooltip: function(event) { //get the HTML tooltip string assigned to the element that the mouse is over (which will soon launch the tooltip) var txt = event.target.getAttribute("tooltipHTML"); // get the HTML div element that is inside the custom XUL tooltip var div = document.
getElementById("myHTMLTipDiv"); //clear the HTML div element of any prior shown custom HTML while(div.firstChild) div.removeChild(div.firstChild); //safely convert HTML string to a simple DOM object, stripping it of JavaScript and more complex tags var injectHTML = Components.classes["@mozilla.org/feed-unescapehtml;1"] .getService(Components.interfaces.nsIScriptableUnescapeHTML) .parseFragment(txt, false, nu...
Tabbox - Archive of obsolete content
te. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. ...
...avoid using it. ...
... Examples: ...
Toolbar - Archive of obsolete content
/** * Installs the toolbar button with the given ID into the given * toolbar, if it is not already present in the document. * * @param {string} toolbarId The ID of the toolbar to install to. * @param {string} id The ID of the button to install. * @param {string} afterId The ID of the element to insert after. ...
...ID into the given * toolbar, if it is not already present in the document. * * @param {string} toolbarId The ID of the toolbar to install to. * @param {string} id The ID of the button to install. * @param {string} afterId The ID of the element to insert after. ...
...button to install. * @param {string} afterId The ID of the element to insert after. ...
XUL user interfaces - Archive of obsolete content
der: 1px inset -moz-dialog; margin: 4px; padding: 0px 4px; } #status { padding: 4px; } #status[warning] { color: red; } Make a new text file, script7.js. ...
...ding: 0px 4px; } #status { padding: 4px; } #status[warning] { color: red; } Make a new text file, script7.js. ...
... } #status[warning] { color: red; } Make a new text file, script7.js. ...
Using XML Data Islands in Mozilla - Archive of obsolete content
Here is a complete demo (al...
...<title>XML Data Block Demo</title> <script id="purchase-order" type="application/xml"> <purchaseOrder xmlns="http://example.mozilla.org/PurchaseOrderML"> <lineItem> <name>Line Item 1</name> <price>1.25</price> </lineItem> <lineItem> <name>Line Item 2</name> <price>2.48</price> </lineItem> </purchaseOrder> </script> <script> function runDemo() { var orderSource = document.
getElementById("purchase-order").textContent; var parser = new DOMParser(); var doc = parser.parseFromString(orderSource, "application/xml"); var lineItems = doc.getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "lineItem"); var firstPrice = lineItems[0].getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "price")[0].textContent; document.body.textContent = "The pur...
...ck-based way shown here works in Firefox, Opera, WebKit-based browsers such as Chrome and Safari, and IE9 while IE's XML data islands work only in IE. Here is another possible way, using the <object> tag. For this demo, you must create an external document called purchase_order.xml: <!DOCTYPE html> <html> <head> <title>XML Data Block Demo</title> <script> function runDemo() { var doc = document.
getElementById("purchase-order").contentDocument; var lineItems = doc.getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "lineItem"); var firstPrice = lineItems[0].getElementsByTagNameNS("http://example.mozilla.org/PurchaseOrderML", "price")[0].textContent; document.
getElementById("output-box").textContent = "The purchase order contains " + lineItems.length + " line items. The price of t...
jspage - Archive of obsolete content
b){if(Browser.Engine.trident&&b){["name","type","checked"].each(function(c){if(!b[c]){return;}a+=" "+c+'="'+b[c]+'"'; if(c!="checked"){delete b[c];}});a="<"+a+">";}return document.id(this.createElement(a)).set(b);},newTextNode:function(a){return this.createTextNode(a); },getDocument:function(){return this;},getWindow:function(){return this.window;},id:(function(){var a={string:function(d,c,b){d=b.
getElementById(d);return(d)?a.element(d,c):null; },element:function(b,e){$uid(b);if(!e&&!b.$family&&!(/^object|embed$/i).test(b.tagName)){var c=Element.Prototype;for(var d in c){b[d]=c[d];}}return b;},object:function(c,d,b){if(c.toElement){return a.element(c.toElement(b),d); }return null;}};a.textnode=a.whitespace=a.window=a.document=$arguments(0);return function(c,e,d){if(c&&c.$family&&c.uid){return c;}var b=$...
...nt:function(l,m){return j(this,"parentNode",null,l,false,m);},getParents:function(l,m){return j(this,"parentNode",null,l,true,m);},getSiblings:function(l,m){return this.getParent().getChildren(l,m).erase(this); },getChildren:function(l,m){return j(this,"nextSibling","firstChild",l,true,m);},getWindow:function(){return this.ownerDocument.window;},getDocument:function(){return this.ownerDocument; },
getElementById:function(o,n){var m=this.ownerDocument.
getElementById(o);if(!m){return null;}for(var l=m.parentNode;l!=this;l=l.parentNode){if(!l){return null; }}return document.id(m,n);},getSelected:function(){return new Elements($A(this.options).filter(function(l){return l.selected;}));},getComputedStyle:function(m){if(this.currentStyle){return this.currentStyle[m.camelCase()]; }var l=this.getDocument().defaul...
...f(!Selectors.Filters.byClass(f,g)){return false;}}}if(c.attributes){for(d=c.attributes.length; d--;d){var b=c.attributes[d];if(!Selectors.Filters.byAttribute(f,b.name,b.operator,b.value)){return false;}}}if(c.pseudos){for(d=c.pseudos.length;d--;d){var a=c.pseudos[d]; if(!Selectors.Filters.byPseudo(f,a.parser,a.argument,e)){return false;}}}return true;},getByTagAndID:function(b,a,d){if(d){var c=(b.
getElementById)?b.
getElementById(d,true):Element.
getElementById(b,d,true); return(c&&Selectors.Filters.byTag(c,a))?[c]:[];}else{return b.getElementsByTagName(a);}},search:function(o,h,t){var b=[];var c=h.trim().replace(Selectors.RegExps.splitter,function(k,j,i){b.push(j); return":)"+i;}).split(":)");var p,e,A;for(var z=0,v=c.length;z<v;z++){var y=c[z];if(z==0&&Selectors.RegExps.quick.test(y)){p=o.getElementsByT...
id - Archive of obsolete content
<< XUL Reference home id Type: unique id A unique identifier so that you can identify the element with. You can use this as a parameter to
getElementById() and other DOM functions and to reference the element in style sheets. ...
... << XUL Reference home id Type: unique id A unique identifier so that you can identify the element with. You can use this as a parameter to
getElementById() and other DOM functions and to reference the element in style sheets. ...
..."Click Me" oncommand="doSomething()"/> <script> function doSomething(){ var myButton = document.
getElementById('foo'); myButton.setAttribute('label','The button was pressed'); } </script> A more abstract version of the above would be a <button id="foo" label="Click Me" oncommand="setWidgetLabel(this, 'I was pressed')"/> <script> function setWidgetLabel(idName, newCaption){ document.
getElementById( idName.id ).setAttribute('label',newCaption) } </script> Not specifying the id attribute for a window or a prefwindow fills the console with the following warning message: Warning: Empty string passed to
getElementById() See also name ...
label - Archive of obsolete content
he element. If this is left out, no text appears. For an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. ...
...menulist.value property upon user selection of the menuitem. ...
...el" command="the-big-button"/> <button id="the-big-button" label="Click me" oncommand="alert(document.
getElementById('the-big-label').value)"/> <label id="myLabel" value="My label"/> <button label="Click me" oncommand="document.
getElementById('myLabel').setAttribute('value','Value changed');" /> <checkbox label="my Checkbox" id="myCheckboX"/> <button label="Another click" oncommand="document.
getElementById('myCheckboX').setAttribute('label','Still not checked');"/> <button label="Show label of checkbox" oncommand="alert( document.
getElementById('myCheckboX').getAttribute('label') )"/> ...
Dynamically modifying XUL-based user interface - Archive of obsolete content
nterface. In XUL applications JavaScript defines the behavior, using DOM APIs to access the XUL document. So what are the Document Object Model APIs? They are the 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? ...
...endChild(), createElement(), insertBefore(), and removeChild() DOM methods. Removing all children of an element This example removes all children of an element with id=someElement from the current document, by calling removeChild() method to remove the first child, until there are no children remaining. Note, that hasChildNodes() and firstChild are also part of the DOM API. var element = document.
getElementById("someElement"); while(element.hasChildNodes()){ element.removeChild(element.firstChild); } Inserting menu items to a menu This example adds two new menu items to a <menupopup>: to the start and to the end of it. It uses document.createElementNS() method to create the items, and insertBefore() with appendChild() to insert the created xml elements within the document. Note: document.c...
... node after all other nodes, while insertBefore() inserts the node before the node referenced by its second parameter. function createMenuItem(aLabel) { const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var item = document.createElementNS(XUL_NS, "menuitem"); // create a new XUL menuitem item.setAttribute("label", aLabel); return item; } var popup = document.
getElementById("myPopup"); // a <menupopup> element var first = createMenuItem("First item"); var last = createMenuItem("Last item"); popup.insertBefore(first, popup.firstChild); popup.appendChild(last); You can also use appendChild() and insertBefore() to move existing elements. For example you could move the item labeled "First item" to the end of popup by adding this statement as a last line to the snippet ...
Introduction to XUL - Archive of obsolete content
cript XUL can contain HTML content, including JavaScript. JavaScript functions may be added in a fashion similar to HTML. There is no <head> section of a XUL file, so script is just mixed in with the other content, delimited by a script element in the HTML namespace. <html:script type="application/javascript"> // dialog initialization code function InitWindow() { var checkbox = document.
getElementById("remember"); if (checkbox) checkbox.checked = true; } </html:script> JavaScript can be referenced as in HTML documents: as onClick handlers and the like. See individual widget documentation referenced at the index for a list of attributes accepting JavaScript values. JavaScript is most safely kept in a separate file and included in the XUL file <html:script language="javascript" s...
...odel, patterned after the HTML extensions. At this time these additional DOM methods are available, though the code is of course the most accurate place to look for this information. These interfaces can be found in the directory mozilla/rdf/content/public/idl. XULDocument XULDocument extends Document in a fashion similar to HTMLDocument's extension interface XULDocument : Document { Element
getElementById(in DOMString id); NodeList getElementsByAttribute(in DOMString name, in DOMString value); };
getElementById works like HTML's
getElementById. getElementsByAttribute returns a list of Elements for which the named attribute has the given value. A value of "*" is a wildcard signifying all elements with the attribute. XULElement XULElement extends Element. interface XULElement : Element { N...
... id="content-frame" src="contentframe.html" flex="100%"/> </window> The beginning of this example, down through the window tag, is the standard preamble. Notice that the example window tag has an id attached to it. Strictly speaking, that is unnecessary for this example. However in practice, most nodes in XUL have these identifiers, which enable the nodes to be retrieved easily using the AOM's
getElementById method. Identifiers are also useful for CSS, since rules can be applied to individual elements in XUL using the same # syntax that is possible for HTML elements. #main-window { display: block; width: 100%; height: 100%; } For example, the above style rule would apply to the main window and dictates that the window should consume the full width and height available to it in a content area...
Extensions - Archive of obsolete content
context menu. Showing and hiding context menu items To have a menuitem you 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. ...
...e, 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 ThumbnailsShowHideItems function will be called when the popup is about to be shown. This function retrieves the menuitem with the id ...
...k occured from within a frame. isTextSelected True if text is selected. ...
MenuModification - Archive of obsolete content
fying a Menu Menus have a number of methods which may be used to add and remove items. Adding Items to a Menu The appendItem method may be used to append a new item to the end of the popup associated with a menu. This method will create a new menuitem element and insert it into the popup. This method may only be used with the menu element. <script> function addToMenu() { var menu = document.
getElementById("edit-menu"); menu.appendItem("Insert", "insert"); } </script> <menu id="edit-menu"/> <button label="Add" oncommand="addToMenu()"/> In this example, the addToMenu function is called when the button is pressed. This function appends a new item to the menu's popup with the label Insert. The first argument to appendItem is the label of the menuitem, and the second argument is a value to associa...
...tem("Insert", "insert"); item.accessKey = "I"; Appending Submenus There is no built-in method to append submenus to a menu. To do this, we instead need to use the inherited node modification methods available for all elements. First, we need to retrieve the menupopup for the menu, and then use the appendChild method to append a new item. <script> function addSubMenu() { var popup = document.
getElementById("file-popup"); var newmenu = document.createElement("menu"); popup.appendChild(newmenu); newmenu.label = "New"; newmenu.appendItem("Document", "doc"); newmenu.appendItem("Image", "image"); } </script> <menu label="File" onpopupshowing="addSubMenu()"> <menupopup id="file-popup"/> </menu>. Comment: appendItem not working in TB 52.7.0. Workaround: add menupopup to menu. Then add menui...
...o want to make sure to remove the items again in a popuphiding event listener. Otherwise, a new submenu would be added every time the menu is opened, which is clearly not desirable. Another possibility is to ensure that the menu is only added once. The following shows how the addSubMenu function above might be rewritten to handle this case. <script> function addSubMenu() { var popup = document.
getElementById("file-popup"); if (popup.hasChildNodes()) return; var newmenu = document.createElement("menu"); popup.appendChild(newmenu); newmenu.label = "New"; newmenu.appendItem("Document", "doc"); newmenu.appendItem("Image", "image"); } </script> The hasChildNodes method may be used to check if a node has any children. The first time the function is called, the hasChildNodes method will r...
Sorting and filtering a custom tree view - Archive of obsolete content
this is useful if this is an editable table //to prevent the user from losing the row they edited var topVisibleRow = null; if (table) { topVisibleRow = getTopVisibleRow(); } if (data == null) { //put object loading code here. for ou...
...for strings, lowercases them function prepareForComparison(o) { if (typeof o == "string") { return o.toLowerCase(); } return o; } function getTopVisibleRow() { return tree.treeBoxObject.getFirstVisibleRow(); } function setTopVisibleRow(topVisible...
... { return o.toLowerCase(); } return o; } function getTopVisibleRow() { return tree.treeBoxObject.getFirstVisibleRow(); } function setTopVisibleRow(topVisibleRow) { return tree.treeBoxObject.scrollToRow(topVisibleRow); } function inputFilter(event) { //do this now rather than doing it at every comparison var value = prepareForComparison(event.target.value); setFilter(value); document.
getElementById("clearFilter").disabled = value.length == 0; } function clearFilter() { document.
getElementById("clearFilter").disabled = true; var filterElement = document.
getElementById("filter"); filterElement.focus(); filterElement.value = ""; setFilter(""); } function setFilter(text) { filterText = text; loadTable(); } ...
Filtering - Archive of obsolete content
he template results should be filtered based on that value. This can be done by modifying the DOM nodes inside the query and rebuilding the template. For instance, to apply a filter, you might add a new <triple> element. To remove the filter, the <triple> should be removed again. Let's assume that we've given an id of 'cond' to the query tag. ...
...that value. This can be done by modifying the DOM nodes inside the query and rebuilding the template. For instance, to apply a filter, you might add a new <triple> element. To remove the filter, the <triple> should be removed again. Let's assume that we've given an id of 'cond' to the query tag. ...
...If this is set, we add a filter, otherwise we remove it. The code is fairly straightforward. A new <triple> element is created and the object attribute is set to the value to filter by. For example, the resulting triple for the Netherlands might be: <triple subject="?photo" ...
Box Objects - Archive of obsolete content
This means that while both hidden and collapsed elements have 0 width and height, hidden elements have a x and y position of 0, while collapsed elements will retain their position in the window. To retrive or modify the hidden or collapsed state use the corresponding properties as in the following example. ...
...ate use the corresponding properties as in the following example. ...
...ipt> function showPositionAndSize() { var labelbox = document.
getElementById('thelabel').boxObject; alert("Position is (" + labelbox.x + "," + labelbox.y + ") and size is (" + labelbox.width + "," + labelbox.height + ")"); } </script> <button label="Hide" oncommand="document.
getElementById('thelabel').hidden = true;"/> <button label="Show" oncommand="document.
getElementById('thelabel').hidden = false;"/> <button label="Collapse" oncommand="document.
getElementById('thelabel').collapsed = true;"/> <button label="Uncollapse" oncommand="document.
getElementById('thelabel').collapsed = false;"/> <button label="Show Position/Size" oncommand="showPositionAndSize();"/> <label id="thelabel" value="I am a label"/> Note that if you hide and collapse the...
Commands - Archive of obsolete content
d menu items hooked up to it will be disabled automatically. If you re-enable the command, the buttons will become enabled again. Example: Toggling command disabled Example 2 : Source View <command id="cmd_openhelp" oncommand="alert('Help');"/> <button label="Help" command="cmd_openhelp"/> <button label="More Help" command="cmd_openhelp"/> <button label="Disable" oncommand="document.
getElementById('cmd_openhelp').setAttribute('disabled','true');"/> <button label="Enable" oncommand="document.
getElementById('cmd_openhelp').removeAttribute('disabled');"/> In this example, both buttons use the same command. When the Disable button is pressed, the command is disabled by setting its disabled attribute, and both buttons will be disabled as well. It is normal to put a group of commands ...
... row. (See Discussion about opening this example). The example below isn't completely polished. Really, we should ensure that the selection and focus is adjusted appropriately after a deletion. ...
...thod which inserts a controller into an element before other ones. This might be useful to override commands. For example, the following example will disable pasting into a textbox. var tboxController = { supportsCommand : function(cmd){ return (cmd == "cmd_paste"); }, isCommandEnabled : function(cmd){ return false; }, doCommand : function(cmd){ }, onEvent : function(evt){ } }; document.
getElementById("tbox").controllers.insertControllerAt(0,tboxController); In this example, we insert the controller at index 0, which means before any others. The new controller supports the 'cmd_paste' command and always indicates that the command is disabled. The default textbox controller never gets called because the command dispatcher found the controller above to handle the command first. Next, we'll fi...
Focus and Selection - Archive of obsolete content
om an element. You can respond to focus changes by adding an onfocus or onblur attribute on an element. They work just like their HTML counterparts. You might use these event handlers to highlight the element or display text on a status bar. The following example can be used to apply a function to handle a focus event. Example 2 : Source View <script> function displayFocus(){ var elem=document.
getElementById('sbar'); elem.setAttribute('value','Enter your phone number.'); } </script> <textbox id="tbox1"/> <textbox id="tbox2" onfocus="displayFocus();"/> <description id="sbar" value=""/> The focus event, when it occurs, will call the displayFocus function. This function will change the value of the text label. We could extend this example to remove the text when the blur event occurs. Typically, yo...
... property. The example below shows this. Example 3 : Source View <window id="focus-example" title="Focus Example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init(){ addEventListener("focus",setFocusedElement,true); } function setFocusedElement(){ var focused = document.commandDispatcher.focusedElement; 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 n...
...ected to ever be focused. Changing the focus There are several ways to change the currently focused element. The simplest is to call the focus method of a the XUL element that you wish to set the focus to. The blur method can be used to remove the focus from an element. The following example demonstrates this: Example 5 : Source View <textbox id="addr"/> <button label="Focus" oncommand="document.
getElementById('addr').focus()"/> Or, you can use the methods advanceFocus and rewindFocus on the command dispatcher. These methods move the focus to the next element in sequence or the previous element respectively. This is what happens when the user presses TAB or Shift+Tab. For textboxes, a special attribute, focused is added whenever the element has the focus. You can check for the presence of this attribu...
Using the Editor from XUL - Archive of obsolete content
nction to get executed when the XUL is done loading. The XUL contains an <editor> tag, e.g.: <editor type="content-primary" id="content-frame" src="about:blank" flex="1"/> The attribute type="content-primary" identifies this as the window content element, i.e. that which you get from window._content. Having an id attribute, id="content-frame", allows us to find this element with document.
getElementById("content-frame"), and to style it from CSS. EditorOnLoad() is called. It does some getting of window.arguments (which is a way callers can pass parameters to new windows -- we use this to get the URL to be loaded), then it calls EditorStartup(), where the real work happens. It passes two parameters; the first indicates whether we want a plain text or HTML editor (pass text or html here),...
...rguments (which is a way callers can pass parameters to new windows -- we use this to get the URL to be loaded), then it calls EditorStartup(), where the real work happens. It passes two parameters; the first indicates whether we want a plain text or HTML editor (pass text or html here), and the second is the <iframe> element on which we wish to create the editor. We could either pass document.
getElementById("content-frame") or window._content here. The important stuff in EditorStartup() begins where we get or create an editorShell. The <editor> tag actually creates an nsEditorBoxObject behind the scenes. The nsEditorBoxObject creates an nsEditorShell, and holds the owning reference to it. Through the magic of XBL, the XUL bindings, and the nsIEditorBoxObject interface, you can get a JavaScript...
...s of setup before finally kicking off the URL load, which the most important part here. When the XUL was parsed, the src attribute on the content frame was set to about:blank (our default 'blank page' URL). We can't set that before XUL parsing, so we have to force a load of the page we now want to edit. We get the URL to load from the args element, then kick off the load: var url = document.
getElementById("args").getAttribute("value"); editorShell.LoadUrl(url); Loading the document in the <iframe> of course happens asynchronously, so we need to know when we have a document that we can start editing. nsEditorShell is able to observe the document load on the <iframe>, because it implements nsIDocumentLoaderObserver, and registered itself as a doc loader when it was assigned the content window.
Client-side form validation - Learn web development
how to do this. We'll start with some simple HTML (feel free to put this in a blank HTML file; use a fresh copy of fruit-start.html as a basis, if you like): <form> <label for="mail">I would like you to provide me with an e-mail address:</label> <input type="email" id="mail" name="mail"> <button>Submit</button> </form> And add the following JavaScript to the page: const email = document.
getElementById("mail"); email.addEventListener("input", function (event) { if (email.validity.typeMismatch) { email.setCustomValidity("I am expecting an e-mail address!"); } else { email.setCustomValidity(""); } }); Here we store a reference to the email input, then add an event listener to it that runs the contained code each time the value inside the input is changed. Inside the contained cod...
...px; box-sizing: border-box; } .error.active { padding: 0.3em; } Now lets look at the JavaScript 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 cont...
...padding: 0; font-size: 80%; color: white; background-color: #900; border-radius: 0 0 5px 5px; box-sizing: border-box; } .error.active { padding: 0.3em; } The big changes are in the JavaScript code, which needs to do much more heavy lifting. // There are fewer ways to pick a DOM node with legacy browsers const form = document.getElementsByTagName('form')[0]; const email = document.
getElementById('mail'); // The following is a trick to reach the next sibling Element 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-...
Advanced text formatting - Learn web development
t brown color.</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); const output = document.querySelector('.output'); const code = textarea.value; const userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solution...
...hinking.)</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); const output = document.querySelector('.output'); const code = textarea.value; const userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solution...
...ing work.</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); const output = document.querySelector('.output'); const code = textarea.value; const userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solution...
Getting started with HTML - Learn web development
v class="controls"> <input id="reset" type="button" value="Reset" /> <input id="solution" type="button" value="Show solution" /> </div> html { font-family: 'Open Sans Light',Helvetica,Arial,sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.
getElementById('code'); var reset = document.
getElementById('reset'); var solution = document.
getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = ht...
...site.</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.
getElementById('code'); var reset = document.
getElementById('reset'); var solution = document.
getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = ht...
...buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h1 { color: blue; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } img { max-width: 100%; } 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 = ht...
Useful string methods - Learn web development
Item); } } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCod...
...listItem); } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCod...
...istItem); } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCod...
Getting started with React - Learn web development
ilable to other modules. Interrogating the index Let's open src/index.js, because that's where the App component is being used. This file is the entry point for our app, and it initially looks like this: import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.
getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); As with App.js, the file starts by importing all the JS modules and other assets it needs to run. src/index.css holds global styles that are applied to ou...
...pieces of code that help application performance and allow features of your web applications to work offline, but they're not in scope for this article. You can delete line 5, as well as lines 9 through 12. Your final index.js file should look like this: import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; ReactDOM.render(<App />, document.
getElementById('root')); Variables and props Next, we'll use a few of our JavaScript skills to get a bit more comfortable editing components and working with data in React. We'll talk about how variables are used inside JSX, and introduce props, which are a way of passing data into a component (which can then be accessed using variables). Variables in JSX Back in App.js, let's focus on line 9: <img src={lo...
... is any data passed into a React component. Props are written inside component calls, and use the same syntax as HTML attributes -- prop="value". Let's open index.js and give our <App/> call its first prop. Add a prop of subject to the <App/> component call, with a value of Clarice. When you are done, your code should look something like this: ReactDOM.render(<App subject="Clarice" />, document.
getElementById('root')); Back in App.js, let's revisit the App function itself, which reads like this (with the return statement shortened for brevity): function App() { const subject = "React"; return ( // return statement ); } Change the signature of the App function so that it accepts props as a parameter, and delete the subject const. Just like any other function parameter, you can put props in...
Components.utils.exportFunction
Xray filtering and waiving Xrays provide a filtered view ...
...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 ex...
...This prevents passing cross-origin objects (like Window or Location) to privileged functions, since the privileged code will have full access to those o...
Working with windows in chrome code
peaking, it implements a number of interfaces, including nsIDOMJSWindow and nsIDOMWindow, but it also contains the user-defined properties for global variables and functions of the window. So, for example, to access the DOM document corresponding to the window, you can use win.document. Note however, that the open() call returns before the window is fully loaded, so some calls, like win.document.
getElementById() will fail. To overcome this difficulty, you can move the initialization code to a load handler of the window being opened or pass a callback function, as described below. You can get a Window object from a document using document.defaultView. Content windows When a XUL window contains a widget capable of displaying a page, such as <browser> or <iframe>, the document in that widget is, natura...
...ess the web page in the selected tab in a Firefox window. Some examples use _content instead of content. The former has been deprecated for a while, and you should use content in the new code. Accessing a document in the sidebar Firefox has a sidebar, which is implemented as a <browser> element with id="sidebar". To access the elements and variables inside the sidebar, you need to use document.
getElementById("sidebar").contentDocument or .contentWindow, like when Accessing content documents. For more sidebar tips, see Code snippets:Sidebar. Accessing the elements of the top-level document from a child window The opposite case is when you want to access the chrome document from a privileged script loaded in a <browser> or an <iframe>. A typical case when this can be useful is when your code runs i...
..., {status: "Reading remote data", maxProgress: 50, progress: 10} ); progress.xul: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window onload="onLoad();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script><![CDATA[ var gStatus, gProgressMeter; var maxProgress = 100; function onLoad() { gStatus = document.
getElementById("status"); gProgressMeter = document.
getElementById("progressmeter"); if("arguments" in window && window.arguments.length > 0) { maxProgress = window.arguments[0].maxProgress; setProgress(window.arguments[0].progress); setStatus(window.arguments[0].status); } } function setProgress(value) { gProgressMeter.value = 100 * value / maxProgress; } function setStatus(text) { gSt...
CanvasPattern.setTransform() - Web APIs
thod This is just a simple code snippet which uses the setTransform method to create a CanvasPattern with the specified pattern transformation from an SVGMatrix. The pattern gets applied if you set it as the current fillStyle and gets drawn onto the canvas when using the fillRect() method, for example. ...
...ate a CanvasPattern with the specified pattern transformation from an SVGMatrix. The pattern gets applied if you set it as the current fillStyle and gets drawn onto the canvas when using the fillRect() method, for example. ...
... </div> <textarea id="code" class="playable-code" style="height:120px"> var img = new Image(); img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createPattern(img, 'repeat'); pattern.setTransform(matrix.rotate(-45).scale(1.5)); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 400, 400); };</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; var svg1 = document.
getElementById('svg1'); var matrix = svg1.createSVGMatrix(); function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } re...
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
element The element to check whether it is focused or not. path A Path2D path to use. Examples Managing button focus This example draws two buttons on a canvas. The drawFocusIfNeeded() method is used to draw a focus ring when appropriate. ...
... Examples Managing button focus This example draws two buttons on a canvas. The drawFocusIfNeeded() method is used to draw a focus ring when appropriate. ...
...ws two buttons on a canvas. The drawFocusIfNeeded() method is used to draw a focus ring when appropriate. ...
CanvasRenderingContext2D.filter - Web APIs
f 100% means completely sepia. A value of 0% leaves the drawing unchanged. none No filter is applied. Initial value. Examples To view these examples, make sure to use a browser that supports this feature; see the compatibility table below. Applying a blur This example blurs a piece of text using the filter property. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.filter = 'blur(4px)'; ctx.font = '48px serif'; ctx.fillText('Hello world', 50, 100); Result Applying multiple filters You can combine as many filters as you like. This example 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" ...
...ext('Hello world', 50, 100); Result Applying multiple filters You can combine as many filters as you like. This example applies the contrast, sepia, and drop-shadow filters to a photo of a gecko. ...
... many filters as you like. This example 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.stroke() - Web APIs
on-zero winding rule, which means that path intersections will still get filled. Syntax void ctx.stroke(); void ctx.stroke(path); Parameters path A Path2D path to stroke. Examples A simple stroked rectangle This example creates a rectangle using the rect() method, and then draws it to the canvas using stroke(). HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.stroke(); Result Re-stroking paths Typically, you'll want to call beginPath() for each new thing you want to stroke. If you don't, the previous sub-paths will remain part of the current path, and get stroked every time you call the stroke() method. In some cases, however, this may be the desired effect. HTML <...
...ach new thing you want to stroke. If you don't, the previous sub-paths will remain part of the current path, and get stroked every time you call the stroke() method. In some cases, however, this may be the desired effect. HTML <canvas id="canvas"></canvas> JavaScript This code strokes the first path three times, the second path two times, and the third path only once. ...
..., 140); ctx.stroke(); Result Stroking and filling If you want to both stroke and fill a path, the order in which you perform these actions will determine the result. In this example, the square on the left is drawn with the stroke on top of the fill. The square on the right is drawn with the fill on top of the stroke. ...
Manipulating video using canvas - Web APIs
consists of three methods. Initializing the chroma-key player The doLoad() method is called when the XHTML document initially loads. This method's job is to prepare the variables needed by the chroma-key processing code, and to set up an event listener so we can detect when the user starts playing the video. ...
...roma-key player The doLoad() method is called when the XHTML document initially loads. This method's job is to prepare the variables needed by the chroma-key processing code, and to set up an event listener so we can detect when the user starts playing the video. ...
... This method's job is to prepare the variables needed by the chroma-key processing code, and to set up an event listener so we can detect when the user starts playing the video. ...
Document.getElementsByClassName() - Web APIs
the document. The element on which it is called will be used as the root of the search. Examples Get all elements that have a class of 'test': document.getElementsByClassName('test') Get all elements that have both the 'red' and 'test' classes: document.getElementsByClassName('red test') Get all elements that have a class of 'test', inside of an element that has the ID of 'main': document.
getElementById('main').getElementsByClassName('test') Get the first element with a class of 'test', or undefined if there is no matching element: document.getElementsByClassName('test')[0] We can also use methods of Array.prototype on any HTMLCollection by passing the HTMLCollection as the method's this value. Here we'll find all div elements that have a class of 'test': var testElements = document.getEleme...
...ments, function(testElement){ return testElement.nodeName === 'DIV'; }); Get the first element whose class is 'test' This is the most commonly used method of operation. ...
... Living Standard ...
Element: fullscreenchange event - Web APIs
t is currently in full-screen mode, 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.
...EventListener('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. ...
...ment) { 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. ...
Element.outerHTML - Web APIs
An attempt was made to set outerHTML using an HTML string which is not valid. NoModificationAllowedError An attempt was made to set outerHTML on an element which is a direct child of a Document, such as Document.documentElement. ...
... Notes If the element has no parent element, setting its outerHTML proper...
...iv> Javascript var d = document.
getElementById("d"); console.log(d.outerHTML); // The string '<div id="d"><p>Content</p><p>Further Elaborated</p></div>' // is written to the console window Replacing a node by setting the outerHTML property: HTML <div id="container"> <div id="d">This is a div.</div> </div> Javascript var container = document.
getElementById("container"); var d = document.
getElementById("d"); console.log(container.firstChild.nodeName); // logs "DIV" d.outerHTML = "<p>This paragraph replaced the original div.</p>"; console.log(container.firstChild.nodeName); // logs "P" // The #d div is no longer part of the document tree, // the new paragraph replaced it. Notes If the element has no parent element, setting its outerHTML property will not change it or its descendants. Many...
Element.setCapture() - Web APIs
nt mouse coordinates are drawn while you mouse around after clicking and holding down on an element. ...
...der: 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", mouseMoved, false); } function mouseMoved(e) { var output = docume...
...utput").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", mouseMoved, false); } function mouseMoved(e) { var output = document.
getElementById("output"); output.innerHTML = "Position: " + e.clientX + ", " + e.clientY; } </script> </head> <body onload="init()"> <p>This is an example of how to use mouse capture on elements in Gecko 2.0.</p> <p><a id="myButton" href="#">Test Me</a></p> <div id="output">No events yet</div> </body> </html> View Live Examples Notes The element may not be scrolled completely to the top or...
Using the Gamepad API - Web APIs
bles: The gamepadInfo paragraph that the connection info is written into, the ball that we want to move, the start variable that acts as the ID for requestAnimation Frame, the a and b variables that act as position modifiers for moving the ball, and the shorthand variables that will be used for the requestAnimationFrame() and cancelAnimationFrame() cross browser forks. var gamepadInfo = document.
getElementById("gamepad-info"); var ball = document.
getElementById("ball"); var start; var a = 0; var b = 0; Next we use the gamepadconnected event to check for a gamepad being connected. When one is connected, we grab the gamepad using Navigator.getGamepads()[0], print information about the gamepad into our gamepad info div, and fire the gameLoop() function that starts the whole ball movement process up. wi...
...; a.className = "axes"; for (var i = 0; i < gamepad.axes.length; i++) { var p = document.createElement("progress"); p.className = "axis"; //p.id = "a" + i; p.setAttribute("max", "2"); p.setAttribute("value", "1"); p.innerHTML = i; a.appendChild(p); } d.appendChild(a); // See https://github.com/luser/gamepadtest/blob/master/index.html var start = document.
getElementById("start"); if (start) { start.style.display = "none"; } document.body.appendChild(d); requestAnimationFrame(updateStatus); } function disconnecthandler(e) { removegamepad(e.gamepad); } function removegamepad(gamepad) { var d = document.
getElementById("controller" + gamepad.index); document.body.removeChild(d); delete controllers[gamepad.index]; } function updateStatus() { ...
...nnecthandler(e) { removegamepad(e.gamepad); } function removegamepad(gamepad) { var d = document.
getElementById("controller" + gamepad.index); document.body.removeChild(d); delete controllers[gamepad.index]; } function updateStatus() { if (!haveEvents) { scangamepads(); } var i = 0; var j; for (j in controllers) { var controller = controllers[j]; var d = document.
getElementById("controller" + j); var buttons = d.getElementsByClassName("button"); for (i = 0; i < controller.buttons.length; i++) { var b = buttons[i]; var val = controller.buttons[i]; var pressed = val == 1.0; if (typeof(val) == "object") { pressed = val.pressed; val = val.value; } var pct = Math.round(val * 100) + "%"; b.style.backgroundSiz...
GeolocationCoordinates.longitude - Web APIs
Greenwich meridian. This is the same standard used by the Global Positioning System (GPS). Examples In this simple example, we fetch the user'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. ...
...he Global Positioning System (GPS). Examples In this simple example, we fetch the user'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. ...
...his simple example, we fetch the user'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. ...
GlobalEventHandlers.onanimationiteration - Web APIs
s the box to migrate from the top-left corner of the container to the bottom-right corner. @keyframes slideBox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } JavaScript Some JavaScript code will need to be written to handle the click on the button to start the next iteration. Let's have a look. ...
... to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } JavaScript Some JavaScript code will need to be written to handle the click on the button to start the next iteration. Let's have a look. var box = document.
getElementById("box"); var iterationCounter = 0; box.onanimationiteration = function(event) { box.style.animationPlayState = "paused"; document.
getElementById("play").innerHTML = "Start Iteration #" + (iterationCounter+1); }; This sets up two global variables: box, which references the "box" element that we're animating, and iterationCounter, which is initially zero, which indicates how many iterations of the animation have occurred. The onanimationiteration event handler is then set up. It simply sets the box's animation-play-state to "paused", the...
...tes how many iterations 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 iterat...
GlobalEventHandlers.ondragend - Web APIs
etData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's border to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.
getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragE...
...d color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...visually indicate // the drag ended. ...
GlobalEventHandlers.ondragenter - Web APIs
etData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's border to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.
getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragE...
...d color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...visually indicate // the drag ended. ...
GlobalEventHandlers.ondragexit - Web APIs
etData("text", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's border to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.
getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragE...
...d color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's border back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...visually indicate // the drag ended. ...
GlobalEventHandlers.ondragleave - Web APIs
xt", ev.target.id); } function dragover_handler(ev) { console.log("dragOver"); // Change the target element's background color to signify a drag over event // has occurred ev.currentTarget.style.background = "lightblue"; ev.preventDefault(); } function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.
getElementById(data)); } function dragenter_handler(ev) { console.log("dragEnter"); // Change the source element's background color for enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's background color back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.
...r enter events ev.currentTarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragLeave"); // Change the source element's background color back to white ev.currentTarget.style.background = "white"; } function dragend_handler(ev) { console.log("dragEnd"); // Change the target element's background color to visually indicate // the drag ended. ...
...ndicate // the drag ended. ...
HTMLCanvasElement.mozGetAsFile() - Web APIs
dth="100" height="100"></canvas> <p><a href="#" id="link">Click here to try out mozGetAsFile()</a>.</p> JavaScript The following code uses mozGetAsFile() to create a File object from the canvas and appends it as an image to the page by loading it as a data URL using the readAsDataURL() method. Then a new <img> element is created using the new data URL. ...
...page by loading it as a data URL using the readAsDataURL() method. Then a new <img> element is created using the new data URL. ...
...the new data URL. function draw() { var canvas = document.
getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgb(200, 0, 0)'; ctx.fillRect(10, 10, 55, 50); ctx.fillStyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillRect(30, 30, 55, 50); var link = document.
getElementById('link'); link.addEventListener('click', copy); } function copy() { var canvas = document.
getElementById('canvas'); var f = canvas.mozGetAsFile('test.png'); var reader = new FileReader(); reader.readAsDataURL(f); reader.onloadend = function() { var newImg = document.createElement('img'); newImg.src = reader.result; document.body.appendChild(newImg); } } window.addEventListener('load', draw); Specifications Not part of any specification. ...
HTMLCanvasElement.toBlob() - Web APIs
file representing the canvas Once you have drawn content into a canvas, you can convert it into a file of any supported image format. The code snippet below, for example, takes the image in the <canvas> element whose ID is "canvas", obtains a copy of it as a PNG image, then appends a new <img> element to the document, whose source image is the one created using the canvas. ...
...b){...}, 'image/jpeg', 0.95); // JPEG at 95% quality A way to convert a canvas to an ico (Mozilla only) This uses -moz-parse to convert the canvas to ico. Windows XP doesn't support converting from PNG to ico, so it uses bmp instead. A download link is created by setting the download attribute. The value of the download attribute is the name it will use as the file name. ...
...f = window.URL.createObjectURL(b); } } canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon', '-moz-parse-options:format=bmp;bpp=32'); Save toBlob to disk with OS.File (chrome/add-on context only) This technique saves it to the desktop and is only useful in Firefox chrome context or add-on code as OS APIs are not present on web sites. var canvas = document.
getElementById('canvas'); var d = canvas.width; ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(d / 2, 0); ctx.lineTo(d, d); ctx.lineTo(0, d); ctx.closePath(); ctx.fillStyle = 'yellow'; ctx.fill(); function blobCallback(iconName) { return function(b) { var r = new FileReader(); r.onloadend = function () { // r.result contains the ArrayBuffer. Cu.import('resource://gre/modules/osfil...
HTMLElement.innerText - Web APIs
...
... Living Standard Introduced, based on the draft of the inne...
... Living Standard Introduced, based on the draft of the innerText specification. See whatwg/html#465 and whatwg/compat#5 for histo...
HTMLElement.offsetLeft - Web APIs
ndingClientRect() to get its position). Therefore, a box with the left, top, width and height of offsetLeft, offsetTop, offsetWidth and offsetHeight will not be a bounding box for a span with wrapped text. Syntax left = element.offsetLeft; left is an integer representing the offset to the left in pixels from the closest relatively positioned parent element. Example var colorTable = document.
getElementById("t1"); var tOLeft = colorTable.offsetLeft; if (tOLeft > 5) { // large left offset: do something here } This example shows a 'long' sentence that wraps within a div with a blue border, and a red box that one might think should describe the boundaries of the span. <div style="width: 300px; border-color:blue; border-style:solid; border-width:1;"> <span>Short span. </span> <span id="longs...
... describe the boundaries of the span. <div style="width: 300px; border-color:blue; border-style:solid; border-width:1;"> <span>Short span. ...
...le="width: 300px; border-color:blue; border-style:solid; border-width:1;"> <span>Short span. ...
HTMLFormElement.elements - Web APIs
nt way to get at the elements most important when processing forms. Example Quick syntax example In this example, we see how to obtain the list of form controls as well as how to access its members by index and by name or ID. ...
... <input type="password" name="password"> </form> var inputs = document.
getElementById("my-form").elements; var inputByIndex = inputs[0]; var inputByName = inputs["username"]; Accessing form controls This example gets the form's element list, then iterates over the list, looking for <input> elements of type "text" so that some form of processing can be performed on them. ...
...ents of type "text" so that some form of processing can be performed on them. var inputs = document.
getElementById("my-form").elements; // Iterate over the form controls for (i = 0; i < inputs.length; i++) { if (inputs[i].nodeName === "INPUT" && inputs[i].type === "text") { // Update text input inputs[i].value.toLocaleUpperCase(); } } Disabling form controls var inputs = document.
getElementById("my-form").elements; // Iterate over the form controls for (i = 0; i < inputs.length; i++) { // Disable all form controls inputs[i].setAttribute("disabled", ""); } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement.elements' in that specification. Living Standard Document Object Model (DOM) Level 2 HT...
HTMLInputElement.stepDown() - Web APIs
Try it with 0, 5, -2, etc. */ input.stepDown(); } } CSS input:...
...Try it with 0, 5, -2, etc. */ input.stepDown(); } } CSS input:invalid { border: red solid 3px; } Result Note if you don't pass a parameter to the stepDown() method, it defaults to 1. Any other value ...
...Try it with 0, 5, -2, etc. ...
HTMLInputElement.stepUp() - Web APIs
Try it with 0 */ input.stepUp() } } CSS input:invalid { border: red soli...
...Try it with 0 */ input.stepUp() } } CSS input:invalid { border: red solid 3px; } Result Note if you don't pass a parameter to the stepUp method, it defaults to 1. Any other value is a multiplier of the st...
... <input type="number" step="1" id="incrementer" min="0" max="25"> </label> </p> <input type="button" value="Increment" id="theButton"> JavaScript /* make the button call the function */ let button = document.
getElementById('theButton') button.addEventListener('click', function() { steponup() }) function steponup() { let input = document.
getElementById('theNumber') let val = document.
getElementById('incrementer').value if (val) { /* increment with a parameter */ input.stepUp(val) } else { /* or without a parameter. Try it with 0 */ input.stepUp() } } CSS input:invalid { border: red solid 3px; } Result Note if you don't pass a parameter to the stepUp method, it defaults to 1. Any other value is a multiplier of the step attribute value, which in this case is 5. If y...
HTMLElement.focus() - Web APIs
dicating whether or not the browser should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true, no scrolling will occur. ...
...s Focus on a text field JavaScript focusMethod = function getFocus() { document.
getElementById("myTextField").focus(); } HTML <input type="text" id="myTextField" value="Text field."> <p></p> <button type="button" onclick="focusMethod()">Click me to focus on the text field!</button> Result Focus on a button JavaScript focusMethod = function getFocus() { document.
getElementById("myButton").focus(); } HTML <button type="button" id="myButton">Click Me!</button> <p></p> <button type="button" onclick="focusMethod()">Click me to focus on the button!</button> Result Focus with focusOption JavaScript focusScrollMethod = function getFocus() { document.
getElementById("myButton").focus({preventScroll:false}); } focusNoScrollMethod = function getFocusWithoutS...
...utton type="button" id="myButton">Click Me!</button> <p></p> <button type="button" onclick="focusMethod()">Click me to focus on the button!</button> Result Focus with focusOption JavaScript focusScrollMethod = function getFocus() { document.
getElementById("myButton").focus({preventScroll:false}); } focusNoScrollMethod = function getFocusWithoutScrolling() { document.
getElementById("myButton").focus({preventScroll:true}); } HTML <button type="button" onclick="focusScrollMethod()">Click me to focus on the button!</button> <button type="button" onclick="focusNoScrollMethod()">Click me to focus on the button without scrolling!</button> <div id="container" style="height: 1000px; width: 1000px;"> <button type="button" id="myButton" style="margin-top: 500px;">Click Me!</but...
HTMLSelectElement.selectedOptions - Web APIs
tput"> </p> The <select> element is set to allow multiple items to be selected, and it is 7 rows tall. Note also the <button>, whose role it is to trigger fetching the HTMLCollection of selected elements using the selected property. ...
... multiple items to be selected, and it is 7 rows tall. Note also the <button>, whose role it is to trigger fetching the HTMLCollection of selected elements using the selected property. ...
...all. Note also the <button>, whose role it is to trigger fetching the HTMLCollection of selected elements using the selected property. ...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
string, then will presumably decode it and process the messages it finds in the resulting array. Examples Simple microtask example In this simple example, we see that enqueueing a microtask causes the microtask's callback to run after the body of this top-level script is done running. HTML <pre id="log"> </pre> JavaScript The code below is used to log the output. let logElem = document.
getElementById("log"); let log = s => logElem.innerHTML += s + "<br>"; In the following code, we see a call to queueMicrotask() used to schedule a microtask to run. This call is bracketed by calls to log(), a custom function that simply outputs text to the screen. log("Before enqueueing the microtask"); queueMicrotask(() => { log("The microtask has run.") }); log("After enqueueing the microtask"); Result ...
...imeout and microtask example In this example, a timeout is scheduled to fire after zero milliseconds (or "as soon as possible"). This demonstrates the difference between what "as soon as possible" means when scheduling a new task (such as by using setTimeout()) versus using a microtask. HTML <pre id="log"> </pre> JavaScript The code below is used to log the output. let logElem = document.
getElementById("log"); let log = s => logElem.innerHTML += s + "<br>"; In the following code, we see a call to queueMicrotask() used to schedule a microtask to run. This call is bracketed by calls to log(), a custom function that simply outputs text to the screen. The code below schedules a timeout to occur in zero milliseconds, then enqueues a microtask. This is bracketed by calls to log() to output additio...
...ample expands slightly on the previous one by adding a function that does some work. This function uses queueMicrotask() to schedule a microtask. The important thing to take away from this one is that the microtask isn't processed when the function exits, but when the main program exits. HTML <pre id="log"> </pre> JavaScript The code below is used to log the output. let logElem = document.
getElementById("log"); let log = s => logElem.innerHTML += s + "<br>"; The main program code follows. The doWork() function here calls queueMicrotask(), yet the microtask still doesn't fire until the entire program exits, since that's when the task exits and there's nothing else on the execution stack. let callback = () => log("Regular timeout callback has run"); let urgentCallback = () => log("*** Oh noes!
The HTML DOM API - Web APIs
CloseEvent WebSocket Server-sent events interfaces The EventSource interface represents the source which sent or is sending server-sent events. EventSource Examples In this example, an <input> element's input event is monitored in order to update the state of a form's "submit" button based on whether or not a given field currently has a value. ...
... The EventSource interface represents the source which sent or is sending server-sent events. EventSource Examples In this example, an <input> element's input event is monitored in order to update the state 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 ...
HTML Drag and Drop API - Web APIs
Each data item is a s...
...ws how to use those attributes, and includes basic event handlers for each attribute. <script> function dragover_handler(ev) { ev.preventDefault(); ev.dataTransfer.dropEffect = "move"; } function drop_handler(ev) { ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM const data = ev.dataTransfer.getData("text/plain"); ev.target.appendChild(document.
getElementById(data)); } </script> <p id="target" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">Drop Zone</p> Note that each handler calls preventDefault() to prevent additional event processing for this event (such as touch events or pointer events). For more information, see: Specifying Drop Targets Handle the drop effect The handler for the drop event is free to process the drag...
...fer.setData("application/my-app", ev.target.id); ev.dataTransfer.dropEffect = "move"; } function dragover_handler(ev) { ev.preventDefault(); ev.dataTransfer.dropEffect = "move" } function drop_handler(ev) { ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM const data = ev.dataTransfer.getData("application/my-app"); ev.target.appendChild(document.
getElementById(data)); } </script> <p id="p1" draggable="true" ondragstart="dragstart_handler(event)">This element is draggable.</p> <div id="target" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">Drop Zone</div> For more information, see: Performing a Drop Drag end At the end of a drag operation, the dragend event fires at the source element -- the element that was the target of the...
MouseEvent.relatedTarget - Web APIs
and blue boxes. ...
...event.relatedTarget.id : "unknown"; mouseoutLog.innerText = `\nfrom ${event.ta...
...event.relatedTarget.id : "unknown"; mouseoutLog.innerText = `\nfrom ${event.target.id} into ${related} ${mouseoutLog.innerT...
Using the Payment Request API - Web APIs
ting availability of the Payment Request API You can effectively detect support for the Payment Request API by checking if the user's browser supports PaymentRequest, i.e. if (window.PaymentRequest). 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 ...
...request button depending on whether users can make payments. In the following snippet we do just this -- depending on whether the user can make a fast payment or needs to add payment credentials first, the title of the checkout button changes between "Fast Checkout with W3C" and "Setup W3C Checkout". In both cases, the checkout button calls PaymentRequest.show(). ...
...(e.g., additional delivery instructions), the merchant can show a page with additional <input type="text"> fields after the checkout. request.show() .then(function(paymentResponse) { // Process payment here. // Close the UI: paymentResponse.complete('success').then(function() { // Request additional shipping address details. const additionalDetailsContainer = document.
getElementById('additional-details-container'); additionalDetailsContainer.style.display = 'block'; window.scrollto(additionalDetailsContainer.getBoundingClientRect().x, 0); }).catch(function(error) { // Handle error. }); }) .catch(function(error) { // Handle error. }); Note: See our Show additional user interface after successful payment demo for the full code. Pre-auth...
Range.extractContents() - Web APIs
ct one or more item, and then click "swap" to move them to the opposite container. ...
...ve them to the opposite container. ...
...list1">123456</p> <button id="swap">Swap selected item(s)</button> <p id="list2">abcdef</p> CSS body { pointer-events: none; } p { border: 1px solid; font-size: 2em; padding: .3em; } button { font-size: 1.2em; padding: .5em; pointer-events: auto; } JavaScript const list1 = document.
getElementById('list1'); const list2 = document.
getElementById('list2'); const button = document.
getElementById('swap'); button.addEventListener('click', e => { selection = window.getSelection(); for (let i = 0; i < selection.rangeCount; i++) { const range = selection.getRangeAt(i); if (range.commonAncestorContainer === list1 || range.commonAncestorContainer.parentNode === list1) { const documentFragment = range.extractContents(); list2.appendChild(documentFragment); ...
Range.selectNodeContents() - Web APIs
tNodeContents(), and Selection.addRange() are used to select the content. Window.getSelection() and Selection.removeAllRanges() are used to deselect it. ...
...to select the content. Window.getSelection() and Selection.removeAllRanges() are used to deselect it. ...
...AllRanges() are used to deselect it. ...
Response.redirected - Web APIs
st is as simple as checking this flag on the Response object. In the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation. Note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under Disallowing redirects below. ...
..., as described under Disallowing redirects below. ...
... Living Standard Initial definition ...
ARIA: button role - Accessibility
// Don't add blank entries to the list. if(name.length > 0) { listItem = document.createElement('li'); listItem.appendChild(document.createTextNode(name)); // Add the ne...
... newNameInput.value = ''; // clear the text field newNameInput.focus(); // give the text field focus to enable entering and additional name. // Don't add blank entries to the list. if(name.length > 0) { listItem = document.createElement('li'); listItem.appendChild(document.createTextNode(name)); // Add the new name to the list. let list = document.
getElementById('nameList'); list.appendChild(listItem); } } Toggle button example In this snippet a <span> element is converted to a toggle button using the button role and the aria-pressed attribute. When the button is activated, the aria-pressed value switches states; changing from true to false and back again. HTML <button type="button" onclick="handleBtnClick()" onKeyDown="handleBtnKeyDown...
...et); } function handleBtnKeyDown(event) { // Check to see if space or enter were pressed if (event.key === " " || event.key === "Enter" || event.key === "Spacebar") { // "Spacebar" for IE11 support // Prevent the default action to stop scrolling when space is pressed event.preventDefault(); toggleButton(event.target); } } function toggleButton(element) { var audio = document.
getElementById('audio'); // Check to see if the button is pressed var pressed = (element.getAttribute("aria-pressed") === "true"); // Change aria-pressed to the opposite state element.setAttribute("aria-pressed", !pressed); // toggle the play state of the audio file if(pressed) { audio.pause(); } else { audio.play(); } } Result Accessibility concerns Buttons are interactive contro...
Web applications and ARIA FAQ - Accessibility
s bar widget. The aria-valuemin and aria-valuemax attributes specify the minimum and maximum values for the progress bar, and the aria-valuenow describes the current state of it. Along with placing them directly in the markup, ARIA attributes can be added to the element and updated dynamically using JavaScript code like this: // Find the progress bar <div> in the DOM. var progressBar = document.
getElementById("percent-loaded"); // Set its ARIA roles and states, so that assistive technologies know what kind of widget it is. progressBar.setAttribute("role", "progressbar"); progressBar.setAttribute("aria-valuemin", 0); progressBar.setAttribute("aria-valuemax", 100); // Create a function that can be called at any time to update the value of the progress bar. function updateProgress(percentComplete) { ...
... used for an HTML5 progress bar: <!DOCTYPE html> <html> <head><title>Gracefully degrading progress bar</title></head> <body> <progress id="progress-bar" value="0" max="100">0% complete</progress> <button id="update-button">Update</button> </body> </html> ... and here is the JavaScript code that will ensure the progress bar still works in older browsers: var progressBar = document.
getElementById("progress-bar"); // Check to see if the browser supports the HTML5 <progress> tag. var supportsHTML5Progress = (typeof (HTMLProgressElement) !== "undefined"); function setupProgress() { if (!supportsHTML5Progress) { // HTML5 <progress> isn't supported in this browser, so we need to add // ARIA roles and states to the element. progressBar.setAttribute("role", "progressbar"); pr...
...now", percentComplete); } else { // 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 us...
:scope - CSS: Cascading Style Sheets
ement. When used from a DOM API such as querySelector(), querySelectorAll(), matches(), or Element.closest(), :scope matches the element on which the method was called. Syntax :scope Examples Identity match In this simple example, we demonstrate that using the :scope pseudo-class from the Element.matches() method matches the element on which it's called. JavaScript let paragraph = document.
getElementById("para"); let output = document.
getElementById("output"); if (paragraph.matches(":scope")) { output.innerText = "Yep, the element is its own scope as expected!"; } HTML <p id="para"> This is a paragraph. It is not an interesting paragraph. Sorry about that. </p> <p id="output"></p> Result Direct children A situation where the :scope pseudo-class prove to be useful is when you need to g...
...) { output.innerText = "Yep, the element is its own scope as expected!"; } HTML <p id="para"> This is a paragraph. It is not an interesting paragraph. Sorry about that. </p> <p id="output"></p> Result Direct children A situation where the :scope pseudo-class prove to be useful is when you need to get direct descendant of an already retrieved Element. ...
...a"> This is a paragraph. It is not an interesting paragraph. Sorry about that. </p> <p id="output"></p> Result Direct children A situation where the :scope pseudo-class prove to be useful is when you need to get direct descendant of an already retrieved Element. ...
font-kerning - CSS: Cascading Style Sheets
-line.InheritedyesComputed valueas specifiedAnimation typediscrete Formal syntax auto | normal | none Examples Enabling and disabling kerning HTML <div id="kern"></div> <div id="nokern"></div> <textarea id="input">AV T. ...
...mation typediscrete Formal syntax auto | normal | none Examples Enabling and disabling kerning HTML <div id="kern"></div> <div id="nokern"></div> <textarea id="input">AV T. ...
...mal | none Examples Enabling and disabling kerning HTML <div id="kern"></div> <div id="nokern"></div> <textarea id="input">AV T. ...
grid-auto-flow - CSS: Cascading Style Sheets
"row" : "column"; if (dense.checked) { gridAutoFlow += " dense"; } grid.style.gridAutoFlow = gridAutoFlow; } Result Specifications Specification Status Comment CSS Grid LayoutThe definition of...
... Candida...
... Candidate Recommendation Initial definition ...
Web Audio playbackRate explained - Developer guides
Note: Try out this example live, and try ad...
... Note: Try out this example live, and try adjusting the playback rate control to see the e...
... Note: Try out this example live, and try adjusting the playback rate control to see the effect. defaultPlaybackRate and ratechang...
Audio and Video Delivery - Developer guides
latest versions of Chrome, Firefox and Opera. To grab the stream from your webcam, first set up a <video> element: <video id="webcam" width="480" height="360"></video> Next, if supported connect the webcam source to the video element: if (navigator.mediaDevices) { navigator.mediaDevices.getUserMedia({ video: true, audio: false }) .then(function onSuccess(stream) { var video = document.
getElementById('webcam'); video.autoplay = true; video.srcObject = stream; }) .catch(function onError() { alert('There has been a problem retreiving the streams - are you running on file:/// or did you disallow access?'); }); } else { alert('getUserMedia is not supported in this browser.'); } To find out more, read our MediaDevices.getUserMedia page. Mediastream Recording New standards a...
...member keyboard controls for user convenience and accessibility. ...
...sibility. ...
Rich-Text Editing in Mozilla - Developer guides
sists of an iframe, which will be the rich editing area, as well as elements for basic editing commands such as bold/italics/text color. Figure 3 : Setting up rich-text editing HTML: <body onload="load()"> JavaScript: function load(){ getIFrameDocument("editorWindow").designMode = "On"; } function getIFrameDocument(aID){ // if contentDocument exists, W3C compliant (Mozilla) if (document.
getElementById(aID).contentDocument){ return document.
getElementById(aID).contentDocument; } else { // IE return document.frames[aID].document; } } The example contains a doRichEditCommand function that makes it easier to execute commands on the iframe's document and keeps the HTML code clean. The function executed the requested command using execCommand() and then sets focus back to the edita...
... sets focus back to the editable document, as clicking on a button will set focus on the button itself, which breaks the editing flow. ...
...utton> JavaScript: function doRichEditCommand(aName, aArg){ getIFrameDocument('editorWindow').execCommand(aName,false, aArg); document.
getElementById('editorWindow').contentWindow.focus() } Example: a simple but complete Rich Text Editor <!doctype html> <html> <head> <title>Rich Text Editor</title> <script type="text/javascript"> var oDoc, sDefTxt; function initDoc() { oDoc = document.
getElementById("textBox"); sDefTxt = oDoc.innerHTML; if (document.compForm.switchMode.checked) { setDocMode(true); } } function formatDoc(sCmd, sValue) { if (validateMode()) { document.execCommand(sCmd, false, sValue); oDoc.focus(); } } function validateMode() { if (!document.compForm.switchMode.checked) { return true ; } alert("Uncheck \"Show HTML\"."); oDoc.focus(); return false; } function s...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
h: 500px; height: 200px; border: 2px solid rgb(245, 220, 225); padding: 4px 6px; font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif" } JavaScript The script here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <input type="color"> element. ...
...(245, 220, 225); padding: 4px 6px; font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif" } JavaScript The script here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <input type="color"> element. ...
...16px "Lucida Grande", "Helvetica", "Arial", "sans-serif" } JavaScript The script here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <input type="color"> element. ...
Promise - JavaScript
andom. The Promise() constructor is used to create the promise. The fulfillment of the promise is simply logged, via a fulfill callback set using p1.then(). A few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the promise. ...
...(You need a browser that supports Promise. ) By clicking the button several times in a short amount of time, you'll even see the...
...(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 fulfilled one after another. Loading an image with XHR Another s...
Communicating With Other Scripts - Archive of obsolete content
includes a button and a page script: <html> <head> <meta charset="utf-8"> </head> <body> <input id="message" type="button" value="Send a message"/> <script type="text/javascript" src="page-script.js"></script> </body> </html> The content script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.
getElementById("message"); messenger.addEventListener("click", sendCustomEvent, false); function sendCustomEvent() { var greeting = {"greeting" : "hello world"}; var event = document.createEvent('CustomEvent'); event.initCustomEvent("addon-message", true, true, greeting); document.documentElement.dispatchEvent(event); } Finally, the page script "page-script.js" listens for the message and logs the gre...
...g); }, false); After Firefox 30: clone the message object This technique depends on being able to share the message payload between the content script scope and the page script scope. ...
XUL Migration Guide - Archive of obsolete content
button API, which is only available from Firefox 29 onwards. The window/utils module gives you direct access to chrome windows, including the browser's chrome window. ...
...he window/utils module gives you direct access to chrome windows, including the browser's chrome window. Here's a really simple example add-on that modifies the browser chrome using window/utils: function removeForwardButton() { var window = require("sdk/window/utils").getMostRecentBrowserWindow(); var forward = window.document.
getElementById('forward-button'); var parent = window.document.
getElementById('urlbar-container'); parent.removeChild(forward); } require("sdk/ui/button/action").ActionButton({ id: "remove-forward-button", label: "Remove Forward Button", icon: "./icon-16.png", onClick: removeForwardButton }); There are more useful examples of this technique in the Jetpack Wiki's collection of third party modules. Accessing tabbrowser This example uses the action button API,...
panel - Archive of obsolete content
user // entered. // In this implementation 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 t...
...tEntryPanel.port.on("text-entered", function (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 ...
Miscellaneous - Archive of obsolete content
ng 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. This is the scrolling area. This is the scrolling area. ...
...If you wish to block selected scripts based on their URI, implement nsIContentPolicy. Using string bundles from Ja...
Tree - Archive of obsolete content
eView = tree.treeBoxObject.view; for (var i = 0; i < treeView.rowCount; i++) { if (treeView.isContainer(i) && treeView.isContainerOpen(i)) treeView.toggleOpenState(i); } Getting the text from the selected row Assuming the given <tree>: <tree id="my-tree" seltype="single" onselect="onTreeSelected()"> Use the following JavaScript: function onTreeSelected(){ var tree = document.
getElementById("my-tree"); var cellIndex = 0; var cellText = tree.view.getCellText(tree.currentIndex, tree.columns.getColumnAt(cellIndex)); alert(cellText); } Getting the tree item from the focused row Assuming <tree id="my-tree">, you can use the following to get the tree item: var view = document.
getElementById("my-tree").view; var sel = view.selection.currentIndex; //returns -1 if the tree is n...
...thing similar. But this will not work. You can't add event handlers to <treecell>. Instead, you can add the event handler to the <tree> element. You can then use the event and some utility methods to find the <treecell>. ...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
type: "menu", label: "Test button label", tooltiptext: "Test button tooltip", removable: true, key: "myTestButton123" }, [ "menupopup", { onpopupshowing: function(event) { addEntryToPopup(this, document, window); } }, null ] ]; var capturedNodes = {}; var toolbox = doc.
getElementById("navigator-toolbox"); var palette = toolbox.palette; var domFragment = jsonToDOM(jsonTemplateBtn, document, capturedNodes); palette.appendChild(domFragment); alert("capturedNodes contains any created nodes that have optionally been captured (for later convenient JavaScript access) by giving them a 'key' attribute; for example: " + capturedNodes.myTestButton123); Another Example This here is a...
...bose, but slightly more efficient: function escapeHTML(str) { return str.replace(/[&"'<>]/g, (m) => escapeHTML.replacements[m]); } escapeHTML.replacements = { "&": "&", '"': """, "'": "'", "<": "<", ">": ">" }; Note that quotation marks must be escaped in order to prevent fragments escaping attribute values. var href = "http://www.google.com/"; var text = "Google"; document.
getElementById("target-div").innerHTML = '<div>\ <a href="' + escapeHTML(href) + '" target="_top">' + escapeHTML(text) + '</a>\ </div>' It needs to be stressed that this method should not be used in new code and is only a temporary measure to shore up legacy code bases. Safely Generating Event Listeners and Scripts It is occasionally necessary to generate event listeners and script fragments fro...
JavaScript Object Management - Archive of obsolete content
OM on the window has loaded completely, but before it's displayed to the user. This allows you to manipulate and possibly change elements 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 bef...
... 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 like this anyway, one way to do it is to have a timeout execute the code after a delay: init : function(aEvent) { let that = this; this._stringBundle = document.
getElementById("xs-hw-string-bundle"); window.setTimeout( function() { window.alert(that._stringBundle.getString("xulschoolhello.greeting.label")); }, 0); } The setTimeout function executes the function in the first parameter, after a delay in miliseconds specified by the second parameter. In this case we set the delay to 0, which means the function should be executed as soon as possible. Firefo...
The Essentials of an Extension - Archive of obsolete content
. Naming and referencing objects in such a long and verbose manner can feel uncomfortable at first, but it's worth the cost. We use Javadoc style comments on all namespaces, objects and object members. This is a similar standard to the one used in Mozilla code, and some tools can generate documentation automatically from Javadoc. sayHello : function(aEvent) { let stringBundle = document.
getElementById("xulschoolhello-string-bundle"); let message = stringBundle.getString("xulschoolhello.greeting.label"); window.alert(message); } And, finally, this is our function declaration. Three lines of code are all we need for it to work. The first line in the body of the function declares a variable that will hold the stringbundle element defined in the overlay. The variable is declared using let,...
...W" and the Window menu on Mac OS. So we settled on the letter "l". DTD strings are resolved and set when the document is being loaded. If you request the label attribute value for the Hello World menu using DOM, you get the localized string, not the string key. ...
Creating a dynamic status bar extension - Archive of obsolete content
refreshInformation() so that its variable scope includes the variables used by that function. Due to the way JavaScript works, if infoReceived() were outside refreshInformation(), it would not have access to the same variable scope. In fact, even the this value would not match, so we couldn't get at the same variables and functions that way. ...
...We need this so that we can make changes to the status bar panel itself. We then fetch the result returned by the web server into the variable output from the XMLHttpRequest.responseText property. The text we receive back from the server looks something like this: "GOOG",414.20,"5/1/2006","1:36pm",-3.74,417.85,419.44,412.19,4760215 We then parse the text. We use the split() stri...
Localizing an extension - Archive of obsolete content
ript code Now we're ready to revise the JavaScript code to load the strings from the string bundle instead of using literal strings. This involves rewriting the refreshInformation() function to load the strings, and its enclosed infoReceived() function to use the loaded, localized, strings instead of string literals. ...
...Then it fetches all the strings we need from the bundle, one by one, by calling the string bundle's getString() method, passing the appropriate key for each string. In this case, we're also appending a space to the end of each string. That's just how this particular program works, and isn't something that you have to do. Then we replace any occurrences of the...
Monitoring WiFi access points - Archive of obsolete content
low WiFi-based location services to be used by geolocation services. Example This example simply displays a list of the available access points. ...
...n test() { } test.prototype = { onChange: function (accessPoints) { netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); var d = document.
getElementById("d"); d.innerHTML = ""; for (var i=0; i<accessPoints.length; i++) { var a = accessPoints[i]; d.innerHTML += "<p>" + a.mac + " " + a.ssid + " " + a.signal + "</p>"; } var c = document.
getElementById("c"); c.innerHTML = "<p>" + count++ + "</p>"; }, onError: function (value) { alert("error: " +value); }, QueryInterface: function(iid) { netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); if (iid.equals(Components.interfaces.nsIWifiListener) || iid.equals(Components.interfaces.nsISupports)) return this; thr...
Visualizing an audio spectrum - Archive of obsolete content
alysis on an audio stream, rather than the code shown below. ...
...vas before drawing spectrum ctx.clearRect(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); ...
Monitoring downloads - Archive of obsolete content
s the full source URL of the file. Download the full sample. Setting up When the extension loads, it will do some housekeeping chores. In particular, it needs to get an instance of the Download Manager's nsIDownloadManager interface and create the database into which its data will be stored. ...
..."ProfD", Components.interfaces.nsIFile); this.dbFile.append("downloadlogger.sqlite"); // Get access to the storage service and open the database this.storageService = Components.classes["@mozilla.org/storage/service;1"] .getService(Components.interfaces.mozIStorageService); var dbConn = this.storageService.openDatabase(this.dbFile); var loglist = document.
getElementById("loglist"); var statement = dbConn.createStatement("SELECT * FROM items"); // Get all items in table try { while (statement.executeStep()) { var row = document.createElement('listitem'); // Add the cells to the row var cell = document.createElement('listcell'); var sourceStr = statement.getString(0); row.setAttribute("tooltiptext", sourceStr); ...
PyDOM - Archive of obsolete content
a top-level window has something like: <window ... script="foo = 1" ... An event handler like: <button onclick="print foo"/> Should be able to reference 'foo' via globals as shown. Note that you can stick arbitrary values on any DOM object - this is what JS calls 'expandos'. ...
...f might look like: <button id="some-button" label="click here" onclick="event.target.foo += 1; print 'Foo is now', event.target.foo"/> Note that (a) we have stuck an arbitrary attribute on a DOM element and (b) in all cases (e.g., event handler and top-level script), the DOM node needs to be explicitly specified - the globals are the window itself. The event handler could also have used
getElementById - the point is that both the event handler and top-level script share the same namespace. Using Python Ideally, you just tell Mozilla you are using Python, and magically you can use Python instead of JavaScript. Once you set the script type for a node, it is the default for that node and all children. This means that if you set the script-type to Python for the window, Python is the default scrip...
Building accessible custom components in XUL - Archive of obsolete content
egains focus (by pressing SHIFT-TAB, or cycling all the 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. ...
...w = get_index_within_parent(current); var column = 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 assistiv...
removeItemAt - Archive of obsolete content
<< XUL Reference home removeItemAt( index ) Return type: element Removes the child item in the element at the specified index. The method returns the removed item. ...
...e specified index. The method returns the removed item. ...
OpenClose - Archive of obsolete content
perty which may be set to true to open the menu, or false to close the menu. A simple example: somemenu.open = true; This single line of code will open a menu referenced by the variable 'somemenu'. Note that the open property applies to the menu or button, not to the menupopup. Here is a complete example which uses a button to open a menu: <button label="Open Menu" oncommand="document.
getElementById('editMenu').open = true;"/> <menu id="editMenu" label="Edit"> <menupopup> <menuitem label="Cut"/> <menuitem label="Copy"/> <menuitem label="Paste"/> </menupopup> </menu> This technique may be used for both menupopups that use the menu tag, the button tag and the toolbarbutton tag. For menupopups attached to other elements using the popup or context attributes, see Opening a Pop...
...es the x and y offsets, in this case 60 and 50 as offsets from the edge of the window or frame. This way, a popup can be positioned relative to the window, rather than relative to a specific node. For example, you might wish to open a popup at the current mouse position when the mouse is clicked. Here is an example mouse click event listener: function mouseClicked(event) { var panel = document.
getElementById("some-panel"); panel.openPopup(null, "", event.clientX, event.clientY, false, false); } The openPopupAtScreen method A second method, openPopupAtScreen, may be used to open up a popup and place it at a specific screen coordinate. In this case, the popup is not anchored to an element and just appears at a specific location specified by the x and y arguments to this method. void openPopupAtSc...
Panels - Archive of obsolete content
bout both methods, see Opening and Closing Popups. Closing a panel A panel is closed automatically when the user clicks outside of the panel. It is quite common however, to have an element such as a button within the panel to close it as well. For instance, using the search panel example above, we could add a button which closes the panel when pressed: <script> function doSearch() { document.
getElementById("search-panel").hidePopup(); } </script> <toolbarbutton label="Search" type="panel"> <panel id="search-panel" position="after_start"> <textbox id="search"/> <button label="Search" oncommand="doSearch();"/> </panel> </toolbarbutton> In this example, the doSearch() function is called when the "Search" button is pressed. This function retrieves the popup and calls the hidePopup method...
.... Although no element within the popup panel is focused by default, the user may focus the first element within the panel by pressing the Tab key. If you want to set the focus to an element by default when a panel is opened, adjust the focus within a popupshown event handler. For instance, to have the textbox initially focused in the example above: <panel id="search-panel" onpopupshown="document.
getElementById('search').focus()"> To disable the adjusting of focus when a panel is opened, set the noautofocus attribute to true: <panel noautofocus="true"> This will cause the focus to remain on the element within the main window that has focus when the panel is opened. Note that this will also keep the focus within the panel when it is closed. When a panel is closed, the focus is removed from the elem...
SQLite Templates - Archive of obsolete content
friends where gender = 'male' This technique is used as quotes or other special characters are handled automatically. If a quote appears in the value, it will escaped as needed. Now, to adjust the query to something else, say to look up females, all you need to do is get a reference to the param element and adjust the contents. You would likely want to add an id to the param element so that the
getElementById method may be used to refer to it. You can add as many parameters as necessary for the query. The example above used a string parameter. If you want a numeric parameter, you should also set the type attribute. <listbox id="friends" datasources="profile:userdata.sqlite" ref="*" querytype="storage"> <template> <query> select name, from myfriends where age >= :minage && age <= :maxage ...
...ox> Here, the age is an integer number, so the type attribute is set to integer. Integers are 32-bit values, but you can use the value int64 for 64-bit integers. You can also use the value double for double precision floating point values. If no type is specified, a string is assumed. We could later change the age to use in the query with a short script: function adjustAge(min, max) { document.
getElementById("minage").textContent = min; document.
getElementById("maxage").textContent = max; document.
getElementById("friends").builder.rebuild(); } This function takes two arguments, the minimum and maximum values to use. We retrieve the param elements and set their textContent properties to the desired value. Finally, we rebuild the entire template. << PreviousNext >> ...
Template Builder Interface - Archive of obsolete content
thod. You can add as many datasources as you wish, and you can remove them using the RemoveDataSource method. A common pattern is to use the following: var RDF = Components.classes["@mozilla.org/rdf/rdf-service;1"]. getService(Components.interfaces.nsIRDFService); var ds = RDF.GetDataSource("http://www.xulplanet.com/ndeakin/tests/xul/template-guide-streets.rdf"); var tree = document.
getElementById("theTree"); tree.database.AddDataSource(ds); tree.builder.rebuild(); This is the typical way to add a datasource to an element, in this case to the tree with the id 'theTree'. The datasource is retrieved using the RDF service's GetDataSource method. After adding a datasource, the tree builder's rebuild method is invoked to rebuild the template with the new data. This doesn't happen automatically...
...d the datasource, which is useful, since you will often want to add or remove other datasources at the same time. The composite datasource can only be accessed from privileged code, regardless of what datasources it contains. Fortunately in this situation, you can just set the datasources attribute (or the corresponding property) to the datasources that you want. For instance: var tree = document.
getElementById("theTree"); tree.datasources = "template-guide-photos5.rdf template-guide-streets.rdf"; This will also change the datasources used. In this case, the template will be rebuilt automatically as you can set all of the datasources at once with this method of changing datasources. So you don't need to call the rebuild method. You can also do the same with the ref attribute (or the ref property) and t...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
Middle click break; case 2: // Right click break; } } To add more buttons, put more <toolbarbutton> elements inside the <toolbarpalette> element. Wrap elements other than <toolbarbutton> in <toolbaritem>. Adding the Button Bootstrap Style Adding a button to the BrowserPalette on runtime in a Bootstrap addon is a bit different because the BrowserPalette is indirectly reached. A simple document.
getElementById('BrowserToolbarPalette') will 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 = "...
...un on Gists@GitHub here: _ff-addon-snippet-AddToolbarButtonToPalette.js . It is based on the code from the repo above. Here are some discussions at Mozillazine about adding a toolbar button in a Bootstrap addon: Programmatically add a button to toolbar palette? The advantage to adding the toolbar button to the palette rather than creating an element and then appendChild to the toolbar (document.
getElementById('nav-bar')) or appendChild to the addon bar (document.
getElementById('addon-bar')) is that once in the toolbar palette, users can configure it through the customize menu. They can drag it to the addon bar or to the toolbar. Styling the button Most toolbar buttons have icons. To attach an image to the button we use standard Mozilla skinning facilities. If you're unfamiliar with how that works, r...
Adding Methods to XBL-defined Elements - Archive of obsolete content
as the parameter to getAnonymousNodes(). The next example can be used to create text with a label. The method 'showTitle' can be used to show or hide the label. It works by getting a reference to the title element using the anonymous array and changing the visibility of it. ...
...ext with a label. The method 'showTitle' can be used to show or hide the label. It works by getting a reference to the title element using the anonymous array and changing the visibility of it. ...
Adding Properties to XBL-defined Elements - Archive of obsolete content
<< PreviousNext >> Next, we'll find out how to add custom properties to XBL-defined elements. The XBL Interface JavaScript and the DOM provide access to get and set the properties of elements. With XBL, you can define your own properties for the elements you create. You can also add methods that can be called. That way, all you need is to get a reference to the element (using document.
getElementById or a similar function) and then get or set the additional properties and call the methods on it. There are three types of items you can add. Fields are used to hold a simple value. Properties can also be used to hold a value but may have code execute when an attempt is made to retrieve or modify the value. Methods are functions which may be executed. All three are defined within an implement...
...set the value. The example below creates a button which generates and stores a random number. You can retrieve this same number multiple times by getting the number property from the button. Most of the work here is done in the oncommand handlers. Later, we'll find out how to move this to XBL. XUL: <box id="random-box" class="randomizer"/> <button label="Generate" oncommand="document.
getElementById('random-box').number=Math.random();"/> <button label="Show" oncommand="alert(document.
getElementById('random-box').number)"/> XBL: <binding id="randomizer"> <implementation> <field name="number"/> </implementation> </binding> A number field has been defined in the binding, which stores the random number. The two extra buttons set and get the value of this field. The syntax i...
Creating Dialogs - Archive of obsolete content
the platform the application is running on. In addition, the openDialog() function can take additional arguments beyond the first three. These arguments are passed to the new dialog and placed in an array stored in the new window's arguments property. You can pass as many arguments as you wish. This is a convenient way to supply default values to the fields in the dialog. var somefile=document.
getElementById('enterfile').value; window.openDialog("chrome://findfile/content/showdetails.xul","showmore", "chrome",somefile); In this example the dialog showdetails.xul is displayed. It's passed one argument, somefile, which was taken from the value of an element with the ID enterfile. In a script used by the dialog, we can then refer to the argument using the window's arguments property...
...le/content/showdetails.xul","showmore", "chrome",somefile); In this example the dialog showdetails.xul is displayed. It's passed one argument, somefile, which was taken from the value of an element with the ID enterfile. In a script used by the dialog, we can then refer to the argument using the window's arguments property. For example: var fl = window.arguments[0]; document.
getElementById('thefile').value = fl; This is an effective way to pass values to the new window. You can pass values back from the opened window to the original window in one of two ways. First, you could use the window.opener property which holds the window that opened the dialog. Second, you could pass a function or object as one of the arguments when creating the dialog, then call that function or modify t...
Custom Tree Views - Archive of obsolete content
he first treecol in the example above. This example is very simple of course -- in reality you would have more complex data in each cell. The final step is to associate the view object with the tree. The tree has a property view, which can be assigned to the view object declared above. We can assign a value to this property at any time to set or change the view. function setView(){ document.
getElementById('my-tree').view = treeView; } The following presents the example together. An inline script has been used here to simplify the example. Normally, you would put the script in an external script file. Example custom tree Source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window title="Tree Example" id="tree-window" xmlns="http://www.mozilla.org/...
...The setView() function has been called in the onload() handler for the...
More Event Handlers - Archive of obsolete content
the events. To manually stop event 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 call...
...rdinates. The first is the screenX and screenY properties and are relative to the top left corner of the screen. The second set, clientX and clientY, are relative to the top left corner of the document. Here is an example which displays the current mouse coordinates: Example 4 : Source View <script> function updateMouseCoordinates(e){ var text = "X:" + e.clientX + " Y:" + e.clientY; document.
getElementById("xy").value = text; } </script> <label id="xy"/> <hbox width="400" height="400" onmousemove="updateMouseCoordinates(event);"/> In this example, the size of the box has been set explicitly so the effect is easier to see. The event handler gets the clientX and clientY properties and creates a string from them. This string is then assigned to the value property of the label. Note that the event ar...
More Wizards - Archive of obsolete content
It is also called whenever a key is pressed in the textbox, to determine whether the Next button should be enabled again. ...
... textbox, to determine whether the Next button should be enabled again. ...
Property Files - Archive of obsolete content
lugin/locale/strings.properties"/> </stringbundleset> Like other non-displayed elements, you should declare all your stringbundles inside a stringbundleset element so that they are all kept together. Getting a String from the Bundle This stringbundle element has a number of properties. The first is getString which can be used in a script to read a string from the bundle. var strbundle = document.
getElementById("strings"); var nofilesfound=strbundle.getString("notFoundAlert"); alert(nofilesfound); This example first gets a reference to the bundle using its id Then, it looks up the string 'notFoundAlert' in the property file. The function getString() returns the value of the string or null if the string does not exist. Finally, the string is displayed in an alert box. Text Formatting The next meth...
... string does not exist. Finally, the string is displayed in an alert box. Text Formatting The next method is getFormattedString(). This method also gets a string with the given key name from the bundle. In addition, each occurrence of formatting code (e.g. %S) is replaced by each successive element in the supplied array. var dir = "/usr/local/document"; var count = 10; var strbundle = document.
getElementById("strings"); var result = strbundle.getFormattedString("resultMessage", [ dir, count ]); alert(result); This example will display following message in an alert box. 10 files found in the /usr/local/document directory. You will notice the formatting codes %1$S and %2$S is used, and replaced different order in the array. Formatting code %n$S is specify the position of corresponding parameter dire...
Tree View Details - Archive of obsolete content
ol id="element" label="Element" primary="true" flex="1"/> </treecols> <treechildren/> </tree> </window> We use a simple tree here with no data in the treechildren. The 'init' function is called when the window is loaded to initialize the tree. It simply sets the custom view by retrieving the tree and setting its 'view' property. We will define 'treeView' next. function init() { document.
getElementById("elementList").view = treeView; } The custom tree view will need to implement a number of methods, of which the important ones will be examined individually. First we'll define two structures to hold the data for the tree, the first will hold a map between parents and the children they contain, and the second will hold an array of the visible items. Remember that a custom view must keep track o...
... << PreviousNext >> ...
XUL Event Propagation - Archive of obsolete content
arget itself or any of the intervening nodes. 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 e...
...ding 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 capturing, or be registered to listen for events that bubble up the hiearchy normally. Note: The DOM provides the addEve...
tree - Archive of obsolete content
XUL for the tree: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <?xml-stylesheet href="file://C:/main.css" type="text/css"?> <window xmlns="http://www.mozilla.org/k...
... ...
How to enable locale switching in a XULRunner application - Archive of obsolete content
selectedItem = listitem; } loca...
... must be restarted to activate the new choice. Here is an example event handler which is fired when the user clicks on the button to change the locale. It saves the new locale to the user application preferences (thereby overriding the default prefs.js above) and then asks XULRunner to restart. function changeLocale() { try { // Which locale did the user select? var localeListbox = document.
getElementById("locale-listbox"); var newLocale = localeListbox.selectedItem.value; // Write preferred locale to local user config var prefs = Components.classes["@mozilla.org/preferences-service;1"]. getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref("general.useragent.locale", newLocale); // Restart application var appStartup = Components.classes["@mozilla...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
erful concept of Jaxer is the ability to access the DOM server-side with JavaScript. This gives you added control to interrogate and manage the document structure before it's pushed to the client. Listing 7 contains the code which demonstrates this concept. Listing 7 - Manipulating the DOM server-side <script runat="server"> window.onserverload = function() { document.
getElementById( "out-logger" ).innerHTML = Jaxer.File.read( "dump.txt" ); } </script> The code in listing 7 is executed server-side and takes advantage of the onserverload event which ensures that we have a complete DOM before trying to access it. This code is simple in that it updates the innerHTML of the logging div with the contents of a text file. The contents of this file are obta...
...a <script> function formHandler() { // get the form values var name = txt_name.getValue(); var email = txt_email.getValue(); var message = txt_message.getValue(); // if the form passes validation client-side, submit results to the processor if( validateComments( name, email, message ) ) { formProcessor( name, email, message ); // update the logger with the most recent entry document.
getElementById( "out-logger" ).innerHTML += "name: " + name + "<br/>email: " + email + "<br/>message: " + message + "<br/><br/>"; } else { Ext.Msg.alert( "Error", "Please enter the required fields" ); } } </script> <!-- processes the form contents --> <script runat="server"> function formProcessor( name, email, message ) { // perform the same validation of the data server-side if( !validateComments( name...
Displaying a graphic with audio samples - Archive of obsolete content
E html> <html> <head> <title>JavaScript Spectrum Example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <img id="mozlogo" style="display:none" src="mozilla2.png"></img> <script> var canvas = document.
getElementById('fft'), ctx = canvas.getContext('2d'), channels, rate, frameBufferLength, fft; function loadedMetadata() { channels = audio.mozChannels; rate = audio.mozSampleRate; frameBufferLength = audio.mozFrameBufferLength; fft = new FFT(frameBufferLength / channels, rate); } ...
...tx.fillRect (0,0, canvas.width, canvas.height); ctx.fillStyle = "rgb(255,255,255)"; for (var i = 0; i < signal.length; i++ ) { // 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> ...
GLSL Shaders - Game development
the alpha transparency (ranging from 0.0 -- fully transparent -- to 1.0 -- fully opaque). Applying the shaders To actually apply the newly created shaders to the cube, comment out the basicMaterial definition first: // var basicMaterial = new THREE.MeshBasicMaterial({color: 0x0095DD}); Then, create the shaderMaterial: var shaderMaterial = new THREE.ShaderMaterial( { vertexShader: document.
getElementById( 'vertexShader' ).textContent, fragmentShader: document.
getElementById( 'fragmentShader' ).textContent }); This shader material takes the code from the scripts and applies it to the object the material is assigned to. Then, in the line that defines the cube we need to replace the basicMaterial: var cube = new THREE.Mesh(boxGeometry, basicMaterial); ...with the newly created shaderMaterial:...
...H, HEIGHT); renderer.setClearColor(0xDDDDDD, 1); document.body.appendChild(renderer.domElement); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(70, WIDTH/HEIGHT); camera.position.z = 50; scene.add(camera); var boxGeometry = new THREE.BoxGeometry(10, 10, 10); var shaderMaterial = new THREE.ShaderMaterial( { vertexShader: document.
getElementById( 'vertexShader' ).textContent, fragmentShader: document.
getElementById( 'fragmentShader' ).textContent }); var cube = new THREE.Mesh(boxGeometry, shaderMaterial); scene.add(cube); cube.rotation.set(0.4, 0.2, 0); function render() { requestAnimationFrame(render); renderer.render(scene, camera); } render(); CSS body { margin: 0; padding: 0; fo...
Images in HTML - Learn web development
th: 95%"> <img> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.
getElementById('code'); var reset = document.
getElementById('reset'); var solution = document.
getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = ht...
...x; width: 95%"> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.
getElementById('code'); var reset = document.
getElementById('reset'); var solution = document.
getElementById('solution'); var output = document.querySelector('.output'); var code = textarea.value; var userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = ht...
Introduction to events - Learn web development
ubmit event handler (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty. ...
...n a form when it is submitted) that tests whether the text fields are empty. ...
Looping code - Learn web development
d(para); </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCod...
...ontent += ; </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCod...
Making decisions in your code — conditionals - Learn web development
: 0; } .output li { display: block; float: left; width: 25%; border: 2px solid white; padding: 5px; height: 40px; background-color: #4A2DB6; color: white; } html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCod...
... textColor; }</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCod...
Arrays - Learn web development
er 4 // number 5 let itemText = 0; const listItem = document.createElement('li'); listItem.textContent = itemText; list.appendChild(listItem); } totalBox.textContent = 'Total: $' + total.toFixed(2); </textarea> <div class="playable-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'; updateCod...
...ocus(); } } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { eval(textarea.value); } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntry = jsSolution; solution.value = 'Show solution'; updateCod...
Basics
> <msup> <mi>y</mi> <mn>4</mn> </msup> </mrow> <mo>+</mo> <msup> <mi>y</mi> <mn>5</mn> </msup> </mrow> </maction> </mtd> </mtr> </mtable> </mtd> </mtr> </mtable> </math> </div> CSS Content .control { text-decoration: none; font-weight: bold; font-size: 200%; } input { color: red; } [class="inputmath"] { border: 1px dotted; } JavaScript Content function setSelection(id,value) { document.
getElementById(id).setAttribute("selection",value); } function expand() { setSelection("a11","2"); setSelection("a12","2"); setSelection("a13","2"); setSelection("a21","2"); setSelection("a22","2"); setSelection("a23","2"); setSelection("a31","2"); setSelection("a32","2"); setSelection("a33","2"); setSelection("a41","2"); setSelection("a42","2"); setSelection("a43","2"); } function unexpand() { ...
... MathML Button HTML Content <div style="text-align: center"> <button style="white-space: normal;"> <span style="color: brown;"> For example, <b>click</b> this MathML continued fraction<br/> inside this HTML button<br /...
MathML Torture Test
addEventListener("change", updateMathFont, false) } window.addEventListener("load", load, false); The following test contains sample TeX formulas from Knuth's TeX...
...h; } .TeXGyreTermes math { font-family: TeX Gyre Termes Math; } .XITS math { font-family: XITS Math; } JavaScript Content function updateMathFont() { var mathFont = document.
getElementById("MathFont").value; if (mathFont == "Default") { document.body.removeAttribute("class"); } else { document.body.setAttribute("class", mathFont); } } function load() { document.
getElementById("MathFont"). 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 a...
MathML Demo: <mspace> - space
f="javascript:downdepth();" title="decrease depth">-</a> <math display="block"> <mstyle displaystyle="true"> <msqrt> <mrow> <mn>3</mn> <mspace style="background-color: yellow" id="thespace" height="0.1ex" depth="0.1ex" width="0.1em" /> <mi>x</mi> </mrow> </msqrt> </mstyle> </math> </p> JavaScript Content var height=0; var width=0; var depth=0; function upheight() { height++; document.
getElementById("thespace").setAttribute("height",height+".1ex"); } function downheight() { height--; document.
getElementById("thespace").setAttribute("height",height+".1ex"); } function upwidth() { width++; document.
getElementById("thespace").setAttribute("width",width+".1em"); } function downwidth() { width--; document.
getElementById("thespace").setAttribute("width",width+".1em"); } function updept...
...eight",height+".1ex"); } function downheight() { height--; document.
getElementById("thespace").setAttribute("height",height+".1ex"); } function upwidth() { width++; document.
getElementById("thespace").setAttribute("width",width+".1em"); } function downwidth() { width--; document.
getElementById("thespace").setAttribute("width",width+".1em"); } function updepth() { depth++; document.
getElementById("thespace").setAttribute("depth",depth+".1ex"); } function downdepth() { depth--; document.
getElementById("thespace").setAttribute("depth",depth+".1ex"); } ...
Mozilla DOM Hacking Guide
argument in a wrapper that will be of the type expected by our C++ function. Similarly, then return type of the C++ function will be wrapped by XPConnect so that JavaScript can use it safely. When, in JavaScript, a client tries to access a DOM object or a DOM method on a DOM object, the JS engine asks XPConnect to search for the relevant C++ method to call. For example, when we ask for |document.
getElementById("myID");|, XPConnect will find that |document| is a property of the window object, so it will look on the interface nsIDOMWindow, and it will find the GetDocument() method. The return value of GetDocument() is a nsIDOMDocument. So XPConnect will then try to find a method named
GetElementById() on the nsIDOMDocument interface. And indeed it will find it, and thus call it. This is the schema used ...
...itialized in nsDOMClassInfo::Init(), 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...
Mozilla Web Developer FAQ
ument objects such as document.all and document.layers are not part of the W3C DOM and are not supported in Mozilla. (There is partial undetectable support for document.all, though, in newer versions of Mozilla. However, that functionality only exists for compatibility with sites authored specifically for IE. You should not rely on Mozilla's document.all support on new pages.) The method document.
getElementById() can be used instead. In the Standards mode Mozilla does not generate implicit top-level JavaScript variable bindings for elements with the id or name attribute. The correct way to access an element by id is to call the document.
getElementById() method with the id as a string as the argument. Also, old client sniffers can shut out new browsers. The point of having a common API (the W3C DOM) is...
...entById() method with the id as a string as the argument. Also, old client sniffers can shut out new browsers. The point of having a common API (the W3C DOM) is interoperability, and checking for a particular browser defeats that purpose. When working with the DOM, it is better to check for the existence of the methods and objects you are planning on using. For example, the existence of document.
getElementById() can be checked as follows: if(document.
getElementById) { /* code that uses document.
getElementById() */ } Why doesn't Mozilla display my alt tooltips? Contrary to a popular belief stemming from the behavior of a couple browsers running on the Windows platform, alt isn't an abbreviation for 'tooltip' but for 'alternative'. The value of the alt attribute is a textual replacement for the im...
Scroll-linked effects
t, something we want to avoid. Below are a couple of examples of effects that would not work well with asynchronous scrolling, along with equivalent versions that would work well: Example 1: Sticky positioning Here is an implementation of a sticky-positioning effect, where the "toolbar" div will stick to the top of the screen as you scroll down. <body style="height: 5000px" onscroll="document.
getElementById('toolbar').style.top = Math.max(100, window.scrollY) + 'px'"> <div id="toolbar" style="position: absolute; top: 100px; width: 100px; height: 20px; background-color: green"></div> </body> This implementation of sticky positioning relies on the scroll event listener to reposition the "toolbar" div. As the scroll event listener runs in the JavaScript on the browser's main thread, it will be asynch...
...If it is, then it triggers an animation to "snap" the ...
Components.utils.cloneInto
If you pass the {wrapReflectors:true} flag, then the object you clone is allowed to contain these objec...
... ...
nsIMacDockSupport
ribute('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.
getElementById("menu_mac_dockmenu");66 let nativeMenu = Cc["@mozilla.org/widget/standalonenativemenu;1"].createInstance(Ci.nsIStandaloneNativeMenu); console.log('dockMenuElement:', dockMenuElement); nativeMenu.init(dockMenuElement); dockSupport.dockMenu = nativeMenu; This replaces the default menu wit...
...Two types of elements: menu (if you would like to have sub menu items, make sure to set a label on the "menu" element) menuitem (like in example above) Elements can be hidden by adding the hidden attribute to the menu or menuitem and setting it to...
Using popup notifications
licking on the notification icon again. Implementing a timeout function for the popup notification You can use a timeout to make your notification automatically disappear after some amount of time, by calling notification.remove() as shown below. ...
...ction for the popup notification You can use a timeout to make your notification automatically disappear after some amount of time, by calling notification.remove() as shown below. ...
Flash Activation: Browser Comparison - Plugins
sed. Even if the plugin element will eventually be hidden, pages should create the plugin element so that it's visible on the page, and should resize or hide it only after the user has activated the plugin. ...
...r HTML with a callback that calls the JavaScript function pluginCreated(), like this: <object type="application/x-my-plugin" data="somedata.mytype" id="myPlugin"> <param name="callback" value="pluginCreated()"> </object> The pluginCreated() function is then responsible for the setup of your script and any calls back into the plugin that you need to make: function pluginCreated() { document.
getElementById('myPlugin').callPluginMethod(); } ...
Browser Console - Firefox Developer Tools
h the command Ctrl + Alt + R (Windows, Linux) or Cmd + Alt + R (Mac) This command restarts the browser with the same tabs open as before the restart. Modifying the browser UI Since the global window object is the browser's chrome window, you can also modify the browser's user interface. ...
... = window.document.
getElementById("appmenuPrimaryPane"); var makeTheTea = gBrowser.ownerDocument.defaultView.document.createElementNS("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "menuitem"); makeTheTea.setAttribute("label", "A nice cup of tea?"); parent.appendChild(makeTheTea); On macOS, this similar code will add a new item to the "Tools" menu: var parent = window.document.
getElementById("menu_ToolsPopup"); var makeTheTea = gBrowser.ownerDocument.defaultView.document.createElementNS("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "menuitem"); makeTheTea.setAttribute("label", "A nice cup of tea?"); parent.appendChild(makeTheTea); ...
The JavaScript input interpreter - Firefox Developer Tools
ssion you want, press Enter (Return) to execute the statement. Working with iframes If a page contains embedded iframes, you can use the cd() function to change the console's scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. ...
...cope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. ...
Background Tasks API - Web APIs
ting to be run. totalTaskCount is a counter of the number of tasks that have been added to the queue; it will only go up, never down. We use this to do the math to present progress as a precentage of total work to do. currentTaskNumber is used to track how many tasks have been processed so far. taskHandle is a reference to the task currently being processed. let totalTaskCountElem = document.
getElementById("totalTaskCount"); let currentTaskNumberElem = document.
getElementById("currentTaskNumber"); let progressBarElem = document.
getElementById("progress"); let startButtonElem = document.
getElementById("startButton"); let logElem = document.
getElementById("log"); Next we have variables which reference the DOM elements we need to interact with. These elements are: totalTaskCountElem is the <span>...
... This example will create a random number of tasks (between 100 and 20...
CanvasRenderingContext2D.addHitRegion() - Web APIs
ccessibility tools to use as a description of the region, if there is no 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. ...
...ode" style="height:250px"> ctx.beginPath(); ctx.arc(100, 100, 75, 0, 2 * Math.PI, false); ctx.lineWidth = 5; ctx.stroke(); // eyes ctx.beginPath(); ctx.arc(70, 80, 10, 0, 2 * Math.PI, false); ctx.arc(130, 80, 10, 0, 2 * Math.PI, false); ctx.fill(); ctx.addHitRegion({id: "eyes"}); // mouth ctx.beginPath(); ctx.arc(100, 110, 50, 0, Math.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()...
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
cp2x The x-axis coordinate of the second control point. cp2y The y-axis coordinate of the second control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How bezierCurveTo works This example shows how a cubic Bezier curve is drawn. ...
... control points are red and the start and end points are blue. A simple Bezier curve This example draws a simple Bezier curve using bezierCurveTo(). HTML <canvas id="canvas"></canvas> JavaScript The curve begins at the point specified by moveTo(): (30, 30). The first control point is placed at (120, 160), and the second at (180, 10). The curve ends at (220, 140). const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(30, 30); ctx.bezierCurveTo(120,160, 180,10, 220,140); ctx.stroke(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.beziercurveto' in that specification. Living Standard ...
CanvasRenderingContext2D.clearRect() - Web APIs
o the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples Erasing the whole canvas This code snippet erases the entire canvas. This is commonly required at the start of each frame in an animation. The dimensions of the cleared area are set to equal the <canvas> element's width and height attributes. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); Erasing part of a canvas This example draws a blue triangle on top of a yellowish background. The clearRect() method then erases part of the canvas. HTML <canvas id="canvas"></canvas> JavaScript The cleared area is rectangular in shape, with its top-left corner at (10, 10). The cleared area ha...
...0, 0, canvas.width, canvas.height); Erasing part of a canvas This example draws a blue triangle on top of a yellowish background. The clearRect() method then erases part of the canvas. HTML <canvas id="canvas"></canvas> JavaScript The cleared area is rectangular in shape, with its top-left corner at (10, 10). The cleared area has a width of 120 and a height of 100. ...
CanvasRenderingContext2D.clip() - Web APIs
n. Examples A simple clipping region This example uses the clip() method to create a clipping region according to the shape of a circular arc. Two rectangles are then drawn; only those parts within the clipping region are rendered. HTML <canvas id="canvas"></canvas> JavaScript The clipping region is a full circle, with its center at (100, 75), and a radius of 50. ...
..., 0, 100, 100); Result Specifying a path and a fillRule This example saves two rectangles to a Path2D object, which is then made the current clipping region using the clip() method. The "evenodd" rule creates a hole where the clipping rectangles intersect; by default (with the "nonzero" rule), there would be no hole. ...
CanvasRenderingContext2D.closePath() - Web APIs
mples Closing a triangle This example creates the first two (diagonal) sides of a triangle using the lineTo() method. After that, the triangle's base is created with the closePath() method, which automatically connects the shape's first and last points. HTML <canvas id="canvas"></canvas> JavaScript The triangle's corners are at (20, 150), (120, 20), and (220, 150). ...
...tx.stroke(); Result Closing just one sub-path This example draws a smiley face consisting of three disconnected sub-paths. Note: Although closePath() is called after all the arcs have been created, only the last arc (sub-path) gets closed. HTML <canvas id="canvas"></canvas> JavaScript The first two arcs create the face's eyes. The last arc creates the mouth. ...
CanvasRenderingContext2D.createImageData() - Web APIs
ageData object This snippet creates a blank ImageData object using the createImageData() method. HTML <canvas id="canvas"></canvas> JavaScript The generated object is 100 pixels wide and 50 pixels tall, making 5,000 pixels in all. Each pixel within an ImageData object consists of four array values, so the object's data property has a length of 4 x 5,000, or 20,000. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); const imageData = ctx.createImageData(100, 50); console.log(imageData); // ImageData { width: 100, height: 50, data: Uint8ClampedArray[20000] } Filling a blank ImageData object This example creates and fills a new ImageData object with purple pixels. HTML <canvas id="canvas"></canvas> JavaScript Since each pixel consists of four values, the...
...ampedArray[20000] } Filling a blank ImageData object This example creates and fills a new ImageData object with purple pixels. HTML <canvas id="canvas"></canvas> JavaScript Since each pixel consists of four values, the for loop iterates by multiples of four. The array values associated with each pixel are R (red), G (green), B (blue), and A (alpha), in that order. ...
CanvasRenderingContext2D.drawImage() - Web APIs
vas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/db/f374e9c6fc.jpg" width="300" height="227"> </div> JavaScript The source image is taken from the coordinates (33, 71), with a width of 104 and a height of 124. 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 s...
...l size parameters in its constructor, you will have to use the naturalWidth and naturalHeight properties of the created instance to properly calculate things like crop and scale regions, rather than element.width and element.height. The same goes for videoWidth and videoHeight if the element is a <video> element, and so on. ...
CanvasRenderingContext2D.ellipse() - Web APIs
the ellipse anticlockwise (counter-clockwise). The default value is false (clockwise). Examples Drawing a full ellipse This example draws an ellipse at an angle of ?/4 radians (45?). To make a full ellipse, the arc begins at an angle of 0 radians (0?), and ends at an angle of 2? radians (360?). ...
...ath(); ctx.ellipse(100, 100, 50, 75, Math.PI / 4, 0, 2 * Math.PI); ctx.stroke(); // Draw the ellipse's line of reflection ctx.beginPath(); ctx.setLineDash([5, 5]); ctx.moveTo(0, 200); ctx.lineTo(200, 0); ctx.stroke(); Result Various elliptical arcs This example creates three elliptical paths with varying properties. ...
CanvasRenderingContext2D.fill() - Web APIs
The algorithm by which to determine if a point is inside or outside the filling region. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to fill. Examples Filling a rectangle This example fills a rectangle with the fill() method. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.fill(); Result Specifying a path and a fillRule This example saves some intersecting lines to a Path2D object. The fill() method is then used to render the object to the canvas. A hole is left unfilled in the object's center by using the "evenodd" rule; by default (with the "nonzero" rule), the hole would also b...
...(); Result Specifying a path and a fillRule This example saves some intersecting lines to a Path2D object. The fill() method is then used to render the object to the canvas. A hole is left unfilled in the object's center by using the "evenodd" rule; by default (with the "nonzero" rule), the hole would also be filled. ...
CanvasRenderingContext2D.fillRect() - Web APIs
to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples A simple filled rectangle This example draws a filled green rectangle using the fillRect() method. HTML <canvas id="canvas"></canvas> JavaScript The rectangle's top-left corner is at (20, 10). It has a width of 150 and a height of 100. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'green'; ctx.fillRect(20, 10, 150, 100); Result Filling the whole canvas This code snippet fills the entire canvas with a rectangle. This is often useful for creating a background, on top of which other things may then be drawn. To achieve this, the dimensions of the rectangle are set to equal the <canvas> element's width and h...
...2d'); ctx.fillStyle = 'green'; ctx.fillRect(20, 10, 150, 100); Result Filling the whole canvas This code snippet fills the entire canvas with a rectangle. This is often useful for creating a background, on top of which other things may then be drawn. To achieve this, the dimensions of the rectangle are set to equal the <canvas> element's width and height attributes. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillRect(0, 0, canvas.width, canvas.height); Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.fillRect' in that specification. Living Standard ...
CanvasRenderingContext2D.fillStyle - Web APIs
yle = gradient; ctx.fillStyle = pattern; Options color A DOMString parsed as CSS <color> value. gradient A CanvasGradient object (a linear or radial gradient). pattern A CanvasPattern object (a repeating image). Examples Changing the fill color of a shape This example applies a blue fill color to a rectangle. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'blue'; ctx.fillRect(10, 10, 100, 100); Result Creating multiple fill colors using loops In this example, we use two for loops to draw a grid of rectangles, each having a different fill color. To achieve this, we use the two variables i and j to generate a unique RGB color for each square, and only modify the red and green val...
...loops to draw a grid of rectangles, each having a different fill color. To achieve this, we use the two variables i and j to generate a unique RGB color for each square, and only modify the red and green values. (The blue channel has a fixed value.) By modifying the channels, you can generate all kinds of palettes. ...
CanvasRenderingContext2D.fillText() - Web APIs
ecified width. Return value undefined. Examples Drawing filled text This example writes the words "Hello world" using the fillText() method. HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels across. <canvas id="canvas" width="400" height="150"></canvas> JavaScript The JavaScript code for this example follows. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.fillText('Hello world', 50, 90); This code obtains a reference to the <canvas>, then gets a reference to its 2D graphics context. With that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call fillText() to draw the text "Hello world," starting at the coordinates (50, 90). Res...
... that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call fillText() to draw the text "Hello world," starting at the coordinates (50, 90). Result Restricting the text size This example writes the words "Hello world," restricting its width to 140 pixels. HTML <canvas id="canvas" width="400" height="150"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.fillText('Hello world', 50, 90, 140); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.fillText' in that specification. Living Standard ...
CanvasRenderingContext2D.globalAlpha - Web APIs
(fully transparent) and 1.0 (fully opaque), inclusive. The default value is 1.0. Values outside that range, including Infinity and NaN, will not be set, and globalAlpha will retain its previous value. Examples Drawing translucent shapes This example uses the globalAlpha property to draw two semi-transparent rectangles. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.globalAlpha = 0.5; ctx.fillStyle = 'blue'; ctx.fillRect(10, 10, 100, 100); ctx.fillStyle = 'red'; ctx.fillRect(50, 50, 100, 100); Result Overlaying transparent shapes This example illustrates the effect of overlaying multiple transparent shapes on top of each other. We begin by drawing a solid background composed of four differently col...
... we use a for loop to draw a series of circles with increasing radii. With each new circle, the opacity of the previous circles underneath is effectively increased. If we were to increase the step count (and thus draw more circles), the background would eventually disappear completely from the center of the image. ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
turn value Boolean A Boolean, which is true if the specified point is contained in the current or specified path, otherwise false. Examples Checking a point in the current path This example uses the isPointInPath() method to check if a point is within the current path. HTML <canvas id="canvas"></canvas> <p>In path: <code id="result">false</code></p> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); const result = document.
getElementById('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innerText = ctx.isPointInPath(30, 70); Result Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in a circular Path2D path. If yes, the circle becomes green, otherwise it is red. HTML <c...
...cument.
getElementById('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innerText = ctx.isPointInPath(30, 70); Result Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in a circular Path2D path. If yes, the circle becomes green, otherwise it is red. ...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
Boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. Examples Checking a point in the current path This example uses the isPointInStroke() method to check if a point is within the area of the current path's stroke. HTML <canvas id="canvas"></canvas> <p>In stroke: <code id="result">false</code></p> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); const result = document.
getElementById('result'); ctx.rect(10, 10, 100, 100); ctx.stroke(); result.innerText = ctx.isPointInStroke(50, 10); Result Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical Path2D path. If yes, the ellipse's stroke becomes green,...
...; ctx.rect(10, 10, 100, 100); ctx.stroke(); result.innerText = ctx.isPointInStroke(50, 10); Result Checking a point in the specified path Whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical Path2D path. If yes, the ellipse's stroke becomes green, otherwise it is red. ...
CanvasRenderingContext2D.lineCap - Web APIs
s of lines are squared off at the endpoints. Default value. "round" The ends of lines are rounded. "square" The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. Examples Changing the shape of line caps This example rounds the end caps of a straight line. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineWidth = 15; ctx.lineCap = 'round'; ctx.lineTo(100, 100); ctx.stroke(); Result Comparison of line caps In this example three lines are drawn, each with a different value for the lineCap property. Two guides to see the exact differences between the three are added. Each of these lines starts and ends...
...ault "butt" option. It's drawn completely flush with the guides. The second is set to use the "round" option. This adds a semicircle to the end that has a radius half the width of the line. The line on the right uses the "square" option. This adds a box with an equal width and half the height of the line thickness. ...
CanvasRenderingContext2D.lineDashOffset - Web APIs
Note: Lines are drawn by calling the stroke() method. Syntax ctx.lineDashOffset = value; value A float specifying the amount of the line dash offset. The default value is 0.0. Examples Offsetting a line dash This example draws two dashed lines. The first has no dash offset. The second has a dash offset of 4. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setLineDash([4, 16]); // Dashed line with no offset ctx.beginPath(); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke(); // Dashed line with offset of 4 ctx.beginPath(); ctx.strokeStyle = 'red'; ctx.lineDashOffset = 4; ctx.moveTo(0, 100); ctx.lineTo(300, 100); ctx.stroke(); Result The line with a dash offset is drawn in red. Marching ...
...0, 100); ctx.lineTo(300, 100); ctx.stroke(); Result The line with a dash offset is drawn in red. Marching ants The marching ants effect is an animation technique often found in selection tools of computer graphics programs. It helps the user to distinguish the selection border from the image background by animating the border. ...
CanvasRenderingContext2D.lineJoin - Web APIs
"miter" Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. This setting is affected by the miterLimit property. Default value. Examples Changing the joins in a path This example applies rounded line joins to a path. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.lineWidth = 20; ctx.lineJoin = 'round'; ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(190, 100); ctx.lineTo(280, 20); ctx.lineTo(280, 150); ctx.stroke(); Result Comparison of line joins The example below draws three different paths, demonstrating each of the three lineJoin options. <canvas id="canvas" width="150" height="150"></canvas...
... canvas.getContext('2d'); ctx.lineWidth = 20; ctx.lineJoin = 'round'; ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(190, 100); ctx.lineTo(280, 20); ctx.lineTo(280, 150); ctx.stroke(); Result Comparison of line joins The example below draws three different paths, demonstrating each of the three lineJoin options. ...
CanvasRenderingContext2D.lineTo() - Web APIs
s. Syntax ctx.lineTo(x, y); Parameters x The x-axis coordinate of the line's end point. y The y-axis coordinate of the line's end point. Return value undefined. Examples Drawing a straight line This example draws a straight line using the lineTo() method. HTML <canvas id="canvas"></canvas> JavaScript The line begins at (30, 50) and ends at (150, 100). ...
...raw a line to (150, 100) ctx.stroke(); // Render the path Result Drawing connected lines Each call of lineTo() (and similar methods) automatically adds to the current sub-path, which means that all the lines will all be stroked or filled together. This example draws a letter 'M' with a single contiguous line. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.moveTo(90, 130); ctx.lineTo(95, 25); ctx.lineTo(150, 80); ctx.lineTo(205, 25); ctx.lineTo(210, 130); ctx.lineWidth = 15; ctx.stroke(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.lineTo' in that specification. Living Standard ...
CanvasRenderingContext2D.quadraticCurveTo() - Web APIs
urveTo(cpx, cpy, x, y); Parameters cpx The x-axis coordinate of the control point. cpy The y-axis coordinate of the control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How quadraticCurveTo works This example shows how a quadratic Bezier curve is drawn. ...
... In this example, the control point is red and the start and end points are blue. A simple quadratic curve This example draws a simple quadratic Bezier curve using quadraticCurveTo(). HTML <canvas id="canvas"></canvas> JavaScript The curve begins at the point specified by moveTo(): (20, 110). The control point is placed at (230, 150). The curve ends at (250, 20). const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(20, 110); ctx.quadraticCurveTo(230, 150, 250, 20); ctx.stroke(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.quadraticCurveTo' in that specification. Living Standard ...
CanvasRenderingContext2D.resetTransform() - Web APIs
setTransform(); Examples Resetting the matrix This example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resetTransform() method. HTML <canvas id="canvas"></canvas> JavaScript The rotate() method rotates the transformation matrix by 45?. The fillRect() method draws a filled rectangle, adjusted according to that matrix. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Draw a rotated rectangle ctx.rotate(45 * Math.PI / 180); ctx.fillRect(60, 0, 100, 30); // Reset transformation matrix to the identity matrix ctx.resetTransform(); Result Continuing with a regular matrix Whenever you're done drawing transformed shapes, you should call resetTransform() before rendering anything else. In this example, the fi...
...resetTransform(); Result Continuing with a regular matrix Whenever you're done drawing transformed shapes, you should call resetTransform() before rendering anything else. In this example, the first two shapes are drawn with a skew transformation, and the last two are drawn with the identity (regular) transformation. ...
CanvasRenderingContext2D.rotate() - Web APIs
ation center point is always the canvas origin. To change the center point, you will need to move the canvas by using the translate() method. Examples Rotating a shape This example rotates a rectangle by 45?. Note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. ...
.... This is done by applying the values of the shape's center coordinates in a negative direction. HTML <canvas id="canvas"></canvas> JavaScript The shape is a rectangle with its corner at (80, 60), a width of 140, a height of 30. Its horizontal center is at (80 + 140 / 2), or 150. Its vertical center is at (60 + 30 / 2), or 75. Thus, the center point is at (150, 75). const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Non-rotated rectangle ctx.fillStyle = 'gray'; ctx.fillRect(80, 60, 140, 30); // Matrix transformation ctx.translate(150, 75); ctx.rotate(Math.PI / 2); ctx.translate(-150, -75); // Rotated rectangle ctx.fillStyle = 'red'; ctx.fillRect(80, 60, 140, 30); Result The non-rotated rectangle is gray, and the rotated rectangle is red. Specificati...
CanvasRenderingContext2D.scale() - Web APIs
L <canvas id="canvas"></canvas> JavaScript The rectangle has a specified width of 8 and a height of 20. The transformation matrix scales it by 9x horizontally and by 3x vertically. Thus, its final size is a width of 72 and a height of 60. Notice that its position on the canvas also changes. Since its specified corner is (10, 10), its rendered corner becomes (90, 30). const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Scaled rectangle ctx.scale(9, 3); ctx.fillStyle = 'red'; ctx.fillRect(10, 10, 8, 20); // Reset current transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0); // Non-scaled rectangle ctx.fillStyle = 'gray'; ctx.fillRect(10, 10, 8, 20); Result The scaled rectangle is red, and the non-scaled rectangle is gray. Flip...
...lip the context horizontally and scale(1, -1) to flip it vertically. In this example, the words "Hello world!" are flipped horizontally. Note that the call to fillText() specifies a negative x coordinate. This is to adjust for the negative scaling factor: -280 * -1 becomes 280, and text is drawn leftwards from that point. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.scale(-1, 1); ctx.font = '48px serif'; ctx.fillText('Hello world!', -280, 90); ctx.setTransform(1, 0, 0, 1, 0, 0); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.scale' in that specification. Living Standard ...
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
as 2D API scrolls the current or given path into view. It is similar to Element.scrollIntoView(). Syntax void ctx.scrollPathIntoView(); void ctx.scrollPathIntoView(path); Parameters path A Path2D path to use. Examples Using the scrollPathIntoView method This example demonstrates the scrollPathIntoView() method. ...
...vas" width="400" height="200" class="playable-canvas"> <input id="button" type="range" min="1" max="12"> </canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginPath(); ctx.rect(10, 10, 30, 30); 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()...
CanvasRenderingContext2D.setLineDash() - Web APIs
ray get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. If the array is empty, the line dash list is cleared and line strokes return to being solid. Return value undefined. Examples Basic example This example uses the setLineDash() method to draw a dashed line above a solid line. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Dashed line ctx.beginPath(); ctx.setLineDash([5, 15]); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke(); // Solid line ctx.beginPath(); ctx.setLineDash([]); ctx.moveTo(0, 100); ctx.lineTo(300, 100); ctx.stroke(); Result Some common patterns This example illustrates a variety of common line dash patterns. HTML <canvas id="canvas"></c...
...mon line dash patterns. HTML <canvas id="canvas"></canvas> JavaScript The drawDashedLine() function created below makes the drawing of multiple dashed lines simple. It receives a pattern array as its only parameter. ...
CanvasRenderingContext2D.shadowColor - Web APIs
r> value. The default value is fully-transparent black. Examples Adding a shadow to shapes This example adds a shadow to two squares; the first one is filled, and the second one is stroked. The shadowColor property sets the shadows' color, while shadowOffsetX and shadowOffsetY set their position relative to the shapes. ...
... A shadow's opacity is affected by the transparency level of its parent object (even when shadowColor specifies a completely opaque value). This example strokes and fills a rectangle with translucent colors. HTML <canvas id="canvas"></canvas> JavaScript The resulting alpha value of the fill shadow is .8 * .2, or .16. The alpha of the stroke shadow is .8 * .6, or .48. ...
CanvasRenderingContext2D.strokeRect() - Web APIs
ht, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples A simple stroked rectangle This example draws a rectangle with a green outline using the strokeRect() method. HTML <canvas id="canvas"></canvas> JavaScript The rectangle's top-left corner is at (20, 10). It has a width of 160 and a height of 100. ...
..., 10). It has a width of 160 and a height of 100. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.strokeStyle = 'green'; ctx.strokeRect(20, 10, 160, 100); Result Applying various context settings This example draws a rectangle with a drop shadow and thick, beveled outlines. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.shadowColor = '#d53'; ctx.shadowBlur = 20; ctx.lineJoin = 'bevel'; ctx.lineWidth = 15; ctx.strokeStyle = '#38f'; ctx.strokeRect(30, 30, 160, 90); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.strokeRect' in that specification. Living Standard ...
CanvasRenderingContext2D.strokeStyle - Web APIs
= gradient; ctx.strokeStyle = pattern; Options color A DOMString parsed as CSS <color> value. gradient A CanvasGradient object (a linear or radial gradient). pattern A CanvasPattern object (a repeating image). Examples Changing the stroke color of a shape This example applies a blue stroke color to a rectangle. HTML <canvas id="canvas"></canvas> JavaScript var canvas = document.
getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.strokeStyle = 'blue'; ctx.strokeRect(10, 10, 100, 100); Result Creating multiple stroke colors using loops In this example, we use two for loops and the arc() method to draw a grid of circles, each having a different stroke color. To achieve this, we use the two variables i and j to generate a unique RGB color for each circle, and only modi...
...colors using loops In this example, we use two for loops and the arc() method to draw a grid of circles, each having a different stroke color. To achieve this, we use the two variables i and j to generate a unique RGB color for each circle, and only modify the green and blue values. ...
CanvasRenderingContext2D.strokeText() - Web APIs
ied width. Return value undefined. Examples Drawing text outlines This example writes the words "Hello world" using the strokeText() method. HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels high. <canvas id="canvas" width="400" height="150"></canvas> JavaScript The JavaScript code for this example follows. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Hello world', 50, 90); This code obtains a reference to the <canvas>, then gets a reference to its 2D graphics context. With that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call strokeText() to draw the text "Hello world," starting at the coordinates (50, 90). ...
...hat in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call strokeText() to draw the text "Hello world," starting at the coordinates (50, 90). Result Restricting the text size This example writes the words "Hello world," restricting its width to 140 pixels. HTML <canvas id="canvas" width="400" height="150"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Hello world', 50, 90, 140); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.strokeText' in that specification. Living Standard ...
CanvasRenderingContext2D.textAlign - Web APIs
es). "end" The text is aligned at the normal end of the line (right-aligned for left-to-right locales, left-aligned for right-to-left locales). The default value is "start". Examples General text alignment This example demonstrates the three "physical" values of the textAlign property: "left", "center", and "right". ...
...ht'; ctx.fillText('right-aligned', x, 130); Result Direction-dependent text alignment This example demonstrates the two direction-dependent values of the textAlign property: "start" and "end". Note that the direction property is manually specified as "ltr", although this is also the default for English-language text. ...
Canvas API - Web APIs
an be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing. The Canvas API largely focuses on 2D graphics. The WebGL API, which also uses the <canvas> element, draws hardware-accelerated 2D and 3D graphics. Basic example This simple example draws a green rectangle onto a canvas. HTML <canvas id="canvas"></canvas> JavaScript The Document.
getElementById() method gets a reference to the HTML <canvas> element. Next, the HTMLCanvasElement.getContext() method gets that element's context--the thing onto which the drawing will be rendered. The actual drawing is done using the CanvasRenderingContext2D interface. The fillStyle property makes the rectangle green. The fillRect() method places its top-left corner at (10, 10), and gives it a size of 150 un...
... element. Next, the HTMLCanvasElement.getContext() method gets that element's context--the thing onto which the drawing will be rendered. The actual drawing is done using the CanvasRenderingContext2D interface. The fillStyle property makes the rectangle green. The fillRect() method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall. ...
Using channel messaging - Web APIs
he main page and an IFrame. We'll be focusing on the latter example in this article. It looks like so: Creating the channel In the main page of the demo, we have a simple form with a text input for entering messages to be sent to an <iframe>. We also have a paragraph which we will use later on to display confirmation messages that we will receive back from the <iframe>. ...
...atter example in this article. It looks like so: Creating the channel In the main page of the demo, we have a simple form with a text input for entering messages to be sent to an <iframe>. We also have a paragraph which we will use later on to display confirmation messages that we will receive back from the <iframe>. ...
DataTransfer.clearData() - Web APIs
="status">Drag to start</span></div> <div>Data is: <span id="data">uninitialized</span></div> CSS span.tweaked { display: inline-block; margin: 1em 0; padding: 1em 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } JavaScript window.addEventListener('DOMContentLoaded', function () { // Select HTML elements var draggable = document.
getElementById('source'); var dropable = document.
getElementById('target'); var status = document.
getElementById('status'); var data = document.
getElementById('data'); var dropped = false; // Register event handlers draggable.addEventListener('dragstart', dragStartHandler); draggable.addEventListener('dragend', dragEndHandler); dropable.addEventListener('dragover', dragOverHandler); dropable.
...t(); } function dragLeaveHandler (event) { status.innerHTML = 'Drag in process (drop was available)'; event.preventDefault(); } function dropHandler (event) { dropped = true; status.innerHTML = 'Drop done'; event.preventDefault(); // Get data linked to event format << text >> var _data = event.dataTransfer.getData('text/plain'); var element = document.
getElementById(_data); // Append drag source element to event's target element event.target.appendChild(element); // Change CSS styles and displayed text element.style.cssText = 'border: 1px solid black;display: block; color: red'; element.innerHTML = "I'm in the Drop Zone!"; } }) Specifications Specification Status Comment HTML Living StandardThe definition ...
DataTransfer.getData() - Web APIs
Living Standard HTML 5.1The definition of 'getData()' in that specification. Recommendation Initial definition ...
... Living Standard HTML 5.1The definition of 'getData()' in that specification. Recommendation Initial definition ...
DataTransferItem.webkitGetAsEntry() - Web APIs
g an entry in the file system to be scanned and processed (the item parameter), and an element into which to insert the list of contents (the container parameter). Note that to read all files in a directory, readEntries needs to be called repeatedly until it returns an empty array. In Chromium-based browsers, the following example will only return a max of 100 entries. ...
...cessed (the item parameter), and an element into which to insert the list of contents (the container parameter). Note that to read all files in a directory, readEntries needs to be called repeatedly until it returns an empty array. In Chromium-based browsers, the following example will only return a max of 100 entries. ...
Document.getElementsByTagName() - Web APIs
ested <div> elements). ...
...p'); var num = allParas.length; alert('There are ' + num + ' paragraph in this document'); } function div1ParaElems() { var div1 = document.
getElementById('div1'); var div1Paras = div1.getElementsByTagName('p'); var num = div1Paras.length; alert('There are ' + num + ' paragraph in #div1'); } function div2ParaElems() { var div2 = document.
getElementById('div2'); var div2Paras = div2.getElementsByTagName('p'); var num = div2Paras.length; alert('There are ' + num + ' paragraph in #div2'); } </script> </head> <body style="border: solid green 3px"> <p>Some outer text</p> <p>Some outer text</p> <div id="div1" style="border: solid blue 3px"> <p>Some div1 text</p> <p>Some div1 text</p> <p>Some div1 text</p> ...
DocumentOrShadowRoot.activeElement - Web APIs
laoreet diam. ...
...tive element ID: <b id="output-element"></b></p> <p>Selected text: <b id="output-text"></b></p> JavaScript function onMouseUp(e) { const activeTextarea = document.activeElement; const selection = activeTextarea.value.substring( activeTextarea.selectionStart, activeTextarea.selectionEnd ); const outputElement = document.
getElementById('output-element'); const outputText = document.
getElementById('output-text'); outputElement.innerHTML = activeTextarea.id; outputText.innerHTML = selection; } const textarea1 = document.
getElementById('ta-example-one'); const textarea2 = document.
getElementById('ta-example-two'); textarea1.addEventListener('mouseup', onMouseUp, false); textarea2.addEventListener('mouseup', onMouseUp, false); Result Specifications Specification Status ...
Introduction to the DOM - Web APIs
e DOM is concerned, a node in the tree of nodes that make up the object model for an HTML or XML page, the table object also implements the more basic Node interface, from which Element derives. When you get a reference to a table object, as in the following example, you routinely use all three of these interfaces interchangeably on the object, perhaps without knowing it. ...
...the generic Node interface, and together these two interfaces provide many of the methods and properties you use on individual elements. These elements may also have specific interfaces for dealing with the kind 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...
EffectTiming.fill - Web APIs
should be in before the animation 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. ...
... 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. document.
getElementById("animateButton").addEventListener("click", event => { document.
getElementById("box").animate( boxRotationKeyframes, boxRotationTiming ); }, false); The rest of the code is pretty simple: it adds an event listener to the "Animate" button so that when it's clicked by the user, the box is animated by calling Element.animate() on it, providing the boxRotationKeyframes and boxRotationTiming objects to describe the animation that should occur. Result Below we see wh...
Element.attributes - Web APIs
attributes Numerical indexing is useful for going through all of an element's attributes. The following example runs through the attribute nodes for the element in the document with id "paragraph", and prints each attribute's value. ...
...gh all of an element's attributes. The following example runs through the attribute nodes for the element in the document with id "paragraph", and prints each attribute's value. ...
Element.getAttributeNS() - Web APIs
e foo attribute in a custom namespace. <svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="Hello namespaced attribute!"/> <script type="text/javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.
getElementById( 'target' ); console.log( 'attribute test:foo: "' + circle.getAttributeNS( ns, 'foo' ) + '"' ); </script> </svg> In an HTML5 document the attribute has to be accessed with test:foo since namespaces are not supported. <!DOCTYPE html> <html> <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="1...
...spaces are not supported. <!DOCTYPE html> <html> <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="Foo value"/> </svg> <script type="text/javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.
getElementById( 'target' ); console.log('Attribute value: ' + circle.getAttribute('test:foo')); </script> </body> </html> Notes Namespaces are only supported in XML documents. HTML5 documents have to use getAttribute() instead. getAttributeNS() differs from getAttribute() in that it allows you to further specify the requested attribute as being part of a particular namespace, as in the example above, wher...
Element.hasPointerCapture() - Web APIs
which it is invoked has pointer capture for the pointer identified by the given pointer ID. Syntax targetElement.hasPointerCapture(pointerId); Parameters pointerId The pointerId of a PointerEvent object. Return value A Boolean value -- true if the element does have pointer capture, false if it doesn't. Examples <html> <script> function downHandler(ev) { const el = document.
getElementById("target"); // Element 'target' will receive/capture further events el.setPointerCapture(ev.pointerId); /* ... */ // Check whether element still has pointer capture let pointerCap = el.hasPointerCapture(ev.pointerId); if(pointerCap) { // We've still got pointer capture } else { // oops, we've lost pointer capture! } } funct...
...ill receive/capture further events el.setPointerCapture(ev.pointerId); /* ... */ // Check whether element still has pointer capture let pointerCap = el.hasPointerCapture(ev.pointerId); if(pointerCap) { // We've still got pointer capture } else { // oops, we've lost pointer capture! } } function init() { const el = document.
getElementById("target"); el.onpointerdown = downHandler; } </script> <body onload="init();"> <div id="target">Touch this element with a pointer.</div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'hasPointerCapture()' in that specification. Recommendation ...
Element.localName - Web APIs
name = element.localName Return value A DOMString representing the local part of the element's qualified name. ...
...ring representing the local part of the element's qualified name. ...
Element: mouseenter event - Web APIs
n adds an item to the list with the number of the mouseenter or mouseleave event. HTML <div id='mouseTarget'> <ul id="unorderedList"> <li>No events yet!</li> </ul> </div> CSS Styling the div to make it more visible. ...
...r mouseleave event. HTML <div id='mouseTarget'> <ul id="unorderedList"> <li>No events yet!</li> </ul> </div> CSS Styling the div to make it more visible. ...
Element: mouseleave event - Web APIs
adds an item to the list with the number of the mouseenter or mouseleave event. HTML <div id='mouseTarget'> <ul id="unorderedList"> <li>No events yet!</li> </ul> </div> CSS Styling the <div> to make it more visible. ...
...mouseleave event. HTML <div id='mouseTarget'> <ul id="unorderedList"> <li>No events yet!</li> </ul> </div> CSS Styling the <div> to make it more visible. ...
Comparison of Event Targets - Web APIs
> </thead> <tr> <td id="target"></td> <td id="currentTarget"></td> <td id="relatedTarget"></td> <td id="explicitOriginalTarget"></td> <td id="originalTarget"></td> </tr> </table> <p>Clicking on the text will show the difference between explicitOriginalTarget, originalTarget, and target</p> <script> function handleClicks(e) { document.
getElementById('target').innerHTML = e.target; document.
getElementById('currentTarget').innerHTML = e.currentTarget; document.
getElementById('relatedTarget').innerHTML = e.relatedTarget; document.
getElementById('explicitOriginalTarget').innerHTML = e.explicitOriginalTarget; document.
getElementById('originalTarget').innerHTML = e.originalTarget; } function handleMouseover...
...e.target; document.
getElementById('currentTarget').innerHTML = e.currentTarget; document.
getElementById('relatedTarget').innerHTML = e.relatedTarget; document.
getElementById('explicitOriginalTarget').innerHTML = e.explicitOriginalTarget; document.
getElementById('originalTarget').innerHTML = e.originalTarget; } function handleMouseover(e) { document.
getElementById('target').innerHTML = e.target; document.
getElementById('relatedTarget').innerHTML = e.relatedTarget; } document.addEventListener('click', handleClicks, false); document.addEventListener('mouseover', handleMouseover, false); </script> </body> </html> Use of target and relatedTarget The relatedTarget property for the mouseover event holds the node that the mouse was previous...
Event.defaultPrevented - Web APIs
Example This example logs attempts to visit links from two <a> elements. JavaScript is used to prevent the second link from working. ...
... Living Standard ...
Event.preventDefault() - Web APIs
ntTarget.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. ...
...box"> </form> </div> CSS We use a little bit of CSS for the warning box we'll draw when the user presses an invalid key: .warning { border: 2px solid #f39389; border-radius: 2px; padding: 10px; position: absolute; background-color: #fbd8d4; color: #3b3c40; } JavaScript And here's the JavaScript code that does the job. ...
EventTarget.removeEventListener() - Web APIs
as registered for after being removed. However, it can be reattached. Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. Example This example shows how to add a mouseover-based event listener that removes a click-based event listener. ...
...ched. Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. Example This example shows how to add a mouseover-based event listener that removes a click-based event listener. ...
File.getAsDataURL() - Web APIs
e getAsDataURL provides a data: URL that encodes the entire contents of the referenced file. Note: This method is obsolete; you should use the FileReader method readAsDataURL() instead. ...
... ...
File.webkitRelativePath - Web APIs
r selected. Example In this 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. ...
...one or more directories. When the change event occurs, a list of all files contained within the selected directory hierarchies is generated and displayed. ...
FileList - Web APIs
rue, the FileList may contain multiple files. Using the file list All <input> element nodes have a files attribute of type FileList on them which allows access to the items in this list. For example, if the HTML includes the following file input: <input id="fileItem" type="file"> The following line of code fetches the first file in the node's file list as a File object: var file = document.
getElementById('fileItem').files[0]; Method overview File item(index); Properties Attribute Type Description length integer A read-only value indicating the number of files in the list. Methods item() Returns a File object representing the file at the specified index in the file list. File item( index ); Parameters index The zero-based index...
...d index in the file list. File item( index ); Parameters index The zero-based index of the file to retrieve from the list. Return value The File representing the requested file. Example This example iterates over all the files selected by the user using an input element: // fileInput is an HTML input element: <input type="file" id="myfileinput" multiple> var fileInput = document.
getElementById("myfileinput"); // files is a FileList object (similar to NodeList) var files = fileInput.files; var file; // loop through files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } Here is a complete example. <!DOCTYPE HTML> <html> <head> </head> <body> <!--multiple is set to allow multiple files to be sel...
FileSystemDirectoryReader.readEntries() - Web APIs
g an entry in the file system to be scanned and processed (the item parameter), and an element into which to insert the list of contents (the container parameter). Note that to read all files in a directory, readEntries needs to be called repeatedly until it returns an empty array. In Chromium-based browsers, the following example will only return a max of 100 entries. ...
...cessed (the item parameter), and an element into which to insert the list of contents (the container parameter). Note that to read all files in a directory, readEntries needs to be called repeatedly until it returns an empty array. In Chromium-based browsers, the following example will only return a max of 100 entries. ...
GlobalEventHandlers.onanimationcancel - Web APIs
stopped or the page is closed. JavaScript Before we get to the animation code, we define a function which logs information to a box on the user's screen. We'll use this to show information about the events we receive. Note the use of AnimationEvent.animationName and AnimationEvent.elapsedTime to get information about the event which occurred. function log(msg, event) { let logBox = document.
getElementById("log"); logBox.innerHTML += msg; if (event) { logBox.innerHTML += " <code>"+ event.animationName + "</code> at time " + event.elapsedTime.toFixed(2) + " seconds."; } logBox.innerHTML += "\n"; }; Then we set up the handleCancelEvent() function, which is called in response to the animationcancel event, as set up in the HTML above. All we do here is log information t...
...s log information to the console, 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...
HTMLElement.oncopy - Web APIs
unctionRef is a function name or a function expression. The function receives a ClipboardEvent object as its sole argument. Example This example blocks every copy and paste attempt from the <textarea>. ...
..." rows="3">Try copying and pasting text into this field!</textarea> <h3>Log:</h3> <p id="log"></p> JavaScript const log = document.
getElementById('log'); function logCopy(event) { log.innerText = 'Copy blocked!\n' + log.innerText; event.preventDefault(); } function logPaste(event) { log.innerText = 'Paste blocked!\n' + log.innerText; event.preventDefault(); } const editor = document.
getElementById('editor'); editor.oncopy = logCopy; editor.onpaste = logPaste; Result Specification WHATWG Standard ...
HTMLElement.oncut - Web APIs
cut attempt. ...
...a:</h3> <textarea id="editor" rows="3">Try copying and cutting the text in this field!</textarea> <h3>Log:</h3> <p id="log"></p> JavaScript function logCopy(event) { log.innerText = 'Copied!\n' + log.innerText; } function preventCut(event) { event.preventDefault(); log.innerText = 'Cut blocked!\n' + log.innerText; } const editor = document.
getElementById('editor'); const log = document.
getElementById('log'); editor.oncopy = logCopy; editor.oncut = preventCut; Result Specification WHATWG Standard ...
HTMLElement.onpaste - Web APIs
every copy and paste attempt to the <textarea>. ...
... HTML <h3>Play with this text area:</h3> <textarea id="editor" rows="3">Try copying and pasting text into this field!</textarea> <h3>Log:</h3> <p id="log"></p> JavaScript function logCopy(event) { log.innerText = 'Copied!\n' + log.innerText; } function logPaste(event) { log.innerText = 'Pasted!\n' + log.innerText; } const editor = document.
getElementById('editor'); const log = document.
getElementById('log'); editor.oncopy = logCopy; editor.onpaste = logPaste; Result Specification WHATWG Standard ...
HTMLInputElement.webkitdirectory - Web APIs
r details. Example In this 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. ...
...one or more directories. When the change event occurs, a list of all files contained within the selected directory hierarchies is generated and displayed. ...
HTMLMediaElement.play() - Web APIs
le delay before the returned promise is resolved. Be sure your code doesn't expect an immediate response. For even more in-depth information about autoplay and autoplay blocking, see our article Autoplay guide for media and Web Audio APIs. ...
...e sure your code doesn't expect an immediate response. For even more in-depth information about autoplay and autoplay blocking, see our article Autoplay guide for media and Web Audio APIs. ...
Option() - Web APIs
at a value of true does not set the option to selected if it is not already selected. selected Optional A Boolean that sets the option's selected state; the default is false (not selected). If omitted, even if the defaultSelected argument is true, the option is not selected. ...
...ML <select id='s'> </select> */ var s = document.
getElementById('s'); var options = [Four, Five, Six]; options.forEach(function(element,key) { s[key] = new Option(element,key); }); Append options with different parameters /* assuming we have the following HTML <select id="s"> <option>First</option> <option>Second</option> <option>Third</option> </select> */ var s = document.
getElementById('s'); var options = [ 'zero', 'one', 'two' ]; options.forEach(function(element, key) { if (element == 'zero') { s[s.options.length] = new Option(element, s.options.length, false, false); } if (element == 'one') { s[s.options.length] = new Option(element, s.options.length, true, false); // Will add the "selected" attribute } if (element == 'two') { s[s.options.length] = new ...
HTMLSelectElement.add() - Web APIs
; opt2.text = "Option: Value 2"; sel.add(opt1, null); sel.add(opt2, null); /* Produces the following, conceptually: <select> <option value="1">Option: Value 1</option> <option value="2">Option: Value 2</option> </select> */ The before parameter is optional. So the following is accepted. ... sel.add(opt1); sel.add(opt2); ... ...
...lue="2">Option: Value 2</option> </select> And changes it to: <select id="existingList"> <option value="1">Option: Value 1</option> <option value="2">Option: Value 2</option> <option value="3">Option: Value 3</option> </select> */ The before parameter is optional. So the following is accepted. ... sel.add(opt); ... ...
HTMLSelectElement.selectedIndex - Web APIs
e value -1 indicates that no element is selected. ...
...ed. Syntax var index = selectElem.selectedIndex; selectElem.selectedIndex = index; Example HTML <p id="p">selectedIndex: 0</p> <select id="select"> <option selected>Option A</option> <option>Option B</option> <option>Option C</option> <option>Option D</option> <option>Option E</option> </select> JavaScript var selectElem = document.
getElementById('select') var pElem = document.
getElementById('p') // When a new <option> is selected selectElem.addEventListener('change', function() { var index = selectElem.selectedIndex; // Add that data to the <p> pElem.innerHTML = 'selectedIndex: ' + index; }) Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLSelectElement' in that specification. Living Standard No change si...
HTMLTableElement.insertRow() - Web APIs
The HTMLTableElement.insertRow() method inserts a new row (<tr>) in a given <table>, and returns a reference to the new row. If a table has multiple <tbody> elements, by default, the new row is inserted into the last <tbody>. To insert the row into a specific <tbody>: let specific_tbody = document.
getElementById(tbody_id); let row = specific_tbody.insertRow(index) Note: insertRow() inserts the row directly into the table. The row does not need to be appended separately as would be the case if Document.createElement() had been used to create the new <tr> element. Syntax var newRow = HTMLTableElement.insertRow(index); HTMLTableElement is a reference to an HTML <table> element. Parameters index Optional The row index of the new row. If index is -1 or equal to the number of rows, the row is ...
... new cell in the new row. (To be valid HTML, a <tr> must have at least one <td> element.) Finally, we add some text to the cell using Document.createTextNode() and Node.appendChild(). ...
HTMLTrackElement: cuechange event - Web APIs
xtTrack, indicated by the track property, receives 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. ...
...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. let textTrackElem = document.
getElementById("texttrack"); textTrackElem.addEventListener("cuechange", (event) => { let cues = event.target.track.activeCues; }); In addition, you can use the oncuechange event handler: let textTrackElem = document.
getElementById("texttrack"); textTrackElem.oncuechange = (event) => { let cues = event.target.track.activeCues; }); Specifications Specification Status HTML Living StandardThe definition of 'cuechange' in that specification. Living Standard ...
KeyboardEvent.code - Web APIs
Handle keyboard events in a game This example establishes an event listener for keydown events that handle keyboard input for a game that uses the typical "WASD" keyboard layout for steering forward, left, backward, and right. This will use the same...
...mount of rotation applied to the ship, in degrees; it starts at 0? (pointing straight up). Finally, spaceship is set to refer to the element with the ID "spaceship", which is the SVG polygon representing the ship the player controls. let shipSize = { width: 30, height: 30 }; let position = { x: 200, y: 200 }; let moveRate = 9; let turnRate = 5; let angle = 0; let spaceship = document.
getElementById("spaceship"); Next comes the function updatePosition(). This function takes as input the distance the ship is to be moved, where positive is a forward movement and negative is a backward movement. This function computes the new position of the ship given the distance moved and the current direction the ship is facing. It also handles ensuring that the ship wraps across the boundaries of the pla...
KeyframeEffect.target - Web APIs
The target property of a KeyframeEffect interface represents the element or pseudo-element being animated. It may be null for animations that do not target a specific element. It performs as both a getter and a setter, except with animations and transitions generated by CSS. ...
...mentToAnimate"); var keyframes = new KeyframeEffect( targetElement, keyframeBlock, timingOptions ); // returns #elementToAnimate keyframes.target; // assigns keyframes a new target keyframes.target = newTargetElement; Value An Element, CSSPseudoElement, or null. ...
MediaStreamConstraints.audio - Web APIs
CSS content body { font: 14px "Open Sans", "Arial", sans-serif; } audio { margin-top: 20px; border: 1px solid black; width: 160px; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } JavaScript content let audioElement = document.
getElementById("audio"); let logElement = document.
getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.
getElementById("startButton").addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => audioElement.srcObject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); Here we see an event ...
... CSS content body { font: 14px "Open Sans", "Arial", sans-serif; } audio { margin-top: 20px; border: 1px solid black; width: 160px; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } JavaScript content let audioElement = document.
getElementById("audio"); let logElement = document.
getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.
getElementById("startButton").addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ audio: { sampleSize: 8, echoCancellation: true } }).then(stream => audioElement.srcObject = stream) .catch(err => log(err.name + ":...
MediaStreamConstraints.video - Web APIs
id="log"></div> CSS content body { font: 14px "Open Sans", "Arial", sans-serif; } video { margin-top: 20px; border: 1px solid black; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } JavaScript content let videoElement = document.
getElementById("video"); let logElement = document.
getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.
getElementById("startButton").addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ video: true }).then(stream => videoElement.srcObject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); Here we see an even...
... id="log"></div> CSS content body { font: 14px "Open Sans", "Arial", sans-serif; } video { margin-top: 20px; border: 1px solid black; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } JavaScript content let videoElement = document.
getElementById("video"); let logElement = document.
getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.
getElementById("startButton").addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ video: { width: 160, height: 120, frameRate: 15 } }).then(stream => videoElement.srcObject = stream) .catch(err => ...
MediaStreamTrack: ended event - Web APIs
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. ...
...andler for the ended event, which changes an on-screen icon to indicate that the track is no longer active. track.addEventListener('ended', () => { let statusElem = document.
getElementById("status-icon"); statusElem.src = "/images/stopped-icon.png"; }) You can also set up the event handler using the MediaStreamTrack.onended property: track.onended = function() { let statusElem = document.
getElementById("status-icon"); statusElem.src = "/images/stopped-icon.png"; } Specifications Specification Status Comment Media Capture and StreamsThe definition of 'ended' in that specification. Candidate Recommendation Initial specification. ...
MediaStreamTrack: mute event - Web APIs
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. 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 mute...
...ed to #aaa. When the track exits the muted state--detected by the arrival of an unmute event--the background color is restored to white. You can also use the onmute event handler property to set up a handler for this event; similarly, the onunmute event handler is available for setting up a handler for the unmute event. The following example shows this: musicTrack.onmute = event => { document.
getElementById("timeline-widget").style.backgroundColor = "#aaa"; } musicTrack.mute = event = > { document.
getElementById("timeline-widget").style.backgroundColor = "#fff"; } Specifications Specification Status Comment Media Capture and StreamsThe definition of 'mute' in that specification. Candidate Recommendation Initial specification. ...
MediaStreamTrack: unmute event - Web APIs
able 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. 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 mute...
...ged to #aaa. When the track exits the muted state--detected by the arrival of an unmuted event--the background color is restored to white. You can also use the onunmute event handler property to set up a handler for this event; similarly, the onmute event handler is available for setting up a handler for the mute event. The following example shows this: musicTrack.onmute = event => { document.
getElementById("timeline-widget").style.backgroundColor = "#aaa"; } musicTrack.mute = event = > { document.
getElementById("timeline-widget").style.backgroundColor = "#fff"; } Specifications Specification Status Comment Media Capture and StreamsThe definition of 'unmute' in that specification. Candidate Recommendation Initial specification. ...
MouseEvent.pageX - Web APIs
ates how to access the mouse position information in every available coordinate system. Let's take a look at a simple example that shows you the mouse's position relative 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. ...
...rmation in every available coordinate system. Let's take a look at a simple example that shows you the mouse's position relative 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. ...
MouseEvent - Web APIs
example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. ...
...() { var evt = new MouseEvent("click", { bubbles: true, cancelable: true, view: window }); var cb = document.
getElementById("checkbox"); //element to click on var canceled = !cb.dispatchEvent(evt); if(canceled) { // A handler called preventDefault alert("canceled"); } else { // None of the handlers called preventDefault alert("not canceled"); } } document.
getElementById("button").addEventListener('click', simulateClick); Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'MouseEvent' in that specification. Working Draft Redefines MouseEvent from long to double. This means that a PointerEvent whose pointerType is mouse will be a double. Pointer LockThe definition...
Online and offline events - Web APIs
k 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). ...
...online="..." 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). ...
Node.firstChild - Web APIs
first child in the tree, or null if the node has no children. If the node is a Document, it returns the first node in the list of its direct children. Syntax var childNode = node.firstChild; Example This example demonstrates the use of firstChild and how whitespace nodes might interfere with using this property. <p id="para-01"> <span>First span</span> </p> <script> var p01 = document.
getElementById('para-01'); console.log(p01.firstChild.nodeName); </script> In the above, the console will show '#text' because a text node is inserted to maintain the whitespace between the end of the opening <p> and <span> tags. Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on. Another #text node is inserted between the closing </span> and </p>tags. ...
...gs. Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on. Another #text node is inserted between the closing </span> and </p>tags. If this whitespace is removed from the source, the #text nodes are not inserted and the span element becomes the paragraph's first child. <p id="para-01"><span>First span</span></p> <script> var p01 = document.
getElementById('para-01'); console.log(p01.firstChild.nodeName); </script> Now the console will show 'SPAN'. To avoid the issue with node.firstChild returning #text or #comment nodes, ParentNode.firstElementChild can be used to return only the first element node. However, node.firstElementChild requires a shim for Internet Explorer 9 and earlier. Specifications Specification Status Comment...
Node.localName - Web APIs
nterfaces. ...
...name is the local name as a string (see Notes below for details) Example (Must be served with XML content type, such as text/xml or application/xhtml+xml.) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <script type="application/javascript"><![CDATA[ function test() { var text = document.
getElementById('text'); var circle = document.
getElementById('circle'); text.value = "<svg:circle> has:\n" + "localName = '" + circle.localName + "'\n" + "namespaceURI = '" + circle.namespaceURI + "'"; } ]]></script> </head> <body onload="test()"> <svg:svg version="1.1" width="100px" height="100px" viewBox="0 0 100 100"> <svg:circle cx="50" cy="50" r="30" style="fill:#aaa" id="circle"/> </svg:svg> ...
Node.nodeName - Web APIs
However, in HTML, text_field's value would read "DIV", because nodeName and tagName return in upper case on HTML elements in DOMs flagged as HTML documents. Read more details on nodeName case sensitivity in different browsers. Note th...
...However, in HTML, text_field's value would read "DIV", because nodeName and tagName return in upper case on HTML elements in DOMs flagged as HTML documents. Read more details on nodeName case sensitivity in different browsers. Note that the Element.tagName property could have been ...
Node.textContent - Web APIs
me indicates. Sometimes people use innerHTML to retrieve or write text inside an element, but textContent has better performance because its value is not parsed as HTML. Moreover, using textContent can prevent XSS attacks. Examples Given this HTML fragment: <div id="divA">This is <span>some</span> text!</div> ... ...
... its value is not parsed as HTML. Moreover, using textContent can prevent XSS attacks. Examples Given this HTML fragment: <div id="divA">This is <span>some</span> text!</div> ... you can use textContent to get the element's text content: let text = document.
getElementById('divA').textContent; // The text variable is now: 'This is some text!' ... or set the element's text content: document.
getElementById('divA').textContent = 'This text is different!'; // The HTML for divA is now: // <div id="divA">This text is different!</div> Specifications Specification Status Comment DOMThe definition of 'Node.textContent' in that specification. Living Standard ...
OffscreenCanvas - Web APIs
l display the ImageBitmap on the canvas and transfer its ownership to the canvas. A single OffscreenCanvas may transfer frames into an arbitrary number of other ImageBitmapRenderingContext objects. Given these two <canvas> elements <canvas id="one"></canvas> <canvas id="two"></canvas> the following code will provide the rendering using an OffscreenCanvas as described above. var one = document.
getElementById("one").getContext("bitmaprenderer"); var two = document.
getElementById("two").getContext("bitmaprenderer"); var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext('webgl'); // ... some drawing for the first canvas using the gl context ... // Commit rendering to the first canvas var bitmapOne = offscreen.transferToImageBitmap(); one.transferFromImageBitmap(bitmapOne); // ...
...fscreenCanvas Another way to use the OffscreenCanvas API, is to call transferControlToOffscreen() on a <canvas> element, either on a worker or the main thread, which will return an OffscreenCanvas object from an HTMLCanvasElement object from the main thread. Calling getContext() will then obtain a RenderingContext from that OffscreenCanvas. main.js (main thread code): var htmlCanvas = document.
getElementById("canvas"); var offscreen = htmlCanvas.transferControlToOffscreen(); var worker = new Worker("offscreencanvas.js"); worker.postMessage({canvas: offscreen}, [offscreen]); offscreencanvas.js (worker code): onmessage = function(evt) { var canvas = evt.data.canvas; var gl = canvas.getContext("webgl"); // ... some drawing using the gl context ... }; You can also use requestAnimationFrame i...
Path2D() - Web APIs
h2D(path); new Path2D(d); Parameters path Optional When invoked with another Path2D object, a copy of the path argument is created. d Optional When invoked with a string consisting of SVG path data, a new path is created from that description. Examples Creating and copying paths This example creates and copies a Path2D path. <canvas id="canvas"></canvas> const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); let path1 = new Path2D(); path1.rect(10, 10, 100,100); let path2 = new Path2D(path1); path2.moveTo(220, 60); path2.arc(170, 60, 50, 0, 2 * Math.PI); ctx.stroke(path2); Using SVG paths This example creates a Path2D path using SVG path data. The path will move to point (M10 10) and then move horizontally 80 points to the right (h 80), then 80 ...
...eTo(220, 60); path2.arc(170, 60, 50, 0, 2 * Math.PI); ctx.stroke(path2); Using SVG paths This example creates a Path2D path using SVG path data. The path will move to point (M10 10) and then move horizontally 80 points to the right (h 80), then 80 points down (v 80), then 80 points to the left (h -80), and then back to the start (Z). <canvas id="canvas"></canvas> const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); let p = new Path2D('M10 10 h 80 v 80 h -80 Z'); ctx.fill(p); Specification Specification Status Comment HTML Living StandardThe definition of 'Path2D()' in that specification. Living Standard Initial definition. ...
RTCDTMFSender: tonechange event - Web APIs
'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>". ...
... Candidate Recommendation Definition for the WebRTC API ...
RTCIceCandidatePair - Web APIs
local end of the connection. remote The RTCIceCandidate describing the configuration of the remote end of the connection. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
...scribing the configuration of the remote end of the connection. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
RTCIceTransport.getSelectedCandidatePair() - Web APIs
It's possible for one of the configurations in the selected candidate pair to remain unchanged when a new pairing is chosen. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
...andidate pair to remain unchanged when a new pairing is chosen. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
RTCIceTransport.onselectedcandidatepairchange - Web APIs
r.global properties specify RTCIceCandidate objects describing the local and remote candidates that are currently being used. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
...g the local and remote candidates that are currently being used. Example In this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair. ...
Range.setStart() - Web APIs
e.setEnd() methods to add part of an address to a range. The selected range is then highlighted using Range.surroundContents(). The address contains nine nodes: five text nodes, and four <br> elements. HTML <p id="address">Wyatt Earp<br> 101 E. Main St.<br> Dodge City, KS<br> 67801<br> USA</p> <hr> <p>Nodes in the original address:</p> <ol id="log"></ol> JavaScript const address = document.
getElementById('address'); const log = document.
getElementById('log'); // Log info address.childNodes.forEach(node => { const li = document.createElement('li'); li.textContent = `${node.nodeName}, ${node.nodeValue}`; log.appendChild(li); }); // Highlight the street and city const startOffset = 2; // Start at third node: 101 E. Main St. const endOffset = 5; // End at fifth node: Dodge City, KS const ...
...; const mark = document.createElement('mark'); range.surroundContents(mark); Result Get characters from a text node This example uses the Range.setStart() and Range.setEnd() methods to define the contents of a range. The resulting range contains the first through fifth characters within a text node. HTML <p id="content">0123456789</p> <p id="log"></p> JavaScript const element = document.
getElementById('content'); const textNode = element.childNodes[0]; const range = document.createRange(); range.setStart(textNode, 0); // Start at first character range.setEnd(textNode, 5); // End at fifth character document.
getElementById('log').textContent = range; Result Specifications Specification Status Comment DOMThe definition of 'Range.setStart()' in that specification. ...
Selection.containsNode() - Web APIs
).containsNode(document.body, true)); Find the hidden word In this example, a message appears when you select the secret word. It uses addEventListener() to check for selectionchange events. ...
... hidden word In this example, a message appears when you select the secret word. It uses addEventListener() to check for selectionchange events. HTML <p>Can you find the secret word?</p> <p>Hmm, where <span id="secret" style="color:transparent">SECRET</span> could it be?</p> <p id="win" hidden>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. Work...
TextMetrics - Web APIs
t2D.textBaseline property to the ideographic baseline of the line box, in CSS pixels. Examples Baselines illustrated This example demonstrates the baselines the TextMetrics object holds. The default baseline is the alphabeticBaseline. See also the CanvasRenderingContext2D.textBaseline property. ...
...he x-direction of a piece of text, the sum of actualBoundingBoxLeft and actualBoundingBoxRight can be wider than the width of the inline box (width), due to slanted/italic fonts where characters overhang their advance width. ...
TextTrack: cuechange event - Web APIs
xtTrack, indicated by the track property, receives 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. ...
...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. let textTrackElem = document.
getElementById("texttrack"); textTrackElem.addEventListener("cuechange", (event) => { let cues = event.target.track.activeCues; }); In addition, you can use the oncuechange event handler: let textTrackElem = document.
getElementById("texttrack"); textTrackElem.oncuechange = (event) => { let cues = event.target.track.activeCues; }); Specifications Specification Status HTML Living StandardThe definition of 'cuechange' in that specification. Living Standard ...
VideoPlaybackQuality.droppedVideoFrames - Web APIs
y dropped either before or after decoding them, when it's determined that it will not be possible to draw them to the screen at the correct time. Example This example calls getVideoPlaybackQuality() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been dropped. That value is then presented in an element for the user's reference. ...
...it's determined that it will not be possible to draw them to the screen at the correct time. Example This example calls getVideoPlaybackQuality() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been dropped. That value is then presented in an element for the user's reference. var videoElem = document.
getElementById("my_vid"); var percentElem = document.
getElementById("percent"); var quality = videoElem.getVideoPlaybackQuality(); var dropPercent = (quality.droppedVideoFrames/quality.totalVideoFrames)*100; percentElem.innerText = Math.trunc(dropPercent).toString(10); Specifications Specification Status Comment Media Playback QualityThe definition of 'VideoPlaybackQuality.droppedVideoFrames' in that specification. Editor's Draft ...
VisualViewport - Web APIs
VisualViewport.onscroll property. Examples Hiding an overlaid box on zoom This example, taken from the Visual Viewport README, shows how to write a simple bit of code that will hide an overlaid box (which might contain an advert, say) 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. ...
...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 layoutViewport = document.
getElementById('layoutViewport'); // Since the bar is position: fixed we need to offset it by the visual // viewport's offset from the layout viewport origin. var offsetLeft = viewport.offsetLeft; var offsetTop = viewport.height - layoutViewport.getBoundingClient...
A basic 2D WebGL animation example - Web APIs
let vertexCount; // Rendering data shared with the // scalers. ...
...ers are compiled, the program is linked using gl.linkProgram(). If an error occurrs while linking the program, the error message is logged to console. Finally, the compiled program is returned to the caller. Compiling an individual shader The compileShader() function, below, is called by buildShaderProgram() to compile a single shader. ...
Using the Web Storage API - Web APIs
r not. Getting values from storage As noted above, values can be retrieved from storage using Storage.getItem(). This takes the key of the data item as an argument, and returns the data value. For example: function setStyles() { var currentColor = localStorage.getItem('bgcolor'); var currentFont = localStorage.getItem('font'); var currentImage = localStorage.getItem('image'); document.
getElementById('bgcolor').value = currentColor; document.
getElementById('font').value = currentFont; document.
getElementById('image').value = currentImage; htmlElem.style.backgroundColor = '#' + currentColor; pElem.style.fontFamily = currentFont; imgElem.setAttribute('src', currentImage); } Here, the first three lines grab the values from local storage. Next, we set the values displayed in the form ...
...tive image on the page, so your customization options come up again on reload. Setting values in storage Storage.setItem() is used both to create new data items, and (if the data item already exists) update existing values. This takes two arguments -- the key of the data item to create/modify, and the value to store in it. function populateStorage() { localStorage.setItem('bgcolor', document.
getElementById('bgcolor').value); localStorage.setItem('font', document.
getElementById('font').value); localStorage.setItem('image', document.
getElementById('image').value); setStyles(); } The populateStorage() function sets three items in local storage -- the background color, font, and image path. It then runs the setStyles() function to update the page styles, etc. We've also included an onchange ha...
Using Web Workers - Web APIs
{ listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments); } else { this.defaultListener.call(instance, event.data); } } } // your custom "queryable" worker var myTask = new QueryableWorker('my_task.js'); // your custom "listeners" myTask.addListener('printStuff', function (result) { document.
getElementById('firstLink').parentNode.appendChild(document.createTextNode('The difference is ' + result + '!')); }); myTask.addListener('doAlert', function (time, unit) { alert('Worker waited for ' + time + ' ' + unit + ' :-)'); }); </script> </head> <body> <ul> <li><a id="firstLink" href="javascript:myTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a><...
...starts the recursion, spawning new copies of itself to handle each iteration of the calculation. The HTML code <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Test threads fibonacci</title> </head> <body> <div id="result"></div> <script language="javascript"> var worker = new Worker('fibonacci.js'); worker.onmessage = function(event) { document.
getElementById('result').textContent = event.data; dump('Got: ' + event.data + '\n'); }; worker.onerror = function(error) { dump('Worker error: ' + error.message + '\n'); throw error; }; worker.postMessage('5'); </script> </body> </html> The web page creates a div element with the ID result , which gets used to display the result, then spawns the worker. After spawning...
Window.getDefaultComputedStyle() - Web APIs
e computed style. pseudoElt Optional A string specifying the pseudo-element to match. Must be null (or not specified) for regular elements. Return value The returned style is a CSSStyleDeclaration object. The object is of the same type as the object returned by Window.getComputedStyle(), but only takes into account user-agent and user rules. ...
...y takes into account user-agent and user rules. Example Simple example var elem1 = document.
getElementById("elemId"); var style = window.getDefaultComputedStyle(elem1); Longer example <style> #elem-container { position: absolute; left: 100px; top: 200px; height: 100px; } </style> <div id="elem-container">dummy</div> <div id="output"></div> <script> var elem = document.
getElementById("elem-container"); var theCSSprop = window.getDefaultComputedStyle(elem).position; document.
getElementById("output").innerHTML = theCSSprop; // Will output "static" </script> Use with pseudo-elements The getDefaultComputedStyle() method can pull style info from pseudo-elements (e.g., ::before or ::after). <style> h3:after { content: ' rocks!'; } </style> <h3>generated content</h3> <...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
rnating two colors The following example calls the flashtext() function once a second until the Stop button is pressed. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>setInterval/clearInterval example</title> <script> var nIntervId; function changeColor() { nIntervId = setInterval(flashText, 1000); } function flashText() { var oElem = document.
getElementById('my_box'); oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red'; // oElem.style.color == 'red' ? 'blue' : 'red' is a conditional or ternary operator. } function stopTextColor() { clearInterval(nIntervId); } </script> </head> <body onload="changeColor();"> <div id="my_box"> <p>Hello World</p> </div> <button onclick="stopTextColor();">Stop</bu...
...You can cancel the interval using WindowOrWorkerGlobalScope.clearInterval(). If you wish to have your function called once after the specified delay, use WindowOrWork...
msCapsLockWarningOff - Web APIs
on. True: Automatic caps lock warning is turned off. ...
...le>msCapsLockWarningOff example</title> <script type="text/javascript"> function capsOff() { if (document.msCapsLockWarningOff == false) { document.msCapsLockWarningOff = true; document.
getElementById("caps").innerHTML = "Warning off"; } else { document.msCapsLockWarningOff = false; document.
getElementById("caps").innerHTML = "Warning on"; } } </script> </head> <body> <label>Type a password: <input type="password" /></label><br /> <button id="caps" onclick="capsOff();">Warning off</button> </body> </html> ...
ARIA live regions - Accessibility
a space. Advanced use case: Clock As an illustration of aria-atomic, consider a site with a simple clock, showing hours and minutes. The clock is updated each minute, with the new remaining time simply overwriting the current content. <div id="clock" role="timer" aria-live="polite"></div> /* basic JavaScript to update the clock */ setInterval(function() { var now = new Date(); document.
getElementById('clock').innerHTML = "Time: " + now.getHours() + ":" + ("0"+now.getMinutes()).substr(-2); }, 60000); The first time the function executes, the entirety of the string that is added will be announced. On subsequent calls, only the parts of the content that changed compared to the previous content will be announced. For instance, when the clock changes from "17:33" to "17:34", assistive technologi...
...e Clock example does not work as expected. A working example of a simple year control for better understanding: <div id="date-input"> <label>Year: <input type="text" id="year" value="1990" onblur="change(event)"/> </label> </div> <div id="date-output" aria-live="polite"> The set year is: <span id="year-output">1990</span> </div> function change(event) { var yearOut = document.
getElementById("year-output"); switch (event.target.id) { case "year": yearOut.innerHTML = event.target.value; break; default: return; } }; Without aria-atomic="true" the screenreader announces only the changed value of year. With aria-atomic="true", the screenreader announces "The set year is: changedvalue" Advanced use case: Roster A chat site would like to display a list of...
Using the alert role - Accessibility
ontrol may have instruction about the expected value. If a different value is entered, role="alert can be added to the instruction text so that the screen reader announces it as an alert. The pseudo code snippet below illustrates this approach: <p id="formInstruction">You must select at least 3 options</p> // When the user tries to submit the form with less than 3 checkboxes selected: document.
getElementById("formInstruction").setAttribute("role", "alert"); Example 4: Making an element with an alert role visible If an element already has role="alert" and is initially hidden using CSS, making it visible will cause the alert to fire as if it was just added to the page. This means that an existing alert can be "reused" multiple times. Note: In most cases this approach is not recommended, because it'...
... able to perceive the alert text even when the alert does not currently applies, causing users to incorrectly believe that there is a problem. .hidden { display:none; } <p id="expirationWarning" role="alert" class="hidden">Your log in session will expire in 2 minutes</p> // removing the 'hidden' class makes the element visible, which will make the screen reader announce the alert: document.
getElementById("expirationWarning").className = ""; Working Examples: Alert role example using an ARIA alert box Alert example using a modal ARIA dialog box Notes Using the alert role on an element implies that element has aria-live="assertive". The alert role should only be used for static text content. The element that the alert role is used on does not have to be able to receive focus, as screen...
Using the aria-invalid attribute - Accessibility
idate the fields immediately on blur; the application could wait until the form is submitted (though this is not necessarily recommended). ...
...ID); var invalid = (elem.value.indexOf(aSearchTerm) < 0); if (invalid) { elem.setAttribute("aria-invalid", "true"); updateAlert(aMsg); } else { elem.setAttribute("aria-invalid", "false"); updateAlert(); } } The snippet below shows the alert functions, which add (or remove) the error message: function updateAlert(msg) { var oldAlert = document.
getElementById("alert"); if (oldAlert) { document.body.removeChild(oldAlert); } if (msg) { var newAlert = document.createElement("div"); newAlert.setAttribute("role", "alert"); newAlert.setAttribute("id", "alert"); var content = document.createTextNode(msg); newAlert.appendChild(content); document.body.appendChild(newAlert); } } Note that...
Alerts - Accessibility
I-ARIA widget for notification. This notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the "onblur" handler in JavaScript's default 'alert' function). ...
...This method takes three para...
-moz-image-rect - CSS: Cascading Style Sheets
This places the four segments of our image in a two-by-two box grid. These four segments are all contained within a larger <div> block whose primary purpose is to receive click events and dispatch them to our JavaScript code. The JavaScript code This code handles the click event when the container receives a mouse click. ...
...he click event when the container receives a mouse click. function rotate() { var prevStyle = window.getComputedStyle(document.
getElementById("box4"), null).getPropertyValue("background-image"); // Now that we've saved the last one, start rotating for (var i=1; i<=4; i++) { var curId = "box" + i; // Shift the background images var curStyle = window.getComputedStyle(document.
getElementById(curId), null).getPropertyValue("background-image"); document.
getElementById(curId).style.backgroundImage = prevStyle; prevStyle = curStyle; } } This uses window.getComputedStyle() to fetch the style of each element, shifting it to the following element. Notice that before it begins doing so it saves a copy of the last box's style since it will be overwritten by the third element's styl...
Using CSS animations - CSS: Cascading Style Sheets
direction: alternate; } @keyframes slidein { from { margin-left:100%; width:300% } to { margin-left:0%; width:100%; } } Adding the animation event listeners We'll use JavaScript code to listen for all three possible animation events. 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 clas...
...It simply looks at the event.type to determine which kind of animation event occurred, then adds an appropriate note to the <ul> (unordered list) we're using to log these events. The output, when all is said and done, looks something like this: Started: elapsed time is 0 New loop started at time 3.01200008392334 New loop started ...
Border-radius generator - CSS: Cascading Style Sheets
uerySelectorAll('.ui-checkbox'); var size = elem.length; for (var i = 0; i < size; i++) new CheckBox(elem[i]); } return { init : init, setValue : setValue, subscribe : subscribe, unsubscribe : unsubscribe } })(); window.addEventListener("load", function() { BorderRadius.init(); }); var BorderRadius = (function BorderRadius() { function getElemById(id) { return document.
getElementById(id); } /** * Shadow dragging */ var PreviewMouseTracking = (function Drag() { var active = false; var lastX = 0; var lastY = 0; var subscribers = []; var init = function init(id) { var elem = getElemById(id); elem.addEventListener('mousedown', dragStart, false); document.addEventListener('mouseup', dragEnd, false); } var dragStart = function dragStart(e) { if (...
...etNode(this.topic); this.setUnitX(this.unitX); this.setUnitY(this.unitY); this.setUnitR(this.unitR); this.updateWidth(); this.updateHeight(); this.updateRadius(); if (x === 'left') this.resizeX = 1; if (x === 'right') this.resizeX = -1; if (y === 'top') this.resizeY = 1; if (y === 'bottom') this.resizeY = -1; radius.className = 'radius'; var unit_selector = document.
getElementById("unit-selection"); var unitW = new UnitSelector(this.topic + '-w'); var unitH = new UnitSelector(this.topic + '-h'); var unitR = new UnitSelector(this.topic); unit_selector.appendChild(unitW.container); unit_selector.appendChild(unitH.container); unit_selector.appendChild(unitR.container); node.appendChild(radius); subject.appendChild(handle); unitW.select.addEventListener('ch...
Color picker tool - CSS: Cascading Style Sheets
y: 0; top: -10000px; left: 0; color: #777; float: left; transition: opacity 1s; } #zindex input { border: 1px solid #DDD; font-size: 16px; color: #777; } #zindex .ui-input-slider-info { width: 60px; } #zindex[data-active='true'] { top: 0; opacity: 1; } JavaScript Content 'use strict'; var UIColorPicker = (function UIColorPicker() { function getElemById(id) { return document.
getElementById(id); } var subscribers = []; var pickers = []; /** * RGBA Color class * * HSV/HSB and HSL (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function Color(color) { if(color instanceof Color === true) { this.copy(color); return; } this.r = 0; this.g = 0; this.
...ubscribe : unsubscribe, setPrecision : setPrecision, setSensivity : setSensivity, getPrecision : getPrecision, createSlider : createSlider, }; })(); 'use strict'; window.addEventListener("load", function() { ColorPickerTool.init(); }); var ColorPickerTool = (function ColorPickerTool() { /*========== Get DOM Element By ID ==========*/ function getElemById(id) { return document.
getElementById(id); } function allowDropEvent(e) { e.preventDefault(); } /*========== Make an element resizable relative to it's parent ==========*/ var UIComponent = (function UIComponent() { function makeResizable(elem, axis) { var valueX = 0; var valueY = 0; var action = 0; var resizeStart = function resizeStart(e) { e.stopPropagation(); e.preventDefault(); if (e.button ...
Linear-gradient Generator - CSS: Cascading Style Sheets
px 5%; color: #777; position: relative; float: left; } #output .property { height: 100%; width: 12%; position: absolute; left: 0; } #output .value { width: 88%; position: absolute; white-space: pre; word-wrap: break-word; display: block; right: 0; } JavaScript Content var UIColorPicker = (function UIColorPicker() { 'use strict'; function getElemById(id) { return document.
getElementById(id); } var subscribers = []; var pickers = []; /** * RGBA Color class * * HSV/HSB and HSL (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function Color(color) { if(color instanceof Color === true) { this.copy(color); return; } this.r = 0; this.g = 0; this.
...entListener("load", function() { LinearGradientTool.init(); }); window.addEventListener("load", function() { LinearGradientTool.init(); }); var LinearGradientTool = (function LinearGradientTool() { 'use strict'; var radian = 180 / Math.PI; var inv_radian = Math.PI / 180; var units = {'%': 1, 'px' : 0}; /*========== DOM Methods ==========*/ function getElemById(id) { return document.
getElementById(id); } function allowDropEvent(e) { e.preventDefault(); } function createClassElement(tag, className, parent) { var elem = document.createElement(tag); elem.className = className; if (parent) parent.appendChild(elem); return elem; }; function trackMouse(elem, callback, startFunc, endFunc) { startFunc = startFunc || function(e) {}; endFunc = endFunc || function(e) {}; ele...
clip-path - CSS: Cascading Style Sheets
Candidate Recommendation Extends its application to HTML elements. The clip-path...
... Candidate Recommendation Extends its application to HTML elements. The clip-path property replaces the deprecated clip property. Scalable Vector Graphics (SVG) 1.1 (Seco...
justify-content - CSS: Cascading Style Sheets
Working Draft Adds the [ first | last ]? baselin...
... Working Draft Adds the [ first | last ]? baseline, self-start, self-end, start, end, left, right, unsafe | safe values. CSS Flexible Box Layout...
place-content - CSS: Cascading Style Sheets
ter</option> <option value="start">start</option> <option value="end">end</option> <option value="flex-start">flex-start</option> <option value="flex-end">flex-end</option> <option value="left">left</option> <option value="right">right</option> <option value="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"); justifyContentAlignme...
...nContentAlignment").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("direction"); direction.addEventListener("change", function (evt) { document.
getElementById("container").style.direction = evt.target.value; }); CSS #container { display: flex; height:240px; widt...
Challenge solutions - Developer guides
vaScript Move box to the right Challenge Change the script so that the square jumps to the right by 20 em when its color changes, and jumps back afterwards. Solution Add lines to modify the margin-left property. Be sure to specify it as marginLeft in JavaScript. ...
...s marginLeft in JavaScript. The following script achieves the desired result: // JavaScript demonstration function doDemo (button) { var square = document.
getElementById("square"); square.style.backgroundColor = "#fa4"; square.style.marginLeft = "20em"; button.setAttribute("disabled", "true"); setTimeout(clearDemo, 2000, button); } function clearDemo (button) { var square = document.
getElementById("square"); square.style.backgroundColor = "transparent"; square.style.marginLeft = "0em"; button.removeAttribute("disabled"); } SVG and CSS Change color of inner petals Challenge Change the stylesheet so that the inner petals all turn pink when the mouse pointer is over any one of them, without changing the way the outer petals work. Solution Move the position of the :hover pse...
Using device orientation with 3D transforms - Developer guides
d be alpha - 180 The Y axis of the 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. ...
... 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. ...
<input type="password"> - HTML: Hypertext Markup Language
nput id="pin" type="password" inputmode="numeric" minlength="4" maxlength="8" size="8"> Selecting text As with other textual entry controls, you can use the select() method to select all the text in the password field. HTML <label for="userPassword">Password: </label> <input id="userPassword" type="password" size="12"> <button id="selectAll">Select All</button> JavaScript document.
getElementById("selectAll").onclick = function() { document.
getElementById("userPassword").select(); } Result You can also use selectionStart and selectionEnd to get (or set) what range of characters in the control are currently selected, and selectionDirection to know which direction selection occurred in (or will be extended in, depending on your platform; see its documentation for an explanation). Howe...
... must have a value. Finally, autocomplete is set to off to avoid password managers and session restore features trying to set its value, since this isn't a password at all. JavaScript This is just some simple code to display the entered SSN onscreen so you can see it. Obviously this defeats the purpose of a password field, but it's helpful for experimenting with the pattern. var ssn = document.
getElementById("ssn"); var current = document.
getElementById("current"); ssn.oninput = function(event) { current.innerHTML = ssn.value; } Result Specifications Specification Status Comment HTML Living StandardThe definition of '<input type="password">' in that specification. Living Standard Initial definition HTML 5.1The definition of '<input type="password">' ...
<template>: The Content Template element - HTML: Hypertext Markup Language
nd: #000; } table td { background: #fff; } Avoiding DocumentFragment pitfall A DocumentFragment is not a valid target for various events, as such it is often preferable to clone or refer to the elements within it. ...
...ng DocumentFragment pitfall A DocumentFragment is not a valid target for various events, as such it is often preferable to clone or refer to the elements within it. ...
<track>: The Embed Text Track element - HTML: Hypertext Markup Language
xtTrack, indicated by the track property, receives 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. ...
...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. ...
Transitioning to strict mode - JavaScript
rror! In non-strict, this would silently fail, in contradiction with the user expectation. Poisoned arguments and function properties Accessing arguments.callee, arguments.caller, anyFunction.caller, or anyFunction.arguments throws an error in strict mode. ...
...uments throws an error in strict mode. The only legitimate use case would be to reuse a function as in: // example taken from vanillajs: http://vanilla-js.com/ var s = document.
getElementById('thing').style; s.opacity = 1; (function() { if ((s.opacity-=.1) < 0) s.display = 'none'; else setTimeout(arguments.callee, 40); })(); which can be rewritten as: 'use strict'; var s = document.
getElementById('thing').style; s.opacity = 1; (function fadeOut() { // name the function if((s.opacity-=.1) < 0) s.display = 'none'; else setTimeout(fadeOut, 40); // use the name of the function })(); Semantic differences These differences are very subtle differences. It's possible that a test suite doesn't catch this kind of subtle difference. Careful review of your code base will probably be nec...
Structural overview of progressive web apps - Progressive web apps (PWAs)
var button = docum...
...ntent').innerHTML = content; Then it registers 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. ...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
.responseXML; xsltProcessor.importStylesheet(xslRef); xslloaded = true; } // create a new XML document in memory xmlRef = document.implementation.createDocument("", "", null); // we want to move a part of the DOM from an HTML document to an XML document. ...
...r in the XSL file var sortVal = xsltProcessor.getParameter(null, "myOrder"); if (sortVal == "" || sortVal == "descending") xsltProcessor.setParameter(null, "myOrder", "ascending"); else xsltProcessor.setParameter(null, "myOrder", "descending"); // initiate the transformation var fragment = xsltProcessor.transformToFragment(xmlRef, document); // clear the contents document.
getElementById("example").innerHTML = ""; myDOM = fragment; // add the new content from the transformation document.
getElementById("example").appendChild(fragment) } // XSL Stylesheet: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="...
Creating annotations - Archive of obsolete content
n-box'> </textarea> </body> </html> Save this inside data/editor as annotation-editor.html. Annotation editor content script In the corresponding content script we do two things: handle a message from the add-on code by giving the text area focus listen for the return key and when it is pressed, send the contents of the text area to the add-on. Here's the code: var textArea = document.
getElementById('annotation-box'); textArea.onkeyup = function(event) { if (event.keyCode == 13) { self.postMessage(textArea.value); textArea.value = ''; } }; self.on('message', function() { var textArea = document.
getElementById('annotation-box'); textArea.value = ''; textArea.focus(); }); Save this inside data/editor as annotation-editor.js. Updating main.js Again Now we'll update main.j...
Display a Popup - Archive of obsolete content
ext the user // entered. // In this implementation 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 t...
Bootstrapped extensions - Archive of obsolete content
mponentManager.removeBootstrappedManifestLocation(). This feature was unavailable in Firefox versions before 8. Adding user interface manually If you decide to go ahead and try to develop a bootstrapped extension that modifies the application's user interface, here are a few suggestions to get you started. You need to look up the relevant application UI elements by their ID by calling document.
getElementById(), then manipulate them to inject your UI. For example, you can get access to the menu bar in Firefox with document.
getElementById("main-menubar"). Be sure that at shutdown time, you remove any user interface you've added. Creating a bootstrapped extension To mark an extension as bootstrappable, you need to add the following element to its install manifest: <em:bootstrap>true</em:bootstrap> ...
Downloading Files - Archive of obsolete content
nsIFile); targetFile.append("file.bin"); var obj_URI = Services.io.newURI(aURLToDownload, null, null); // Obtain the privacy context of the browser window that the URL // we are downloading comes from. If, and only if, the URL is not // related to a window, null should be used instead. ...
On page load - Archive of obsolete content
ript 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 = document.
getElementById("messagepane"); // mail if(messagepane){ messagepane.addEventListener("load", function(event) { myExtension.onPageLoad(event); }, true); } }, onPageLoad: function(aEvent) { var doc = aEvent.o...
Windows - Archive of obsolete content
ents.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIDOMWindowUtils); var windowID = util.currentInnerWindowID; Programatically modifying HTML When attempting to modify HTML elements, it is important to specify the namespace. For example, the following code will add a horizontal rule. var hr = document.createElementNS("http://www.w3.org/1999/xhtml", "html:hr"); document.
getElementById("id1").appendChild(hr); ...
Displaying web content in an extension without security issues - Archive of obsolete content
is much easier to use DOM manipulation methods that won't have unexpected side-effects. For example, your template document might have this code: <style type="text/css"> #entryTemplate { display: none; } </style> <div id="entryTemplate"> <div class="title"></div> <div class="description"></div> </div> Now to insert a new entry in the document you would do the following: var template = doc.
getElementById("entryTemplate"); var entry = template.cloneNode(true); entry.removeAttribute("id"); entry.getElementsByClassName("title")[0].textContent = title; entry.getElementsByClassName("description")[0].textContent = description; template.parentNode.appendChild(entry); The important difference here is that the result will always have the same structure as the template tag. cloneNode() always creates a co...
How to convert an overlay extension to restartless - Archive of obsolete content
me.manifest to load XUL overlays anymore with a restartless add-on. You could look into dynamically loading and unloading your overlay, however dynamically manipulating the DOM of your XUL window is usually the more straightforward route. Figure out what XUL elements you need to create for your add-on to add your interface, where it needs to go into a XUL window, and how to do it. Docs: document.
getElementByID(), document.createElement(), Element reference, Node reference (DOM elements are also nodes). You'll need to write two functions. One to take a XUL window object and then create and add your elements, and then another to find your elements and remove them from the window object. The former will need to be run on add-on startup and the later on add-on shutdown. Until you get your bootstrap.js run...
Inline options - Archive of obsolete content
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 example: var observer = { observe: function(aSubject, aTopic, aData) { if (aTopic == "addon-options-displayed" && aData == "MY_ADDON@MY_DOMAIN") { var doc = aSubject; var control = doc.
getElementById("myaddon-pref-control"); control.value = "test"; } } }; Services.obs.addObserver(observer, "addon-options-displayed", false); // Don't forget to remove your observer when your add-on is shut down. This code should be in bootstrap.js (within the startup() function) for restartless extensions or in an XPCOM component or a JavaScript code module (not an overlay!) for traditional exten...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
dler in use. Apart from menuitem elements, it can be used with buttons and other input controls. <menuitem label="Open project page" oncommand="loadURI(this.value)" value="http://mozilla.org/"/> 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. ...
Adding Events and Commands - Archive of obsolete content
broadcaster. You can have as many elements as you want observing a broadcaster. With that set, all you need to do now is set or remove attributes in the broadcaster using JavaScript. All nodes observing it will automatically have those attribute values set or removed as well. You can override pre-existing values, such as the label attribute value in the example. let onlineBroadcaster = document.
getElementById("xulschoolhello-online-broadcaster"); onlineBroadcaster.setAttribute("label", "Something"); You can also have finer-grained control to this behavior by adding the observes element as a child to your observer node. This allows you to choose which attributes you want it to observe. Broadcasters allow you to easily maintain consistency among numerous elements without having to add much code. The...
Connecting to Remote Content - Archive of obsolete content
of the XUL document is appended to a XUL element after the transformation. request.onload = function(aEvent) { let responseXML = aEvent.target.responseXML; let xulNode; // transform the XML document to a XUL document xulDocument = xsltProcessor.transformToDocument(responseXML); // append the XUL node to a XUL element xulNode = document.adoptNode(xulDocument.firstChild); document.
getElementById("foo").appendChild(xulNode); }; We effectively transformed the XML file into XUL and integrated it into the UI. Note: Security should be your number one priority when handling remote content. Do not allow event handlers or any other kinds of code to be passed through your parsers. If you need your generated XUL to have JS code in it, all of it should be added locally, never from the remote sou...
Adding preferences to an extension - Archive of obsolete content
rmation: function() { // Because we may be called as a callback, we can't rely on // "this" referring to the right object, so we need to reference // it by its full name var symbol = StockWatcher.tickerSymbol; var fullUrl = "http://quote.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=" + symbol; function infoReceived() { var samplePanel = document.
getElementById('stockwatcher2'); var output = httpRequest.responseText; if (output.length) { // Remove any whitespace from the end of the string output = output.replace(/\W*$/, ""); // Build the tooltip string var fieldArray = output.split(","); samplePanel.label = symbol + ": " + fieldArray[1]; samplePanel.tooltipText = "Chg: " + fieldArray[...
Creating a Web based tone generator - Archive of obsolete content
und selected } var k = 2* Math.PI * frequency / sampleRate; for (var i=0, size=soundData.length; i<size; i++) { soundData[i] = Math.sin(k * currentSoundSample++); } } var audioDestination = new AudioDataDestination(sampleRate, requestSoundData); function start() { currentSoundSample = 0; frequency = parseFloat(document.
getElementById("freq").value); } function stop() { frequency = 0; } </script> </body> </html> ...
Enabling the behavior - updating the status bar panel - Archive of obsolete content
In order for loadTinderboxStatus() to have any effect we need to define a matching updateTinderboxStatus() function. function updateTinderboxStatus() { var icon = document.
getElementById('tinderbox-status'); if (gXMLHttpRequest.responseText.match("EE0000")) icon.setAttribute("status", "busted"); else if (gXMLHttpRequest.responseText.match("FFAA00")) icon.setAttribute("status", "testfailed"); else if (gXMLHttpRequest.responseText.match("11DD11")) icon.setAttribute("status", "success"); else icon.setAttribute("status", ""); } updateTinderboxStatus() retrieves a reference to the statusbarpanel element then searches through the retrieved HTML document (stored in the responseText property of the XMLHttpRequest instance) for one of several color references. The color red (repres...
Jetpack Snippets - Archive of obsolete content
0, true); }}); Calling into a slidebar from the global jetpack scope jetpack.slideBar.append({ onReady: function (slide) { // call out to a global function, passing the slidebar object exInitSlidebar(slide); }, ...});function exInitSlidebar(aSlidebar) { // This variable will now be global slider = aSlidebar;} // then, accessing the slidebar HTMLvar tl = slider.contentDocument.
getElementById("thumbList"); // or calling slidebar API methods or accessing propertiesslider.notify(); ...
Anonymous Content - Archive of obsolete content
the DocumentXBL interface. See section 3 for more information. This method returns the bound element in the enclosing scope that is responsible for the anonymous node. If invoked on an element at the document-level scope, it returns null. DOM methods that can be invoked on elements (e.g., getElementsByTagName) will only see nodes that are in the same scope. Methods invoked on the document (e.g.,
getElementById) only see nodes that are at the document-level scope. Content generation Rules for generation Whenever bindings are attached to an element, anonymous content will potentially be generated or destroyed. When a new binding is attached, the bindings in its explicit 'inherits' chain are checked to see if any have anonymous content templates. The most derived binding in the chain with a template is...
Binding Attachment and Detachment - Archive of obsolete content
ever). Bindings can be attached to elements through the scripting by assigning the element.style.MozBinding property. Respectively bindings can be detached by setting element.style.MozBinding to empty string. Note: Some older papers mentioned DOM methods document.addBinding and document.removeBinding; these were subsequently discarded as redundant and not implemented. var checkbox = document.
getElementById("mycheckbox"); checkbox.style.MozBinding = "url(http://www.mozilla.org/xbl/htmlBindings.xml#checkbox)"; This attachment is not necessarily synchronous. Scripts that invoke this method should not assume that the binding is installed immediately after this method returns. See Binding Documents for more information. When a binding is attached using the DOM, it inherits from the current most deri...
disabled - Archive of obsolete content
trols. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. // Disabling an element document.
getElementById('buttonRemove').setAttribute("disabled", "disabled"); // Enabling back an element by removing the "disabled" attribute document.
getElementById('buttonRemove').removeAttribute("disabled"); Firefox 3.5 note For keyset elements, support for this attribute was added in Firefox 3.5. ...
oninput - Archive of obsolete content
<< XUL Reference home oninput Type: script code This event is sent when a user enters text in a textbox. This event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. Example <!-- This sets the label's text to the textbox value on each keystroke. --> <script language="javascript"> function setLabel(txtBox){ document.
getElementById('lbl').value = txtBox.value; } </script> <label id="lbl"/> <textbox oninput="setLabel(this);"/> This is similar to the onkeypress event used in HTML documents. ...
statustext - Archive of obsolete content
tustext="Connect to remote server" onmouseover="setStatusMessage(this)" onmouseout="clearStatusMessage()"/> <button label="Ping" statustext="Ping the server" onmouseover="setStatusMessage(this)" onmouseout="clearStatusMessage()"/> <statusbar> <statusbarpanel id="myStatusPanel" label="" flex="1"/> <spacer flex="1"/> </statusbar> <script> function setStatusMessage(obj){ document.
getElementById('myStatusPanel').label = obj.getAttribute('statustext'); } function clearStatusMessage(obj){ document.
getElementById('myStatusPanel').label = ''; } </script> See also statusbar and statusbarpanel ...
appendItem - Archive of obsolete content
<< XUL Reference home appendItem( label, value ) Return type: element Creates a new item and adds it to the end of the existing list of items. You may optionally set a value. The function returns the newly created element. ...
Menus - Archive of obsolete content
indow with a single line: <menu id="menu-tools"/> The overlay should have a menu with the same id 'menu-tools' containing the complete definition of the menu. If you wish to have slight differences between each window, one possibility is to show or hide menu items in a load event listener. For example, to have an item initially hidden in a window: function initMenus() { var item = document.
getElementById("menu-file-open"); item.hidden = true; } The hidden property is set to true to hide the menu with the id 'menu-fileOpen'. This function may be called from within an onload attribute on the window. Accessing and Setting the Active Item In a menu, there will usually be an item that is considered "active". This item will be highlighted, and will do certain functions depending on the kind of ...
Special per-platform menu considerations - Archive of obsolete content
and shortcut keys are overridden by platform conventions. However, regardless of the platform, the command event will be fired on the menu item when it is activated by the user. Notes for Firefox extension developers On the Mac, some elements, once moved to the Application menu, are no longer accessible from XUL overlays or from JavaScript injected into browser.xul. For example, using document.
getElementById() for the Quit menu item returns the hidden item that still sits in the File menu. To change these items in Firefox, overlay hiddenWindow.xul instead. ...
controllers - Archive of obsolete content
to the element. The controllers are used to respond to commands. The document's command dispatcher will locate controllers to handle a command by using the focused element's list. ...
currentIndex - Archive of obsolete content
ange or determine a tree selection, except for trees with seltype="single". (All trees have seltype="multiple" by default.) To reliably change or determine a selection, instead use the nsITreeSelection interface methods available via tree.view.selection. Example // One way of retrieving the text of a cell. ...
Actions - Archive of obsolete content
om/rdf/B" label="http://www.xulplanet.com/rdf/B"/> Naturally, you wouldn't use an id attribute inside a template action since the id would be replaced anyway. In fact, any ids you put inside a template action will be ignored. However, you may use ids on the other parts of the template, such as within the query statements, if you wish to change the statements and rebuild the template. You can use
getElementById to get at particular results, for instance document.
getElementById("http://www.xulplanet.com/rdf/C") would retrieve the second generated button. After all the results have been examined, the DOM tree will look like the following: <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/A"> <template> <query> <content uri="?start"/> <t...
Simple Query Syntax - Archive of obsolete content
tries/iso#IT"/> Adjusting Simple Query Conditions The simple syntax is limited in the kind of filtering it can do, however it is often sufficient for many purposes. Naturally, if you want to set a filter dynamically, as the photos example does with a menulist, you will need to set the attribute on the rule element and rebuild the template. function applyFilter(country) { var rule = document.
getElementById("filterRule"); if (country){ rule.setAttributeNS("http://www.xulplanet.com/rdf/", "country", country); } else { rule.removeAttributeNS("http://www.xulplanet.com/rdf/", "country"); } document.
getElementById("photosList").builder.rebuild(); } This version of the applyFilter function only needs to set or remove the attribute on the rule as necessary. Note that the namespace aware...
Sorting Results - Archive of obsolete content
where in the content the generated output should be inserted. The is similar to using a variable but any predicate may be used, not just one that is used in the template. Changing the Sort To change the sorting for a template's generated contents, you can either change the sort related attributes and rebuild the template, or you can call the sort method of the sort service: var listbox = document.
getElementById("aListBox"); var sortService = Components.classes["@mozilla.org/xul/xul-sort-service;1"]. getService(Components.interfaces.nsIXULSortService); sortService.sort(listbox, "?gender", "descending"); This code will sort a listbox by title in a descending order. The arguments to the sort method specify the root node (the listbox), the sort key and the sort direction. << Previ...
Template Logging - Archive of obsolete content
multiple templates are being used. The second line gives details about the new result. The id of the result is specified at the end, in this case 'http://www.some-fictitious-zoo.com/b...emperorpenguin'. This corresponds to the id attribute set on a generated row. For an RDF datasource, this will be the result's resource. For other datasources, this may be a somewhat random value. However, calling
getElementById using this id will retrieve the generated content for that result if you want to further study the content that was generated. The example also specifies 'query 2 matching rule 1'. This indicates that the result is for the second <query> element. If only one <query> is used, naturally this will always indicate a query of 1. In addition, this result matches the first <rule> of query 2. This inform...
Things I've tried to do with XUL - Archive of obsolete content
HTML-Element in order to access its "clientWidth" method: <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> ... <html:body id="invisible_element" flex="1" > <svg xmlns="http://www.w3.org/2000/svg" version="1.1"><!-- ...or _visible_ XUL content or whatever... --></svg> </html:body> ... var available_width = document.
getElementById("invisible_element").clientWidth; ... XBL in listboxes Using XBL bindings in listboxes is not easy because there is a big bug there: if you create from JS an element you want to bind, and if it is hidden when the listbox is first rendered, the listbox does not create a frame for it, and the xbl doesn't get attached... A workaround for that is to create the element, insert it in the document an...
Code Samples - Archive of obsolete content
= "C:\\WINDOWS\\CHARMAP.EXE" var file = Components .classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile) file.initWithPath(path) file.launch() Open a web page If your button is in Firefox or SeaMonkey, use code like this to open a web page. Change the first line to specify the page that you want to open: const url = "http://www.mozilla.org/" document .
getElementById("content") .webNavigation .loadURI(url, 0, null, null, null) If your button is in Thunderbird or Sunbird, use code like this to open a web page. Change the first line to specify the page that you want to open: const url = "http://www.mozilla.org/" var uri = Components .classes["@mozilla.org/network/simple-uri;1"] .getService(Components.interfaces.nsIURI) uri.spec = url Components .c...
Adding Event Handlers - Archive of obsolete content
DOM Event Listeners The second way to add an event handler is to call an element's addEventListener method. This allows you to attach an event listener dynamically and listen for events during the capturing phase. The syntax is as follows: Example 3 : Source View <button id="okbutton" label="OK"/> <script> function buttonPressed(event){ alert('Button was pressed!'); } var button = document.
getElementById("okbutton"); button.addEventListener('command', buttonPressed, true); </script> The
getElementById() function returns the element with a given id, in this case the button. The addEventListener() function is called to add a new capturing event listener. The first argument is the name of the event to listen to. The second argument is the event listener function which will be called when the event...
Adding Labels and Images - Archive of obsolete content
g and closing description tags for longer blocks of text. It is more common to use the attribute syntax for labels, and the text content syntax for descriptions. Example 4 : Source View <description> This longer section of text is displayed. </description> You can set the text via script using the textContent property, as in the following example: <description id="text" width="200"/> document.
getElementById('text').textContent = "Some lengthy word wrapped text goes here."; Internally, both the label element and the description elements are the same. The label element is intended for labels of controls, such as text fields. The control attribute is only supported for labels. The description element is intended for other descriptive text such as informative text at the top of a dialog box. Images XUL...
Broadcasters and Observers - Archive of obsolete content
server notices a change to the attributes of the broadcaster that it is watching. An example is shown below. Example 3 : Source View <broadcasterset> <broadcaster id="colorChanger" style="color: black"/> </broadcasterset> <button label="Test"> <observes element="colorChanger" attribute="style" onbroadcast="alert('Color changed');"/> </button> <button label="Observer" oncommand="document.
getElementById('colorChanger').setAttribute('style','color: red');" /> Two buttons have been created, one labeled Test and the other labeled Observer. If you click on the Test button, nothing special happens. However, if you click on the Observer button, two things happen. First, the button changes to have red text and, second, an alert box appears with the message 'Color changed'. What happens is the oncomm...
XPCOM Examples - Archive of obsolete content
on. Cookies Next, we will get a list of cookies that have been saved in the browser. The cookie service can be used for such a purpose. It implements the nsICookieManager interface which can be used to enumerate over all of the cookies. Here is an example which populates a menu list with the names of all of the cookies set from MozillaZine. ...
Using Remote XUL - Archive of obsolete content
ant it to load URLs in the iframe when we press the buttons or select the menu items. For that we need to add JavaScript code. <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript"> function loadURL(event) { var contentFrame = document.
getElementById("contentFrame"); var url = event.target.getAttribute("value"); if (url) contentFrame.setAttribute("src", url); } </script> ... </window> The code to load the URLs is simple. First we write an event handler function that receives an event, extracts a URL from the value attribute of the element where the event occurred (a.k.a. the target element), and loads the URL in the if...
XUL element attributes - Archive of obsolete content
d height may be different if the element or its contents have a minimum or maximum height. The CSS height property may also be used. hidden Type: boolean If set to true, the element is not displayed. This is similar to setting the CSS display property to 'none'. id Type: unique id A unique identifier so that you can identify the element with. You can use this as a parameter to
getElementById() and other DOM functions and to reference the element in style sheets. insertafter Type: id When an element is in an overlay, the insertafter attribute specifies the id of the element in the base window that the element should appear after. This attribute overrides the insertbefore attribute. This value may be a comma-separated list of ids, which are scanned and the first one found in...
description - Archive of obsolete content
isplayed <description> This is a long section of text that will word wrap when displayed. </description> This is a long section of text that will not word wrap <description value="This is a long section of text that will not word wrap"> </description> This is a long section of dynamically controlled text that will word wrap <description id="desc" style="width: 300px"></description> document.
getElementById('desc').textContent = "This is a long section of dynamic message text that will word wrap"; Attributes crop Type: one of the values below If the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute. An ellipsis will be used in place of the cropped text. If the box direction is reversed, the crop...
editor - Archive of obsolete content
ocument, contentWindow, docShell, editingSession, editortype, webBrowserFind, webNavigation Methods getEditor, getHTMLEditor, makeEditable Examples This example shows how to made the editor editable by setting the designMode property of the loaded HTML document: <script language="javascript"> function initEditor(){ // this function is called to set up the editor var editor = document.
getElementById("myEditor"); editor.contentDocument.designMode = 'on'; } </script> <editor id="myEditor" editortype="html" src="about:blank" flex="1" type="content-primary"/> Once editable, the document can have special formatting and other HTML pieces added to it using the document.execCommand method: var editor = document.
getElementById("myEditor"); // toggle bold for the current selection editor.c...
iframe - Archive of obsolete content
Default is false. src Type: URI The URI of the content to appear in the element. type Type: one of the values below. The type of browser, which can be used to set access of the document loaded i...
key - Archive of obsolete content
- These elements don't handle any key events --> <key key="" modifiers="control"/> <key keycode="" modifiers="control"/> Modifying attributes In case you want to change one of the <key>'s attributes, such as the modifiers attribute, the keyset element has to be re-added to its parent node; otherwise the new attributes won't be applied. For example: // modify some attributes let key = document.
getElementById(KEY_ID); key.setAttribute("modifiers", "alt shift"); // apply the changes let keyset = document.
getElementById(KEYSET_ID); keyset.parentNode.appendChild(keyset); ...
listbox - Archive of obsolete content
abel="Ruby"/> <listitem label="Emerald"/> <listitem label="Sapphire" selected="true"/> <listitem label="Diamond"/> </listbox> <listbox id="theList" rows="10" width="400"> <listhead> <listheader label="1ct Gem" width="240"/> <listheader label="Price" width="150"/> </listhead> <listcols> <listcol/> <listcol flex="1"/> </listcols> </listbox> var theList = document.
getElementById('theList'); gems = [ {gem: "Ruby", Price: "$3,500 - $4,600"}, {gem: "Emerald", Price: "$700 - 4,250"}, {gem: "Blue Sapphire", Price: "$3,400 - $4,500"}, {gem: "Diamond", Price: "$5,600 - $16,000"} ]; for (var i = 0; i < gems.length; i++) { var row = document.createElement('listitem'); var cell = document.createElement('listcell'); cell.setAttrib...
progressmeter - Archive of obsolete content
The default value if not specified is 100 such that the value may be used as a percentage. mode Type: one of the values below A determinedprogressmeter is used in cases where you know how long an operation will take. An undet...
window - Archive of obsolete content
t in pixels. The actual displayed height may be different if the element or its contents have a minimum or maximum height. The CSS height property may also be used. hidechrome Type: boolean Set this attribute to true to have the chrome including the titlebar hidden. id Type: unique id A unique identifier so that you can identify the element with. You can use this as a parameter to
getElementById() and other DOM functions and to reference the element in style sheets. inactivetitlebarcolor Type: color string Specify background color of the window's titlebar when it is inactive (background). Moreover this hides separator between titlebar and window contents. This affects only on Mac OS X. lightweightthemes Type: boolean true if the window supports lightweight themes, otherwi...
wizard - Archive of obsolete content
ount, pageIndex, pageStep, title, wizardPages Methods advance, cancel, extra1, extra2, getButton, getPageById, goTo, rewind Examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="theWizard" title="Secret Code Wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function checkCode(){ document.
getElementById('theWizard').canAdvance = (document.
getElementById('secretCode').value == "cabbage"); } </script> <wizardpage onpageshow="checkCode();"> <label value="Enter the secret code:"/> <textbox id="secretCode" onkeyup="checkCode();"/> </wizardpage> <wizardpage> <label value="That is the correct secret code."/> </wizardpage> </wizard> Attributes activetitlebarcolor Type...
Building XULRunner with Python - Archive of obsolete content
mp.enabled", true); pref("javascript.options.showInConsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); HTML <script> tags specify that Python is used withtype="application/x-python" attribute. 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...
Getting started with XULRunner - Archive of obsolete content
quite powerful and can even be used on mobile devices.</description> </window> Note: Make sure there is no extra whitespace at the beginning of the XML/XUL file The application also has a JavaScript file. Most XUL applications will include some external JavaScript, so the sample application does too, just to show how to include it into the XUL file. main.js: function showMore() { document.
getElementById("more-text").hidden = false; } For more information about XUL see: XUL. For information about mixing HTML elements into your XUL read Adding HTML Elements. Step 8: Run the application The moment of truth. We need to get XULRunner to launch the bare-bones application. Windows From a Windows command prompt opened to the myapp folder, we should be able to execute this: C:\path\to\xulrunne...
xbDesignMode.js - Archive of obsolete content
* * Contributor(s): Doron Rosenberg <doron@netscape.com> (original author) * * * * ***** END LICENSE BLOCK ***** */ /* xbDesignMode a JavaScript wrapper for browsers that support designMode */ function xbDesignMode(aIFrame){ this.mEditorDocument = null; this.mIFrameElement = null; // argument is a string, therefore an ID if ( (typeof(aIFrame) == "string") && (document.
getElementById(aIFrame).tagName.toLowerCase()=="iframe") ){ this.mIFrameElement = document.
getElementById(aIFrame); } else if( (typeof(aIFrame)=="object") && (aIFrame.tagName.toLowerCase() == "iframe") ){ this.mIFrameElement = aIFrame; } else { throw "Argument isn't an id of an iframe or an iframe reference"; } if (this.mIFrameElement.contentDocument){ // Gecko this.mEditorDocument ...
Adobe Flash - Archive of obsolete content
TML element that spawns the plugin. This may be the embed element or the object element's name or ID attribute respectively. Treat the handle to the HTML element as a handle to the actual Flash plugin and invoke the published methods on it. The illustrative code snippet below shows this idea: <object id="myFlash" ..... > <param name="movie" value="somefile.swf" /> .... var myFlash = document.
getElementById("myFlash").SetVariable("myVar", sendText); A more expanded code example that shows how Example 2 was created is shown in this source listing. FSCommands: Accessing JavaScript from Flash Note: FSCommand may not work with Flash Player versions older than version 8 if the user has installed multiple Mozilla based browsers onto the same machine (see bug 32048 and bug 233533). In Example 2, a J...
Summary of Changes - Archive of obsolete content
TML 4.01 OBJECT deprecated APPLET HTML 4.01 OBJECT non-standard MARQUEE HTML 4.01 DIV plus scripting non-standard BGSOUND HTML 4.01 OBJECT Proprietary or Deprecated Feature W3C Feature or Recommended Replacement IE5+ id_attribute_value document.all.id_attribute_value document.all[id_attribute_value] DOM level 2: document.
getElementById(id_attribute_value) IE5+ FormName.InputName.value DOM level 1: document.forms["FormName"].InputName.value IE5+ InputName.value DOM level 1: document.forms["FormName"].InputName.value IE5+ FormCtrlName DOM level 1: document.forms["FormName"].FormCtrlName IE5+ document.forms(0) DOM level 1: document.forms[0] IE...
RDF in Mozilla FAQ - Archive of obsolete content
urces="rdf:null"> ... </tree> ... </window> Assuming that we've aquired a datasource somehow (e.g., like this), the following sample code illustrates how to add that datasource to the template, and then force the template to rebuild itself based on the newly added datasource's contents. var ds = /* assume we got this somehow! */; // Get the DOM element for 'my-tree' var tree = document.
getElementById('my-tree'); // Add our datasource to it tree.database.AddDataSource(ds); // Force the tree to rebuild *now*. You have to do this "manually"! tree.builder.rebuild(); Any XUL element with a datasources attribute will "get" a database property and a builder property. The database property refers to an nsIRDFCompositeDataSource object, which contains the datasources from which the template is built...
Windows Media in Netscape - Archive of obsolete content
ce of JavaScript. For example, in IE it is possible to do this: Player.closedCaption.CaptioningID = "CapText"; Here, "CapText" is the id of an HTML element, assigned to the CaptioningID property of the Player. Instead of doing that, this is the recommendation and workaround for Netscape 7.1: <script FOR="Player" EVENT="ScriptCommand(type, param)"> if (type == "Text") { var cap = document.
getElementById("CapText"); cap.innerHTML = param; } </script> More detailed examples are available in the final section on examples and sample code. Important Caveats and Usage Scenarios This section covers some of the common usages in conjunction with Windows Media Player and IE that should not be used with Windows Media Player and Netscape 7.1. Detection Strategies Proper detection strategies are impor...
Building up a basic demo with the PlayCanvas engine - Game development
ructure Here's the HTML structure we will use. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MDN Games: PlayCanvas demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="playcanvas-latest.js"></script> <canvas id="application-canvas"></canvas> <script> var canvas = document.
getElementById("application-canvas"); /* all our JavaScript code goes here */ </script> </body> </html> It contains some basic information like the document <title>, and some CSS to set the width and height of the <canvas> element that PlayCanvas will use to 100% so that it will fill the entire available viewport space. The first <script> element includes the PlayCanvas library in the page; we will write ...
Audio for Web games - Game development
tton> <button data-start="2" data-stop="3">8</button> <button data-start="0" data-stop="1">9</button> Now we have buttons with start and stop times in seconds. 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. ...
Crisp pixel art look with image-rendering - Game development
anvas: <canvas id="game" width="128" height="128"></canvas> CSS to size the canvas and render a crisp image: canvas { width: 512px; height: 512px; image-rendering: -moz-crisp-edges; image-rendering: -webkit-crisp-edges; image-rendering: pixelated; image-rendering: crisp-edges; } And some JavaScript to set up the canvas and load the image: // get canvas context var ctx = document.
getElementById('game').getContext('2d'); // load image var image = new Image(); image.onload = function () { // draw the image into the canvas ctx.drawImage(image, 0, 0); } image.src = 'https://udn.realityripple.com/samples/11/a2954fe197.png'; This code used together produces the following result: Note: You can check out the original code on Github (and a live example.) ...
Create the Canvas and draw on it - Game development
grab a reference to it, and it is 480 pixels wide and 320 pixels high. All the JavaScript code we will write in this tutorial will go between the opening <script> and closing </script> tags. Canvas basics To actually be able to render graphics on the <canvas> element, first we have to grab a reference to it in JavaScript. Add the following below your opening <script> tag. var canvas = document.
getElementById("myCanvas"); var ctx = canvas.getContext("2d"); Here we're storing a reference to the <canvas> element to the canvas variable. Then we're creating the ctx variable to store the 2D rendering context -- the actual tool we can use to paint on the Canvas. Let's see an example piece of code that prints a red square on the canvas. Add this below your previous lines of JavaScript, then load your index...
Plug-in Development Overview - Gecko Plugin API Reference
ide methods that can be called from JavaScript and the DOM when accessed through the object or embed element. Consider the following example, where a media player plug-in can be controlled with an advanceToNextSong() method called inside the script element: <object id="myPlugin" type="audio/wav" data="music.wav"> </object> <script type="application/javascript"> var thePlugin = document.
getElementById('myPlugin'); if (thePlugin && thePlugin.advanceToNextSong) thePlugin.advanceToNextSong(); else alert("Plugin not installed correctly"); </script> In the past, LiveConnect and later XPConnect were used to make plug-ins scriptable. See the Wikipedia article for historical information. Both technologies are now obsolete for the purposes of plug-in scriptability, and the cross-browser...
Fundamental text and font styling - Learn web development
p { } </textarea> <h2>Output</h2> <div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div> <div class="controls"> <input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;"> </div> </div> const htmlInput = document.querySelector(".html-input"); const cssInput = document.querySelector(".css-input"); const reset = document.
getElementById("reset"); let htmlCode = htmlInput.value; let cssCode = cssInput.value; const output = document.querySelector(".output"); const styleElem = document.createElement('style'); const headElem = document.querySelector('head'); headElem.appendChild(styleElem); function drawOutput() { output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; } reset.addEventListener("click", fun...
Styling links - Learn web development
0em;padding: 10px;border: 1px solid #0095dd;"></div> <div class="controls"> <input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;"> <input id="solution" type="button" value="Show solution" style="margin: 10px 0 0 10px;"> </div> </div> var htmlInput = document.querySelector(".html-input"); var cssInput = document.querySelector(".css-input"); var reset = document.
getElementById("reset"); var htmlCode = 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...
Styling lists - Learn web development
px;border: 1px solid #0095dd;overflow: auto;"></div> <div class="controls"> <input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;"> <input id="solution" type="button" value="Show solution" style="margin: 10px 0 0 10px;"> </div> </div> var htmlInput = document.querySelector(".html-input"); var cssInput = document.querySelector(".css-input"); var reset = document.
getElementById("reset"); var htmlCode = 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...
Adding vector graphics to the Web - Learn web development
svg> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution" disabled> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); const output = document.querySelector('.output'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntr...
From object to iframe — other embedding technologies - Learn web development
ght: 100px;"> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="Reset"> <input id="solution" type="button" value="Show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.
getElementById('code'); const reset = document.
getElementById('reset'); const solution = document.
getElementById('solution'); const output = document.querySelector('.output'); let code = textarea.value; let userEntry = textarea.value; function updateCode() { output.innerHTML = textarea.value; } reset.addEventListener('click', function() { textarea.value = code; userEntry = textarea.value; solutionEntr...
Video and audio content - Learn web development
ent. Other than this, <audio> supports all the same features as <video> -- review the above sections for more information about them. Restarting media playback At any time, you can reset the media to the beginning--including the process of selecting the best media source, if more than one is specified using <source> elements--by calling the element's load() method: const mediaElem = document.
getElementById("my-media-element"); mediaElem.load(); Detecting track addition and removal You can monitor the track lists within a media element to detect when tracks are added to or removed from the element's media. For example, you can watch for the addtrack event being fired on the associated AudioTrackList object (retrieved via HTMLMediaElement.audioTracks) to be informed when audio tracks are added to t...
Choosing the right approach - Learn web development
g function creates a new Date() object, extracts a time string out of it using toLocaleTimeString(), and then displays it in the UI. We then run it once per second using setInterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displayTime() { let date = new Date(); let time = date.toLocaleTimeString(); document.
getElementById('demo').textContent = time; } const createClock = setInterval(displayTime, 1000); Pitfalls The frame rate isn't optimized for the system the animation is running on, and can be somewhat inefficient. Unless you need to choose a specific (slower) framerate, it is generally better to use requestAnimationFrame(). Browser compatibility DesktopMobileChromeEdgeFirefoxInternet ExplorerOperaSafari...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
creates a new Date() object, extracts a time string out of it using toLocaleTimeString(), and then displays it in the UI. It then runs the function once per second using setInterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displayTime() { let date = new Date(); let time = date.toLocaleTimeString(); document.
getElementById('demo').textContent = time; } const createClock = setInterval(displayTime, 1000); Just like setTimeout(), setInterval() returns an identifying value you can use later when you need to clear the interval. Clearing intervals setInterval() keeps running a task forever, unless you do something about it. You'll probably want a way to stop such tasks, otherwise you may end up getting errors when th...
Manipulating documents - Learn web development
l will match the first <a> element that appears in the document. If you wanted to match and do things to multiple elements, you could use Document.querySelectorAll(), which matches every element in the document that matches the selector, and stores references to them in an array-like object called a NodeList. There are older methods available for grabbing element references, such as: Document.
getElementById(), which selects an element with a given id attribute value, e.g. <p id="myId">My paragraph</p>. The ID is passed to the function as a parameter, i.e. const elementRef = document.
getElementById('myId'). Document.getElementsByTagName(), which returns an array-like object containing all the elements on the page of a given type, for example <p>s, <a>s, etc. The element type is passed to the functio...
Solve common problems in your JavaScript code - Learn web development
owser complains that something is undefined, check that you've spelt all your variable names, function names, etc. correctly. Some common built-in browser functions that cause problems are: Correct Wrong getElementsByTagName() getElementbyTagName() getElementsByName() getElementByName() getElementsByClassName() getElementByClassName()
getElementById() getElementsById() Semi-colon position You need to make sure you don't place any semi-colons incorrectly. For example: Correct Wrong elem.style.color = 'red'; elem.style.color = 'red;' Functions There are a number of things that can go wrong with functions. One of the most common errors is to declare the function, but not call it anywhere. For example...
Componentizing our React app - Learn web development
ew const beneath the final import, but above ReactDOM.render(): const DATA = [ { id: "todo-0", name: "Eat", completed: true }, { id: "todo-1", name: "Sleep", completed: false }, { id: "todo-2", name: "Repeat", completed: false } ]; Next, we'll pass DATA to <App /> as a prop, called tasks. The final line of src/index.js should read like this: ReactDOM.render(<App tasks={DATA} />, document.
getElementById("root")); This array is now available to the App component as props.tasks. You can console.log() it to check, if you'd like. Note: ALL_CAPS constant names have no special meaning in JavaScript; they're a convention that tells other developers "this data will never change after being defined here". Rendering with iteration To render our array of objects, we have to turn each one into a <Todo...
Focus management with Vue refs - Learn web development
updates are first performed on the in-memory nodes, and then all the changes that need to be made to the actual nodes on the page are synced in a batch. Since reading and writing actual DOM nodes is often more expensive than virtual nodes, this can result in better performance. However, it also means you often should not edit your HTML elements directly through native browser APIs (like Document.
getElementById) when using frameworks, because it results in the VDOM and real DOM going out of sync. Instead, if you need to access the underlying DOM nodes (like when setting focus), you can use Vue refs. For custom Vue components, you can also use refs to directly access the internal structure of a child component, however this should be done with caution as it can make code harder to reason about and under...
Handling common HTML and CSS problems - Learn web development
oose Inspect/Inspect element (or whatever the option is in your browser) -- this should open up the dev tools in your browser, with the element highlighted in the DOM inspector. Look for a feature you can use to select that element. For example, at the time of writing, the main Google logo had an ID of hplogo. ...
A bird's-eye view of the Mozilla framework
JavaScript Client Example Suppose the JavaScript service in Figure 2 is getLink() in Help.js, which responds to the user clicking on a link in theContents Panel within theHelp Viewer window by obtaining the link from theContents Panel elements stored in a DOM tree. As a client, getLink() begins by obtaining the XULElement in the DOM tree representing theContents Panel. var tocTree = document.
getElementById("help-toc-panel"); The document object is a XULDocument, and tocTree is theContents Panel XULElement. Using the database attribute of the XULElement, getLink() obtains an nsIRDFCompositeDataSource, which presents the individual datasources of the XULElement as a single RDF graph. var tocDS = tocTree.database; NsIRDFCompositeDataSource inherits from nsIRDFDataSource. Help.js declares an nsI...
Cross Process Object Wrappers
rs to them. To deal with this, CPOWs 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-s...
MozBeforePaint
than that anyway. Limiting the frame rate avoids wasting work, thereby saving CPU usage and power and improving overall system performance. Example This example performs a simple animation, moving a box a short distance after a short period of time. ...
Localization and Plurals
er of files # example: 111 files - Downloads downloadsTitleFiles=#1 file - Downloads;#1 files - Downloads # LOCALIZATION NOTE (timePair): #1 time number; #2 time unit # example: 1 second; 11 seconds timePair=#1 #2 seconds=second;seconds minutes=minute;minutes hours=hour;hours downloads.js: Components.utils.import("resource://gre/modules/PluralForm.jsm"); let getStr = function(string) document.
getElementById("strings").getString(string); // Get the correct plural form for the title let numDownloads = 3; let title = PluralForm.get(numDownloads, getStr("downloadsTitleFiles")); // Put in the correct number of downloads print(title.replace("#1", numDownloads)); // Get the correct plural form of seconds let timeLeft = 55; let seconds = PluralForm.get(timeLeft, getStr("seconds")); // Print the localized ...
Extras
<mi>n</mi> <mo>!</mo> </mrow> </mfrac> </mrow> </math> </foreignObject> <text>exp(?)</text> </switch> </g> </g> </svg> </div> Inline JavaScript HTML Content <math display="block"> <mfrac> <mtext id="num">Mouse</mtext> <mtext id="denum">Over</mtext> </mfrac> </math> JavaScript Content function whoIsThereAlert(evt) { alert("Who is there?"); } function attachListener(id) { document.
getElementById(id).addEventListener("mouseover", whoIsThereAlert); } function init() { attachListener("num"); attachListener("denum"); } window.addEventListener("load", init); ...
MathML In Action
addEventListener("click", zoomToggle, false); } window.addEventListener("load", load, false); Consider an interesting markup like this { u t + f ( u ) x = 0 u ( 0 , x ) = { u - if x < 0 u + if x > 0 or other complex markups like these Ell ^ Y ( Z ; z , ? ) := ? Y ( ? l ( y l 2 ? i ) ? ...
javascript.options.strict
itten, or prone to cause logic errors. This preference controls whether JavaScript warnings are logged to the JavaScript Console. Example : <html> <head> <title>Sample</title> </head> <body> <label id="name">Enter you First Name</label> <p id ="sample"></p> <script> "use strict" name1= "John" ; // This will cause and an error as variable not declared . var name2= "Peter"; document.
getElementById("sample").innerHTML = name1; </script> </body> </html> Possible values and their effects: True: Show JavaScript errors and warnings. False: Show JavaScript errors only. (Default) See also: http://kb.mozillazine.org/Javascript.options.strict ...
Building the WebLock UI
ite method expects is a string, so we can pass a string directly in from the user interface, or we can do a check on the string and verify that it's a valid URL. In this tutorial, focusing as it is on the WebLock functionality (rather than the UI), we'll assume the strings we get from the UI itself are URLs we actually want to write to the white list: function addThisSite() { var tf = document.
getElementById("dialog.input"); // weblock is global and declared above weblock.AddSite(tf.value); } This JavaScript function can be called directly from the XUL widget, where the input string is retrieved as the value property of the textbox element. You also need to create the function that displays the WebLock window itself when the user clicks the weblock icon in the statusbar. That function uses the...
Introduction to XPCOM for the DOM
class" is correctly defined. The XPIDL compiler turns the IDL methods and attributes into C++ functions according to the following rules: The methods of the interface keep the same name in C++ . However in IDL we have to use the so-called "interCaps" model. That means that the first letter is lower-cased, and the other letters that begin a new word are upper-cased. For example, in IDL we'd write
getElementById, which in C++ would be translated to
GetElementById. NS_IMETHOD is a macro that basically means "virtual nsresult". The argument list and return type are turned into correct C++ types according to rules not described here. The attributes of the interface become two functions: a getter, and a setter. In our example, since the attribute is declared as read-only, only a getter is defined: GetNeat.
nsIFileView
opriate id is passed, nsIFileView relies on the treecols section --> <treecol id="FilenameColumn" label="Name" flex="1" primary="true"/> <treecol id="LastModifiedColumn" label="Date" flex="1"/> <treecol id="Size" label="Size" flex="1"/> </treecols> <treechildren/> </tree> <script> var DIR="/home/"; //The directory to be opened var ftree = document.
getElementById("ftree"); //The XUL tree element var lfile = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); lfile.initWithPath(DIR); // Open the directory var fview = Components.classes["@mozilla.org/filepicker/fileview;1"] .createInstance(Components.interfaces.nsIFileView); //Create an instance of the component tview = fview.Query...
Using nsISimpleEnumerator
Using nsISimpleEnumerator <stringbundle>.strings var enumerator = document.
getElementById('aStringBundleID').strings; var s = ""; while (enumerator.hasMoreElements()) { var property = enumerator.getNext().QueryInterface(Components.interfaces.nsIPropertyElement); s += property.key + ' = ' + property.value + ';\n'; } alert(s); Example using JavaScript 1.7 features // creates a generator iterating over enum's values function generatorFromSimpleEnumerator(enum, interface) { while (enum.hasMoreElements()) { yield enum.getNext().QueryInterface(interface); } } var b = document.
getElementById("stringbundleset").firstChild var props = generatorFromEnumerator(b.strings, Components.interfaces.nsIPropertyElement); var s = ""; for (let property in props) { s += property.key + ' = ' + pr...
Filelink Providers
y provide an extraArgs function in the IFrame content which returns an object specifying the name, type, and value to save. The format for the returned object is: { FIELD_NAME: {type: FIELD_TYPE, value: FIELD_VALUE} } Where FIELD_TYPE is "int", "bool", or "char". For example, the Hightail implementation provides the following function: function extraArgs() { var usernameValue = document.
getElementById("username").value; return { "username": {type: "char", value: usernameValue}, }; } In this example, the username value is read from the input, and then the specially-crafted object is returned. Once this is done, the field is accessible from within the implementation via the Preferences API using the key mail.cloud_files.accounts.ACCOUNT_KEY.username where ACCOUNT_KEY is the value pass...
Adding items to the Folder Pane
older-tree-items. Listening for Folder 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-...
Building a Thunderbird extension 6: Adding JavaScript
esult 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. window.addEventListener("load", function(e) { startup(); }, false); window.setInterval( function() { startup(); }, 60000); //update date every minute function startup() { var myPanel = document.
getElementById("my-panel"); var date = new Date(); var day = date.getDay(); var dateString = date.getFullYear() + "." + (date.getMonth()+1) + "." + date.getDate(); myPanel.label = "Date: " + dateString; } The first part registers a new event listener that will be executed automatically when Thunderbird loads. The event listener then calls our startup function which gets our <statusbarpanel>-element with th...
Add New Tab
var aURL = "chrome://myext/mytab.xul"; let tabmail = getMail3Pane().document.
getElementById("tabmail"); tabmail.openTab("chromeTab", { chromePage: aUrl }); ...
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); ...
Plug-in Development Overview - Plugins
ide methods that can be called from JavaScript and the DOM when accessed through the object or embed element. Consider the following example, where a media player plug-in can be controlled with an advanceToNextSong() method called inside the script element: <object id="myPlugin" type="audio/wav" data="music.wav"> </object> <script type="application/javascript"> var thePlugin = document.
getElementById('myPlugin'); if (thePlugin && thePlugin.advanceToNextSong) thePlugin.advanceToNextSong(); else alert("Plugin not installed correctly"); </script> In the past, LiveConnect and later XPConnect were used to make plug-ins scriptable. See the Wikipedia article for historical information. Both technologies are now obsolete for the purposes of plug-in scriptability, and the cross-browser...
Debug eval sources - Firefox Developer Tools
You can debug JavaScript code that is evaluated dynamically, either as a string passed to eval() or as a string passed to the Function constructor. 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. ...
DOM allocation example - Firefox Developer Tools
turn toolbarButton; } function createToolbar() { var toolbar = document.createElement("div"); // stop Spidermonkey from sharing instances toolbar[getRandomInt(0,5000)] = "foo"; for (var i = 0; i < toolbarButtonCount; i++) { var toolbarButton = createToolbarButton(); toolbar.appendChild(toolbarButton); } return toolbar; } function createToolbars() { var container = document.
getElementById("container"); for (var i = 0; i < toolbarCount; i++) { var toolbar = createToolbar(); container.appendChild(toolbar); } } createToolbars(); A simple pseudocode representation of how this code operates looks like this: createToolbars() -> createToolbar() // called 200 times, creates 1 DIV element each time -> createToolbarButton() // called 20 times per toolbar, creates 1...
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 appen...
Animation inspector example: CSS transitions - Firefox Developer Tools
an { opacity: 1; width: 300px; } JavaScript Content function toggleSelection(e) { if (e.button != 0) { return; } if (e.target.classList.contains("icon")) { var wasSelected = (e.target.getAttribute("id") == "selected"); clearSelection(); if (!wasSelected) { e.target.setAttribute("id", "selected"); } } } function clearSelection() { var selected = document.
getElementById("selected"); if (selected) { selected.removeAttribute("id"); } } document.addEventListener("click", toggleSelection); ...
Animation inspector example: Web Animations API - Firefox Developer Tools
)', offset: 0.666 }, { transform: 'scale(1.5)', filter: 'grayscale(0%)'} ]; var noteKeyframeSet = [ { opacity: '0', width: '0'}, { opacity: '1', width: '300px'} ]; var iconKeyframeOptions = { duration: 750, fill: 'forwards', easing: 'ease-in', endDelay: 100 } var noteKeyframeOptions = { duration: 500, fill: 'forwards', easing: 'ease-out', delay: 150 } var icon = document.
getElementById("icon"); var note = document.
getElementById("note"); var iconAnimation = icon.animate(iconKeyframeSet, iconKeyframeOptions); var noteAnimation = note.animate(noteKeyframeSet, noteKeyframeOptions); iconAnimation.pause(); noteAnimation.pause(); var firstTime = true; function animateChannel(e) { if (e.button != 0) { return; } if (e.target.id != "icon") { return; } if (firstTime...
Waterfall - Firefox Developer Tools
right-hand sidebar will also show the 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. ...
Console messages - Firefox Developer Tools
a collection of invalidating changes and recalculate their effect at once. However, if some JavaScript code reads a style that has been modified, then the browser must perform a synchronous reflow in order to calculate the computed style to return. For example, code like this will cause an immediate, synchronous, reflow, when it calls window.getComputedStyle(thing).height: var thing = document.
getElementById("the-thing"); thing.style.display = "inline-block"; var thingHeight = window.getComputedStyle(thing).height; Because of this, it's a good idea to avoid interleaving write and read calls to an element's styles when manipulating the DOM, because every time you read back a style that has been invalidated by a previous write call, you force a synchronous reflow. Security The security messages show...
AddressErrors - Web APIs
ent 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> Result The final product is below. Note: if you...
AnalyserNode - Web APIs
see app.js lines 128-205 for relevant code). var audioCtx = new(window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); // ... ...
Animation.onfinish - Web APIs
nction to be called to handle the finish event, or null if no finish event handler is set. Examples Animation.onfinish is used several times in the Alice in Web Animations API Land Growing/Shrinking Alice Game. Here is one instance where we add pointer events back to an element after its opacity animation has faded it in: // Add an animation to the game's ending credits var endingUI = document.
getElementById("ending-ui"); var bringUI = endingUI.animate(keysFade, timingFade); // Pause said animation's credits bringUI.pause(); // This function removes pointer events on the credits. hide(endingUI); // When the credits are later faded in, // we re-add the pointer events when they're done bringUI.onfinish = function() { endingUI.style.pointerEvents = 'auto'; }; Specifications Specificatio...
Animation.play() - Web APIs
ng. Syntax animation.play(); Parameters None. Return value undefined Example In the Growing/Shrinking Alice Game example, clicking or tapping the cake causes Alice's growing animation (aliceChange) to play forward, causing her to get bigger, as well as triggering the cake's animation. Two Animation.play()s, one EventListener: // The cake has its own animation: var nommingCake = document.
getElementById('eat-me_sprite').animate( [ { transform: 'translateY(0)' }, { transform: 'translateY(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: aliceChange.effect.timing.duration / 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.startTime - Web APIs
rent time in milliseconds, or null if no time is set. You can read this value to determine what the start time is currently set at, and you can change this value to make the animation start at a different time. Examples In the Running on Web Animations API example, the we can sync all new animated cats by giving them all the same startTime as the original running cat: var catRunning = document.
getElementById ("withWAAPI").animate(keyframes, timing); /* A function that makes new cats. */ function addCat(){ var newCat = document.createElement("div"); newCat.classList.add("cat"); return newCat; } /* This is the function that adds a cat to the WAAPI column */ function animateNewCatWithWAAPI() { // make a new cat var newCat = addCat(); // animate said cat with the WAAPI's "animate" function...
AudioScheduledSourceNode: ended event - Web APIs
uledSourceNode 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 Comment Web Audio APIThe definit...
AudioScheduledSourceNode.onended - Web APIs
the browser when the ended event occurs on the AudioScheduledSourceNode. The function receives as input a single parameter, which is an object of type Event describing the event that occurred. 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.onended = function(event) { document.
getElementById("startButton").disabled = false; } Specifications Specification Status Comment Web Audio APIThe definition of 'onended' in that specification. Working Draft Initial specification. ...
AudioTrack.enabled - Web APIs
y is a Boolean whose value is true if the track is enabled; enabled tracks produce audio while the media is playing. Setting enabled to false effectively mutes the audio track, preventing it from contributing to the media's audio performance. Example This example switches between the main and commentary audio tracks of a media element. ...
Blob.size - Web APIs
es = blob.size Value The number of bytes of data contained within the Blob (or Blob-based object, such as a File). Example This example uses an <input> element of type file to ask the user for a group of files, then iterates over those files outputting their names and lengths in bytes. // fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput"> var fileInput = document.
getElementById("myfileinput"); // files is a FileList object (simliar to NodeList) var files = fileInput.files; for (var i = 0; i < files.length; i++) { console.log(files[i].name + " has a size of " + files[i].size + " Bytes"); } Specifications Specification Status Comment File APIThe definition of 'Blob.size' in that specification. Working Draft Initial definition. ...
Blob.type - Web APIs
lue A DOMString containing the file's MIME type, or an empty string if the type could not be determined. Example This example asks the user to select a number of files, then checks each file to make sure it's one of a given set of image file types. var i, fileInput, files, allowedFileTypes; // fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput"> fileInput = document.
getElementById("myfileinput"); // files is a FileList object (simliar to NodeList) files = fileInput.files; // our application only allows GIF, PNG, and JPEG images allowedFileTypes = ["image/png", "image/jpeg", "image/gif"]; for (i = 0; i < files.length; i++) { // Test if file.type is an allowed file type. if (allowedFileTypes.indexOf(files[i].type) > -1) { // file type matched is one of allowed fil...
Body.body - Web APIs
of the body contents. Syntax var stream = response.body; Value A ReadableStream. Example In our simple stream pump example we fetch an image, expose the response's stream using response.body, create a reader using ReadableStream.getReader(), then enqueue that stream's chunks into a second, custom readable stream -- effectively creating an identical copy of the image. ...
CSSKeywordValue.CSSKeywordValue() - Web APIs
example resets the CSS display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. #myElement { display: flex; } <div id="myElement">Check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let keyword = new CSSKeywordValue('initial'); let myElement = document.
getElementById('myElement').attributeStyleMap; myElement.set('display', keyword); console.log( myElement.get('display').value); // 'initial' console.dir( keyword ); Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'CSSKeywordValue' in that specification. Working Draft Initial definition. ...
CSSKeywordValue.value - Web APIs
The value property of the CSSKeywordValue interface returns or sets the value of the CSSKeywordValue. Syntax var val = cssKeywordValue.value cssKeywordValue.value = val Value A USVString. Examples The following example resets the CSS display property to its defaults. let indicator = Document.
getElementById('indicator'); indicator.attributeStyleMap.set('display', new CSSKeywordValue('initial')); indicator.attributeStyleMap.get('display').value // 'initial' Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'undefined' in that specification. Working Draft Initial definition. ...
CSSKeywordValue - Web APIs
from CSSStyleValue. Examples The following example resets the CSS display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector. #myElement { display: flex; } <div id="myElement">Check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let myElement = document.
getElementById('myElement').attributeStyleMap; myElement.set('display', new CSSKeywordValue('initial')); console.log( myElement.get('display').value); // 'initial' Specifications Specification Status Comment CSS Typed OM Level 1The definition of 'CSSKeywordValue' in that specification. Working Draft Initial definition. ...
CSSPositionValue.CSSPositionValue() - Web APIs
alues for properties that take a position, for example object-position. Syntax cvar cssPositionValue = new CSSPositionValue(x, y) Parameters x A position along the web page's horizontal axis. ...
CSSPositionValue.x - Web APIs
The x property of the CSSPositionValue interface returns returns the item's position along the web page's horizontal axis. Syntax var x = CSSPositionValue.x Value A CSSNumericValue. ...
CSSPositionValue.y - Web APIs
The y property of the CSSPositionValue interface returns the item's position along the vertical axis. Syntax var y = CSSPositionValue.y Value A CSSNumericValue. ...
CSSPositionValue - Web APIs
ositionValue() Creates a new CSSPositionValue object. Properties CSSPositionValue.x Returns the item's position along the web page's horizontal axis. CSSPositionValue.y Returns the item's position along the vertical axis. Methods None. Examples The following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page. let replacedEl = document.
getElementById( 'image' ); let position = new CSSPositionValue( CSS.px(35), CSS.px(40) ); replacedEl.attributeStyleMap.set( 'object-position', position ); console.log( position.x.value, position.y.value ); console.log( replacedEl.computedStyleMap().get('object-position') ); We set the object-position property, then check the values returned. #image { width: 300px; height: 300px; border: 1px solid black...
CSSPrimitiveValue.getRectValue() - Web APIs
rty can be achieved using the Rect interface. Syntax var rectValue = cssPrimitiveValue.getRectValue(); Return value A Rect object representing the rect value. Exceptions Type Description DOMException An INVALID_ACCESS_ERR is raised if the CSS value doesn't contain a Rect value. (i.e. this is not CSS_RECT). Example var cs = window.getComputedStyle(document.
getElementById("clippedDiv")); var cssValue = cs.getPropertyCSSValue("clip"); console.log(cssValue.getRectValue()); Specifications Specification Status Comment Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSPrimitiveValue.getRectValue' in that specification. Obsolete Initial definition ...
CSSStyleDeclaration.cssText - Web APIs
The cssText property of the CSSStyleDeclaration interface returns or sets the text of the element's inline style declaration only. To be able to set a stylesheet rule dynamically, see Using dynamic styling information. Not to be confused with stylesheet style-rule CSSRule.cssText. Example <span id="s1" style="color: red;"> Some text </span> <script> var elem = document.
getElementById("s1"); alert(elem.style.cssText); // "color: red;" </script> Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration: cssText' in that specification. Working Draft ...
CSSStyleDeclaration.item() - Web APIs
d. Syntax var propertyName = style.item(index); Parameters index is the index of the node to be fetched. The index is zero-based. Return value propertyName is a DOMString that is the name of the CSS property at the specified index. JavaScript has a special simpler syntax for obtaining an item from a NodeList by index: var propertyName = style[index]; Example var style = document.
getElementById('div1').style; var propertyName = style.item(1); // or simply style[1] - returns the second style listed Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration.item()' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSStyleDeclaration' ...
CSSStyleDeclaration.length - Web APIs
tions in this CSS declaration block. Syntax var num = styles.length; Value An integer that provides the number of styles explictly set on the parent of the instance. Example The following gets the number of explicitly set styles on the following HTML element: <div id="div1" style="margin: 0 10px; background-color: #CA1; font-family: monospace"></div> JavaScript code: var myDiv = document.
getElementById('div1'); var divStyle = myDiv.style; var len = divStyle.length; // 6 Specifications Specification Status Comment CSS Object Model (CSSOM)The definition of 'CSSStyleDeclaration.length' in that specification. Working Draft Document Object Model (DOM) Level 2 Style SpecificationThe definition of 'CSSStyleDeclaration' in that specification. Obsolete ...
CanvasGradient.addColorStop() - Web APIs
range. color A CSS <color> value representing the color of the stop. A SYNTAX_ERR is raised if the value cannot be parsed as a CSS <color> value. Examples Adding stops to a gradient This example uses the addColorStop method to add stops to a linear CanvasGradient object. The gradient is then used to fill a rectangle. ...
CanvasRenderingContext2D.beginPath() - Web APIs
g the current canvas state, you can use CanvasRenderingContext2D.moveTo(). Syntax void ctx.beginPath(); Examples Creating distinct paths This example creates two paths, each of which contains a single line. HTML <canvas id="canvas"></canvas> JavaScript The beginPath() method is called before beginning each line, so that they may be drawn with different colors. ...
CanvasRenderingContext2D.canvas - Web APIs
as API, is a read-only reference to the HTMLCanvasElement object that is associated with a given context. It might be null if there is no associated <canvas> element. Syntax ctx.canvas; Examples Given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a reference to the canvas element within the CanvasRenderingContext2D by using the canvas property: var canvas = document.
getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.canvas // HTMLCanvasElement Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.canvas' in that specification. Living Standard ...
CanvasRenderingContext2D.clearHitRegions() - Web APIs
The CanvasRenderingContext2D method clearHitRegions() removes all hit regions from the canvas. Syntax void ctx.clearHitRegions(); Examples Using the clearHitRegions method This example demonstrates the clearHitRegions() method. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Set some hit regions ctx.addHitRegion({id: 'eyes'}); ctx.addHitRegion({id: 'nose'}); ctx.addHitRegion({id: 'mouth'}); // Remove them altogether from the canvas ctx.clearHitRegions(); Specifications Canvas hit regions have been removed from the WHATWG Living Standard, although discussions about future standardization are ongoing. See https://github.com/whatwg/html/issues/3407 for more information. ...
CanvasRenderingContext2D.createLinearGradient() - Web APIs
fied line. Examples Filling a rectangle with a linear gradient This example initializes a linear gradient using the createLinearGradient() method. Three color stops between the gradient's start and end points are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. ...
CanvasRenderingContext2D.createPattern() - Web APIs
ng a pattern. Examples Creating a pattern from an image This example uses the createPattern() method to create a CanvasPattern with a repeating source image. Once created, the pattern is assigned to the canvas context's fill style and applied to a rectangle. The original image looks like this: HTML <canvas id="canvas" width="300" height="300"></canvas> JavaScript var canvas = document.
getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = 'https://udn.realityripple.com/samples/04/aaeaf9aac4.png'; img.onload = function() { var pattern = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 300, 300); }; Creating a pattern from a canvas In this example we create a pattern from the contents of an offscreen canvas. We the...
CanvasRenderingContext2D.createRadialGradient() - Web APIs
mples Filling a rectangle with a radial gradient This example initializes a radial gradient using the createRadialGradient() method. Three color stops between the gradient's two circles are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle. ...
CanvasRenderingContext2D.direction - Web APIs
" The text direction is inherited from the <canvas> element or the Document as appropriate. Default value. The default value is "inherit". Examples Changing text direction This example draws two pieces of text. The first one is left-to-right, and the second is right-to-left. Note that "Hi!" in ltr becomes "!Hi" in rtl. HTML <canvas id="canvas"></canvas> JavaScript var canvas = document.
getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.font = '48px serif'; ctx.fillText('Hi!', 150, 50); ctx.direction = 'rtl'; ctx.fillText('Hi!', 150, 130); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.direction' in that specification. Living Standard ...
CanvasRenderingContext2D.font - Web APIs
hen drawing text. This string uses the same syntax as the CSS font specifier. Syntax ctx.font = value; Options value A DOMString parsed as CSS font value. The default font is 10px sans-serif. Examples Using a custom font In this example we use the font property to specify a custom font weight, size, and family. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = 'bold 48px serif'; ctx.strokeText('Hello world', 50, 100); Result Loading fonts with the CSS Font Loading API With the help of the FontFace API, you can explicitly load fonts before using them in a canvas. let f = new FontFace('test', 'url(x)'); f.load().then(function() { // Ready to use the font in a canvas context }); Specif...
CanvasRenderingContext2D.getImageData() - Web APIs
ngle, and then uses getImageData() to grab a portion of the canvas. HTML <canvas id="canvas"></canvas> JavaScript The object retrieved by getImageData() has a width of 200 and a height of 100, for a total of 20,000 pixels. Of those pixels, most are either transparent or taken from off the canvas; only 5,000 of them are opaque black (the color of the drawn rectangle). const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 100, 100); ctx.fill(); let imageData = ctx.getImageData(60, 60, 200, 100); ctx.putImageData(imageData, 150, 10); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.getImageData' in that specification. Living Standard ...
CanvasRenderingContext2D.getLineDash() - Web APIs
For example, setting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25]. Examples Getting the current line dash setting This example demonstrates the getLineDash() method. HTML <canvas id="canvas"></canvas> JavaScript As set by setLineDash(), strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setLineDash([10, 20]); console.log(ctx.getLineDash()); // [10, 20] // Draw a dashed line ctx.beginPath(); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.getLineDash' in that specification. ...
CanvasRenderingContext2D.globalCompositeOperation - Web APIs
Tutorial. Syntax ctx.globalCompositeOperation = type; type is a String identifying which of the compositing or blending mode operations to use. Types Examples Changing the composite operation This example uses the globalCompositeOperation property to draw two rectangles that exclude themselves where they overlap. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.globalCompositeOperation = 'xor'; ctx.fillStyle = 'blue'; ctx.fillRect(10, 10, 100, 100); ctx.fillStyle = 'red'; ctx.fillRect(50, 50, 100, 100); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.globalCompositeOperation' in that specification. Li...
CanvasRenderingContext2D.imageSmoothingEnabled - Web APIs
mages or not. The default value is true. Examples Disabling image smoothing This example compares three images. The first image is drawn at its natural size, the second is scaled to 3X and drawn with image smoothing enabled, and the third is scaled to 3X but drawn with image smoothing disabled. ...
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
ct, imageSmoothingEnabled must be true. Syntax ctx.imageSmoothingQuality = "low" || "medium" || "high" Options Possible values: "low" Low quality. "medium" Medium quality. "high" High quality. Example Setting image smoothing quality This example uses the imageSmoothingQuality property with a scaled image. ...
CanvasRenderingContext2D.lineWidth - Web APIs
keText() methods. Syntax ctx.lineWidth = value; Options value A number specifying the line width, in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. This value is 1.0 by default. Examples Changing line width This example draws a line and a rectangle, using a line width of 15 units. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.lineWidth = 15; ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(130, 130); ctx.rect(40, 40, 70, 70); ctx.stroke(); Result More examples For more examples and explanation about this property, see Applying styles and color in the Canvas Tutorial. Specifications Specification Status Comment HTML Living StandardThe ...
CanvasRenderingContext2D.measureText() - Web APIs
method returns a TextMetrics object that contains information about the measured text (such as its width, for example). Syntax ctx.measureText(text); Parameters text The text String to measure. Return value A TextMetrics object. Example Given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a TextMetrics object using the following code: const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); let text = ctx.measureText('Hello world'); console.log(text.width); // 56; Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.measureText' in that specification. Living Standard ...
CanvasRenderingContext2D.miterLimit - Web APIs
Playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginPath(); ctx.moveTo(0,0); ctx.lineWidth = 15; ctx.lineTo(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()...
CanvasRenderingContext2D.moveTo() - Web APIs
ertical) coordinate of the point. Examples Creating multiple sub-paths This example uses moveTo() to create two sub-paths within a single path. Both sub-paths are then rendered with a single stroke() call. HTML <canvas id="canvas"></canvas> JavaScript The first line begins at (50, 50) and ends at (200, 50). The second line begins at (50, 90) and ends at (280, 120). var canvas = document.
getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(50, 50); // Begin first sub-path ctx.lineTo(200, 50); ctx.moveTo(50, 90); // Begin second sub-path ctx.lineTo(280, 120); ctx.stroke(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.moveTo' in that specification. Living...
CanvasRenderingContext2D.putImageData() - Web APIs
Errors thrown NotSupportedError Thrown if any of the arguments is infinite. InvalidStateError Thrown if the ImageData object's data has been detached. Examples Understanding putImageData To understand what this algorithm does under the hood, here is an implementation on top of CanvasRenderingContext2D.fillRect(). ...
CanvasRenderingContext2D.rect() - Web APIs
eft. height The rectangle's height. Positive values are down, and negative are up. Examples Drawing a rectangle This example creates a rectangular path using the rect() method. The path is then rendered using the fill() method. HTML <canvas id="canvas"></canvas> JavaScript The rectangle's corner is located at (10, 20). It has a width of 150 and a height of 100. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 20, 150, 100); ctx.fill(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.rect' in that specification. Living Standard ...
CanvasRenderingContext2D.removeHitRegion() - Web APIs
CanvasRenderingContext2D method removeHitRegion() removes a given hit region from the canvas. Syntax void ctx.removeHitRegion(id); Parameters id A DOMString representing the id of the region that is to be removed. Examples Using the removeHitRegion method This example demonstrates the removeHitRegion() method. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Set a hit region ctx.addHitRegion({id: 'eyes'}); // Remove it from the canvas ctx.removeHitRegion('eyes'); Specifications Canvas hit regions have been removed from the WHATWG Living Standard, although discussions about future standardization are ongoing. See https://github.com/whatwg/html/issues/3407 for more information. ...
CanvasRenderingContext2D.restore() - Web APIs
es nothing. Fore more information about the drawing state, see CanvasRenderingContext2D.save(). Syntax void ctx.restore(); Examples Restoring a saved state This example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later. ...
CanvasRenderingContext2D.save() - Web APIs
Color, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. Syntax void ctx.save(); Examples Saving the drawing state This example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Save the default state ctx.save(); ctx.fillStyle = 'green'; ctx.fillRect(10, 10, 100, 100); // Restore the default state ctx.restore(); ctx.fillRect(150, 40, 100, 100); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.save' in that specification. ...
CanvasRenderingContext2D.setTransform() - Web APIs
ameter, matrix, representing a 2D transformation matrix to set (technically, a DOMMatrixInit object; any object will do as long as it contains the above components as properties). Examples Skewing a shape This example skews a rectangle both vertically (.2) and horizontally (.8). Scaling and translation remain unchanged. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setTransform(1, .2, .8, 1, 0, 0); ctx.fillRect(0, 0, 100, 100); Result Retrieving and passing a DOMMatrix object In the following example, we have two <canvas> elements. We apply a transform to the first one's context using the first type of setTransform() and draw a square on it, then retrieve the matrix from it using CanvasRenderingCont...
CanvasRenderingContext2D.shadowBlur - Web APIs
number of pixels, and is not affected by the current transformation matrix. The default value is 0. Negative, Infinity, and NaN values are ignored. Examples Adding a shadow to a shape This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, and shadowBlur sets its level of bluriness. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Shadow ctx.shadowColor = 'red'; ctx.shadowBlur = 15; // Rectangle ctx.fillStyle = 'blue'; ctx.fillRect(20, 20, 150, 100); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.shadowBlur' in that specification. Living Standard ...
CanvasRenderingContext2D.shadowOffsetX - Web APIs
the left. The default value is 0 (no horizontal offset). Infinity and NaN values are ignored. Examples Moving a shadow horizontally This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, shadowOffsetX sets its offset 25 units to the right, and shadowBlur gives it a blur level of 10. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Shadow ctx.shadowColor = 'red'; ctx.shadowOffsetX = 25; ctx.shadowBlur = 10; // Rectangle ctx.fillStyle = 'blue'; ctx.fillRect(20, 20, 150, 100); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.shadowOffsetX' in that specification. Living Standar...
CanvasRenderingContext2D.shadowOffsetY - Web APIs
are up. The default value is 0 (no vertical offset). Infinity and NaN values are ignored. Examples Moving a shadow vertically This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, shadowOffsetY sets its offset 25 units towards the bottom, and shadowBlur gives it a blur level of 10. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Shadow ctx.shadowColor = 'red'; ctx.shadowOffsetY = 25; ctx.shadowBlur = 10; // Rectangle ctx.fillStyle = 'blue'; ctx.fillRect(20, 20, 150, 80); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.shadowOffsetY' in that specification. Living Standard...
CanvasRenderingContext2D.textBaseline - Web APIs
ext baseline is the bottom of the bounding box. This differs from the ideographic baseline in that the ideographic baseline doesn't consider descenders. The default value is "alphabetic". Examples Comparison of property values This example demonstrates the various textBaseline property values. ...
CanvasRenderingContext2D.transform() - Web APIs
g. c (m21) Horizontal skewing. d (m22) Vertical scaling. A value of 1 results in no scaling. e (dx) Horizontal translation (moving). f (dy) Vertical translation (moving). Examples Skewing a shape This example skews a rectangle both vertically (.2) and horizontally (.8). Scaling and translation remain unchanged. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.transform(1, .2, .8, 1, 0, 0); ctx.fillRect(0, 0, 100, 100); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.transform' in that specification. Living Standard ...
CanvasRenderingContext2D.translate() - Web APIs
shape This example draws a square that is moved from its default position by the translate() method. An unmoved square of the same size is then drawn for comparison. HTML <canvas id="canvas"></canvas> JavaScript The translate() method translates the context by 110 horizontally and 30 vertically. The first square is shifted by those amounts from its default position. const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); // Moved square ctx.translate(110, 30); ctx.fillStyle = 'red'; ctx.fillRect(0, 0, 80, 80); // Reset current transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0); // Unmoved square ctx.fillStyle = 'gray'; ctx.fillRect(0, 0, 80, 80); Result The moved square is red, and the unmoved square is gray. Specifications ...
CanvasRenderingContext2D - Web APIs
low. The Canvas tutorial has more explanation, examples, and resources, as well. Basic example To get a CanvasRenderingContext2D instance, you must first have an HTML <canvas> element to work with: <canvas id="my-house" width="300" height="300"></canvas> To get the canvas' 2D rendering context, call getContext() on the <canvas> element, supplying '2d' as the argument: const canvas = document.
getElementById('my-house'); const ctx = canvas.getContext('2d'); With the context in hand, you can draw anything you like. This code draws a house: // Set line width ctx.lineWidth = 10; // Wall ctx.strokeRect(75, 140, 150, 110); // Door ctx.fillRect(130, 190, 40, 60); // Roof ctx.beginPath(); ctx.moveTo(50, 140); ctx.lineTo(150, 60); ctx.lineTo(250, 140); ctx.closePath(); ctx.stroke(); The resulting dra...
Compositing and clipping - Web APIs
path and turn it into a clipping path instead of stroking or filling the path. By default the <canvas> element has a clipping path that's the exact same size as the canvas itself. In other words, no clipping occurs. A clip example In this example, we'll use a circular clipping path to restrict the drawing of a set of random stars to a particular region. ...
Hit regions and accessibility - Web APIs
nvasRenderingContext2D.removeHitRegion() Removes the hit region with the specified id from the canvas. CanvasRenderingContext2D.clearHitRegions() Removes all hit regions 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. ...
Clipboard.readText() - Web APIs
tation among the DataTransfer objects representing the clipboard's contents. To read non-text contents from the clipboard, use the read() method instead. You can write text to the clipboard using writeText(). Example This example retrieves the textual contents of the clipboard and inserts the returned text into an element's contents. navigator.clipboard.readText().then( clipText => document.
getElementById("outbox").innerText = clipText); Specifications Specification Status Comment Clipboard API and eventsThe definition of 'readText()' in that specification. Working Draft Initial definition. ...
CustomElementRegistry.get() - Web APIs
ements.get(name); Parameters name The name of the custom element whose constructor you want to return a reference to. Return value The constructor for the named custom element, or undefined if there is no custom element definition with that name. ...
CustomElementRegistry.whenDefined() - Web APIs
ct when the custom elements that make up a menu are defined. The menu displays placeholder content until the actual menu content is ready to display. <nav id="menu-container"> <div class="menu-placeholder">Loading...</div> <nav-menu> <menu-item>Item 1</menu-item> <menu-item>Item 2</menu-item> ... <menu-item>Item N</menu-item> </nav-menu> </nav> const container = document.
getElementById('menu-container'); const placeholder = container.querySelector('.menu-placeholder'); // Fetch all the children of menu that are not yet defined. const undefinedElements = container.querySelectorAll(':not(:defined)'); const promises = [...undefinedElements].map( button => customElements.whenDefined(button.localName) ); // Wait for all the children to be upgraded, // then remove the placeholder...
DOMImplementation.createDocument() - Web APIs
the document to be created. documentType Optional Is the DocumentType of the document to be created. It defaults to null. Example var doc = document.implementation.createDocument ('http://www.w3.org/1999/xhtml', 'html', null); var body = document.createElementNS('http://www.w3.org/1999/xhtml', 'body'); body.setAttribute('id', 'abc'); doc.documentElement.appendChild(body); alert(doc.
getElementById('abc')); // [object HTMLBodyElement] Specifications Specification Status Comment DOMThe definition of 'DOMImplementation.createDocument' in that specification. Living Standard Modified the return type of createDocument() from Document to XMLDocument. The third argument of createDocument(), doctype, is now optional and default to null. Document Object ...
DOMMatrixReadOnly.flipX() - Web APIs
t="100" viewBox="-50 0 100 100"> <path fill="red" d="M 0 50 L 50 0 L 50 100 Z" /> <path id="flipped" fill="blue" d="M 0 50 L 50 0 L 50 100 Z" /> </svg> This JavaScript first creates an identity matrix, then uses the `flipX()` method to create a new matrix, which is then applied to the blue triangle, inverting it across the x-axis. The red triangle is left in place. const flipped = document.
getElementById('flipped'); const matrix = new DOMMatrixReadOnly(); const flippedMatrix = matrix.flipX(); flipped.setAttribute('transform', flippedMatrix.toString()); ScreenshotLive sample Specifications Specification Status Comment Geometry Interfaces Module Level 1The definition of 'DOMMatrixReadOnly.flipX()' in that specification. Candidate Recommendation Initial definition ...
DOMTokenList.supports() - Web APIs
The supports() method of the DOMTokenList interface returns true if a given token is in the associated attribute's supported tokens. This method is intended to support feature detection. Syntax let trueOrFalse = element.supports(token) Parameters token A DOMString containing the token to query for. Returns A Boolean indicating whether the token was found. ...
DataTransfer.dropEffect - Web APIs
a("text", ev.target.id); ev.dataTransfer.effectAllowed = "move"; } function drop_handler(ev) { console.log("drop: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.
getElementById(data)); } function dragover_handler(ev) { console.log("dragOver: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } Specifications Specification Status Comment HTML Living StandardThe definition of 'dropEffect' in that sp...
DataTransfer.effectAllowed - Web APIs
.setData("text", ev.target.id); ev.dataTransfer.effectAllowed = "move"; } function drop_handler(ev) { console.log("drop: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); // Get the id of the target and add the moved element to the target's DOM var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.
getElementById(data)); } function dragover_handler(ev) { console.log("dragOver: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } </script> <body> <h1>Examples <code>DataTransfer</code>.{<code>dropEffect</code>, <code>effectAllowed</code>} properties</h1> <div> <p...
DataTransfer.items - Web APIs
types[" + i + "] = " + ev.dataTransfer.types[i]); } } // Print each item's "kind" and "type" if (ev.dataTransfer.items != null) { for (var i=0; i < ev.dataTransfer.items.length; i++) { console.log("... items[" + i + "].kind = " + ev...
DataTransfer.types - Web APIs
types[" + i + "] = " + ev.dataTransfer.types[i]); } } // Print each item's "kind" and "type" if (ev.dataTransfer.items != null) { for (var i=0; i < ev.dataTransfer.items.length; i++) { console.log("... items[" + i + "].kind = " + ev...
DataTransferItem.getAsFile() - Web APIs
the getAsFile() method in a drop event handler. function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = event.dataTransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // This item is the target node data[i].getAsString(function (s){ ev.target.appendChild(document.
getElementById(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI console.log("... Drop: URI"); } else if ((data[i].kind == 'file') && (...
DataTransferItem.getAsString() - Web APIs
hod as an inline function in a drop event handler. function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // This item is the target node data[i].getAsString(function (s){ ev.target.appendChild(document.
getElementById(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI console.log("... Drop: URI"); } else if ((data[i].kind == 'file') && (...
DataTransferItem.kind - Web APIs
his example shows the use of the kind property. function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = event.dataTransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // This item is the target node data[i].getAsString(function (s){ ev.target.appendChild(document.
getElementById(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'file') && (data[i].type.match('^image/'))) { // Drag data item is an image file var f = data[i].getAsFile(); console.log("... Drop: File "); } } } Specific...
DataTransferItem.type - Web APIs
This example shows the use of the type property. function drop_handler(ev) { console.log("Drop"); ev.preventDefault(); var data = ev.dataTransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // This item is the target node data[i].getAsString(function (s){ ev.target.appendChild(document.
getElementById(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // Drag data item is HTML console.log("... Drop: HTML"); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI console.log("... Drop: URI"); } else if ((data[i].kind == 'file') && (...
DataTransferItemList.add() - Web APIs
Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ console...
DataTransferItemList.clear() - Web APIs
Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ console...
DataTransferItemList.length - Web APIs
Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ console...
DataTransferItemList.remove() - Web APIs
Drop: HTML = " + s); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/uri-list'))) { // Drag data item is URI data[i].getAsString(function (s){ console...
Document.URL - Web APIs
The URL read-only property of the Document interface returns the document location as a string. Syntax const url = document.URL Example JavaScript document.
getElementById("url").textContent = document.URL; HTML <p id="urlText"> URL:<br/> <span id="url">URL goes here</span> </p> Result Specifications Specification Status Comment DOMThe definition of 'Document.URL' in that specification. Living Standard Defines that the property is a USVString instead of a DOMString. ...
Document.adoptNode() - Web APIs
ied importedNode in the scope of the importing document. After calling this method, importedNode and externalNode are the same object. Note: importedNode's Node.parentNode is null, since it has not yet been inserted into the document tree! Example const iframe = document.querySelector('iframe'); const iframeImages = iframe.contentDocument.querySelectorAll('img'); const newParent = document.
getElementById('images'); iframeImages.forEach(function(imgEl) { newParent.appendChild(document.adoptNode(imgEl)); }); Notes Before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importNode(); or adopted using document.adoptNode(). Best Practice: Although Firefox doesn't currently enforce this rule, we encourage you to follow th...
Document.createAttribute() - Web APIs
es can be added to a particular element in this manner. The string given in parameter is converted to lowercase. Syntax attribute = document.createAttribute(name) Parameters name is a string containing the name of the attribute. Return value A Attr node. Exceptions INVALID_CHARACTER_ERR if the parameter contains invalid characters for XML attribute. Example var node = document.
getElementById("div1"); var a = document.createAttribute("my_attrib"); a.value = "newVal"; node.setAttributeNode(a); console.log(node.getAttribute("my_attrib")); // "newVal" Specifications Specification Status Comment DOMThe definition of 'Document.createAttribute()' in that specification. Living Standard Precised behavior with uppercase characters Document Object Model...
Document.createDocumentFragment() - Web APIs
istorically, using document fragments could result in better performance. You can also use the DocumentFragment constructor to create a new fragment: let fragment = new DocumentFragment(); Example This example creates a list of major web browsers in a DocumentFragment, then adds the new DOM subtree to the document to be displayed. ...
Document.createElement() - Web APIs
In this case, our custom element extends the HTMLUListElement, which represents the <ul> element. // Create a class for the element class ExpandingList extends HTMLUListElement { constructor() { // Al...
Document.createElementNS() - Web APIs
rom two different namespaces within a single document: <?xml version="1.0"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml" title="||Working with elements||" onload="init()"> <script type="application/javascript"><![CDATA[ let container; let newdiv; let txtnode; function init(){ container = document.
getElementById("ContainerBox"); newdiv = document.createElementNS("http://www.w3.org/1999/xhtml", "div"); txtnode = document.createTextNode("This is text that was constructed dynamically with createElementNS and createTextNode then inserted into the document using appendChild."); newdiv.appendChild(txtnode); container.appendChild(newdiv); } ]]></script> <vbox id="ContainerBox" flex="1"> <html:...
Document.createTextNode() - Web APIs
w Text node. This method can be used to escape HTML characters. Syntax var text = document.createTextNode(data); text is a Text node. data is a string containing the data to be put in the text node. ...
Document.createTouch() - Web APIs
for Touch.radiusY. rotationAngle The value for Touch.rotationAngle. force The value for Touch.force. Return value touch A Touch object configured as described by the input parameters. Example This example illustrates using the Document.createTouch() method to create Touch objects. In following code snippet, two Touch objects are created for the target element. var target = document.
getElementById("target"); var touch1 = Document.createTouch(window, target, 1, 15, 20, 35, 40); var touch2 = Document.createTouch(window, target, 2, 25, 30, 45, 50); Specifications Specification Status Comment Touch EventsThe definition of 'Document.createTouch()' in that specification. Recommendation Initial definition. ...
Document.createTouchList() - Web APIs
jects. Return value list A TouchList object containing the Touch objects specified by the touches parameter. Example This example illustrates using the Document.createTouchList() method to create TouchList objects. In following code snippet, some Touch objects are created for the target element and those touch points are then used to create some TouchList objects. ...
Document.documentURI - Web APIs
The documentURI read-only property of the Document interface returns the document location as a string. Syntax const uri = document.documentURI Example JavaScript document.
getElementById("url").textContent = document.documentURI; HTML <p id="urlText"> URL:<br/> <span id="url">URL goes here</span> </p> Result Specifications Specification Status Comment DOMThe definition of 'documentURI' in that specification. Living Standard ...
Document.getBoxObjectFor() - Web APIs
Returns a boxObject (x, y, width, height) for a specified element. Note: This method is obsolete. You should use the element.getBoundingClientRect() method instead. ...
Document.getElementsByTagNameNS() - Web APIs
tml xmlns="http://www.w3.org/1999/xhtml"> <head> <title>getElementsByTagNameNS example</title> <script type="text/javascript"> function getAllParaElems() { var allParas = document.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); var num = allParas.length; alert("There are " + num + " <p> elements in this document"); } function div1ParaElems() { var div1 = document.
getElementById("div1") var div1Paras = div1.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); var num = div1Paras.length; alert("There are " + num + " <p> elements in div1 element"); } function div2ParaElems() { var div2 = document.
getElementById("div2") var div2Paras = div2.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "p"); var num = div2Paras.length; alert("There...
Document.hasFocus() - Web APIs
ple checks whether the document has focus every 300 milliseconds. To test the functionality of hasFocus(), click on the button to open a new window, and try switching between the two pages. ...
Document.importNode() - Web APIs
refox 29 / Thunderbird 29 / SeaMonkey 2.26)), a shallow clone is defaulted instead of a deep clone. Return value The copied importedNode in the scope of the importing document. Note: importedNode's Node.parentNode is null, since it has not yet been inserted into the document tree! Example const iframe = document.querySelector("iframe"); const oldNode = iframe.contentWindow.document.
getElementById("myNode"); const newNode = document.importNode(oldNode, true); document.
getElementById("container").appendChild(newNode); Notes Before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importNode(); or adopted using document.adoptNode(). Best Practice: Although Firefox doesn't currently enforce this rule, we encourage y...
Document: keypress event - Web APIs
Yes Default Action 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: keyup event - Web APIs
sed 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. ...
Document.styleSheetSets - Web APIs
e styleSheetSets read-only property returns a live list of all of the currently-available style sheet sets. Syntax var sets = document.styleSheetSets; On return, sets is a list of style sheet sets that are available. ...
Document - Web APIs
eturns a Promise that resolves if the access to first-party storage was granted, and rejects if access was denied. Document.routeEvent() Obsolete since Gecko 24 See Window.routeEvent(). Document.mozSetImageElement() Allows you to change the element being used as the background image for a specified element ID. The Document interface is extended with the ParentNode interface: document.
getElementById(String id) Returns an object reference to the identified element. Document.querySelector() Returns the first Element node within the document, in document order, that matches the specified selectors. Document.querySelectorAll() Returns a list of all the Element nodes within the document that match the specified selectors. The Document interface is extended with the XPathEvaluator interface...
DocumentFragment - Web APIs
he methods of its parent, Node, and implements those of the ParentNode interface. DocumentFragment.querySelector() Returns the first Element node within the DocumentFragment, in document order, that matches the specified selectors. DocumentFragment.querySelectorAll() Returns a NodeList of all the Element nodes within the DocumentFragment that match the specified selectors. DocumentFragment.
getElementById() Returns the first Element node within the DocumentFragment, in document order, that matches the specified ID. Functionally equivalent to Document.
getElementById(). Usage notes A common use for DocumentFragment is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM using Node interface methods such as appendChild() or insertBefore(). Doing this mo...
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
erates in a similar way to the elementFromPoint() method. Syntax const elements = document.elementsFromPoint(x, y); Parameters x The horizontal coordinate of a point. y The vertical coordinate of a point. Return value An array of element objects. ...
DocumentOrShadowRoot.nodeFromPoint() - Web APIs
available to chrome code. Syntax var node = document.nodeFromPoint(x, y); Parameters x A double representing the horizontal coordinate of a point. y A double representing the vertical coordinate of a point. Returns A Node object. Examples HTML Content <div> <p>Some text</p> </div> <p>Top node at point 30, 20:</p> <div id="output"></div> JavaScript Content var output = document.
getElementById("output"); if (document.nodeFromPoint) { var node = document.nodeFromPoint(30, 20); output.textContent += node.localName; } else { output.innerHTML = "<span style=\"color: red;\">" + "Browser does not support <code>document.nodeFromPoint()</code>" + "</span>"; } Specifications Not part of any specification at present. ...
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
y implemented in Firefox, and only available to chrome code. Syntax var nodes = document.nodesFromPoint(x, y); Parameters x The horizontal coordinate of a point. y The vertical coordinate of a point. Returns An array of Node objects. ...
EffectTiming.direction - Web APIs
verse" Similar to "alternate", except the animation playback starts by going from the end of the animation sequence toward the beginning the first iteration, then goes forward during the second, and so forth. Examples In the Forgotten Key example, Alice waves her arm up and down by passing her an alternate value for her direction property: // Get Alice's arm, and wave it up and down document.
getElementById("alice_arm").animate([ { transform: 'rotate(10deg)' }, { transform: 'rotate(-40deg)' } ], { easing: 'steps(2, end)', iterations: Infinity, direction: 'alternate', duration: 600 }); Specifications Specification Status Comment Web AnimationsThe definition of 'direction' in that specification. Working Draft Editor's draft. ...
EffectTiming.easing - Web APIs
start) step-end Equivalent to steps(1, end). Examples In the Red Queen's Race example, we animate Alice and the Red Queen by passing an easing of steps(7, end) to animate(): // Define the key frames var spriteFrames = [ { transform: 'translateY(0)' }, { transform: 'translateY(-100%)' } ]; // Get the element that represents Alice and the Red Queen var redQueen_alice_sprite = document.
getElementById('red-queen_and_alice_sprite'); // Animate Alice and the Red Queen using steps() var redQueen_alice = redQueen_alice_sprite.animate( spriteFrames, { easing: 'steps(7, end)', direction: "reverse", duration: 600, playbackRate: 1, iterations: Infinity }); Specifications Specification Status Comment Web AnimationsThe definition of 'easing' in that specification. ...
EffectTiming.iterations - Web APIs
e then stops automatically. Exceptions TypeError An attempt was made to set the value of this property to a negative number or NaN. The property's value is left unchanged. Examples In the Forgotten Key example, Alice waves her arm up and down the entire time the page is open by passing Infinity as the value for her iterations property: // Get Alice's arm, and wave it up and down document.
getElementById("alice_arm").animate([ { transform: 'rotate(10deg)' }, { transform: 'rotate(-40deg)' } ], { easing: 'steps(2, end)', iterations: Infinity, direction: 'alternate', duration: 600 }); Specifications Specification Status Comment Web AnimationsThe definition of 'iterations' in that specification. Working Draft Editor's draft. ...
Element.animate() - Web APIs
mulate or replace (see above). Defaults to replace. Return value Returns an Animation. Examples In the demo Down the Rabbit Hole (with the Web Animation API), we use the convenient animate() method to immediately create and play an animation on the #tunnel element to make it flow upwards, infinitely. Notice the array of objects passed as keyframes and also the timing options block. document.
getElementById("tunnel").animate([ // keyframes { transform: 'translateY(0px)' }, { transform: 'translateY(-300px)' } ], { // timing options duration: 1000, iterations: Infinity }); Implicit to/from keyframes In newer browser versions, you are able to set a beginning or end state for an animation only (i.e. a single keyframe), and the browser will infer the other end of the animation if it is ab...
Element: blur event - Web APIs
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. 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 Ev...
Element.className - Web APIs
The className property of the Element interface gets and sets the value of the class attribute of the specified element. Syntax var cName = elementNodeReference.className; elementNodeReference.className = cName; cName is a string variable representing the class or space-separated classes of the current element. Example let el = document.
getElementById('item'); if (el.className === 'active'){ el.className = 'inactive'; } else { el.className = 'active'; } Notes The name className is used for this property instead of class because of conflicts with the "class" keyword in many languages which are used to manipulate the DOM. className can also be an instance of SVGAnimatedString if the element is an SVGElement. It is better to get/set the className of an element using Element.getAttribute an...
Element.closest() - Web APIs
closestElement is the Element which is the closest ancestor of the selected element. It may be null. Exceptions SyntaxError is thrown if the selectors is not a valid selector list string. ...
Element: contextmenu event - Web APIs
entDefault() when the contextmenu event is fired 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: focus event - Web APIs
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. 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 Ev...
Element: focusin event - Web APIs
f focusin is focusout. Bubbles Yes Cancelable No Interface FocusEvent Event handler property onfocusin Sync / Async Sync Composed Yes Examples Live example HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> JavaScript const form = document.
getElementById('form'); form.addEventListener('focusin', (event) => { event.target.style.background = 'pink'; }); form.addEventListener('focusout', (event) => { event.target.style.background = ''; }); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Document Object Model (DOM) Level 3 Events S...
Element: focusout event - Web APIs
focusout is focusin. Bubbles Yes Cancelable No Interface FocusEvent Event handler property onfocusout Sync / Async Sync Composed Yes Examples Live example HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> JavaScript const form = document.
getElementById('form'); form.addEventListener('focusin', (event) => { event.target.style.background = 'pink'; }); form.addEventListener('focusout', (event) => { event.target.style.background = ''; }); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Document Object Model (DOM) Level 3 Events S...
Element.getAttribute() - Web APIs
the element. If the given attribute does not exist, the value returned will either be null or "" (the empty string); see Non-existing attributes for details. Syntax let attribute = element.getAttribute(attributeName); where attribute is a string containing the value of attributeName. attributeName is the name of the attribute whose value you want to get. Examples const div1 = document.
getElementById('div1'); const align = div1.getAttribute('align'); alert(align); // Shows the value of align for the element with id="div1" Description Lower casing When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding. Non-existing attributes Essentially all web browsers (Firefox, Internet Explorer, recent versions of Opera, Safari, ...
Element.getAttributeNode() - Web APIs
Returns the specified attribute of the specified element, as an Attr node. Syntax var attrNode = element.getAttributeNode(attrName); attrNode is an Attr node for the attribute. attrName is a string containing the name of the attribute. Example // html: <div id="top" /> let t = document.
getElementById("top"); let idAttr = t.getAttributeNode("id"); alert(idAttr.value == "top") Notes When called on an HTML element in a DOM flagged as an HTML document, getAttributeNode lower-cases its argument before proceeding. The Attr node inherits from Node, but is not considered a part of the document tree. Common Node attributes like parentNode, previousSibling, and nextSibling are null for an Attr node. You can, however, get the element to which the attribute belongs with the ownerElement property. ge...
Element.getAttributeNodeNS() - Web APIs
or the attribute with the given namespace and name. Syntax attributeNode = element.getAttributeNodeNS(namespace, nodeName) attributeNode is the node for specified attribute. namespace is a string specifying the namespace of the attribute. nodeName is a string specifying the name of the attribute. == Example == TBD The example needs to be fixed pre> // html: <div id="top" /> t = document.
getElementById("top"); specialNode = t.getAttributeNodeNS( "http://www.mozilla.org/ns/specialspace", "id"); // iNode.value = "full-top" </pre Notes getAttributeNodeNS is more specific than getAttributeNode in that it allows you to specify attributes that are part of a particular namespace. The corresponding setter method is setAttributeNodeNS. DOM methods dealing with element's attributes: Not namespace-a...
Element.getElementsByClassName() - Web APIs
herwise, they're case sensitive. Examples Matching a single class To look for elements that include among their classes a single specified class, we just provide that class name when calling getElementsByClassName(): element.getElementsByClassName('test'); This example finds all elements that have a class of test, which are also a descendant of the element that has the id of main: document.
getElementById('main').getElementsByClassName('test'); Matching multiple classes To find elements whose class lists include both the red and test classes: element.getElementsByClassName('red test'); Examining the results You can use either the item() method on the returned HTMLCollection or standard array syntax to examine individual elements in the collection. However the following code will not work as o...
Element.getElementsByTagName() - Web APIs
ents are found, the HTMLCollection is empty. element is the element from where the search starts. Only the element's descendants are included, not the element itself. tagName is the qualified name to look for. The special string "*" represents all elements. For compatibility with XHTML, lower-case should be used. Example // Check the status of each data cell in a table const table = document.
getElementById('forecast-table'); const cells = table.getElementsByTagName('td'); for (let cell of cells) { let status = cell.getAttribute('data-status'); if (status === 'open') { // Grab the data } } Specifications Specification Status Comment DOMThe definition of 'Element.getElementsByTagName()' in that specification. Living Standard Changed the return value from No...
Element.getElementsByTagNameNS() - Web APIs
d Attr.namespaceURI). For example, if you need to look for XHTML elements, use the XHTML namespace URI, http://www.w3.org/1999/xhtml. localName is either the local name of elements to look for or the special value "*", which matches all elements (see Element.localName and Attr.localName). Example // check the alignment on a number of cells in a table in an XHTML document. var table = document.
getElementById("forecast-table"); var cells = table.getElementsByTagNameNS("http://www.w3.org/1999/xhtml", "td"); for (var i = 0; i < cells.length; i++) { var axis = cells[i].getAttribute("axis"); if (axis == "year") { // grab the data } } Specifications Specification Status Comment DOMThe definition of 'Element.getElementsByTagNameNS()' in that specification. L...
Element.hasAttribute() - Web APIs
The Element.hasAttribute() method returns a Boolean value indicating whether the specified element has the specified attribute or not. Syntax var result = element.hasAttribute(name); result holds the return value true or false. name is a string representing the name of the attribute. ...
Element.hasAttributeNS() - Web APIs
uteNS returns a boolean value indicating whether the current element has the specified attribute. Syntax result = element.hasAttributeNS(namespace,localName) result is the boolean value true or false. namespace is a string specifying the namespace of the attribute. localName is the name of the attribute. ...
Element.hasAttributes() - Web APIs
The hasAttributes() method of the Element interface returns a Boolean indicating whether the current element has any attributes or not. Syntax var result = element.hasAttributes(); Return value result holds the return value true or false. Examples let foo = document.
getElementById('foo'); if (foo.hasAttributes()) { // Do something with 'foo.attributes' } Polyfill ;(function(prototype) { prototype.hasAttributes = prototype.hasAttributes || function() { return (this.attributes.length > 0); } })(Element.prototype); Specifications Specification Status Comment DOMThe definition of 'Element.hasAttributes()' in that specification. Living Standard Moved from the Node interface to the more specialized Element interface. Document Object Model (...
Element.id - Web APIs
Another common case is to use an element's ID as a selector when styling the document with CSS. Note: Identifiers are case-sensitive, but you should avoid creating IDs that differ only in the capitalization. ...
Element.insertAdjacentHTML() - Web APIs
the element itself. text The string to be parsed as HTML or XML and inserted into the tree. Visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> Note: The beforebegin and afterend positions work only if the node is in the DOM tree and has a parent element. Example // <div id="one">one</div> var d1 = document.
getElementById('one'); d1.insertAdjacentHTML('afterend', '<div id="two">two</div>'); // At this point, the new structure is: // <div id="one">one</div><div id="two">two</div> Notes Security considerations When inserting HTML into a page by using insertAdjacentHTML(), be careful not to use user input that hasn't been escaped. It is not recommended you use insertAdjacentHTML() when inserting plain text; inst...
Element: keydown event - Web APIs
=> { 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. ...
Element: keypress event - Web APIs
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 after focussing the <input> element. ...
Element: keyup event - Web APIs
{ 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. ...
Element: mousedown event - Web APIs
line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.
getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mousedown, mousemove, and mouseup myPics.addEventListener('mousedown', e => { x = e.offsetX; y = e.offsetY; isDrawing = true; }); myPics.addEventListener('mousemove', e => { if (isDrawing === true) { drawLine(context,...
Element: mousemove event - Web APIs
line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.
getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mousedown, mousemove, and mouseup myPics.addEventListener('mousedown', e => { x = e.offsetX; y = e.offsetY; isDrawing = true; }); myPics.addEventListener('mousemove', e => { if (isDrawing === true) { drawLine(context,...
Element: mouseout event - Web APIs
e targeted element orange when the mouse exits it. When you try this out, you'll find that mouseout is delivered 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>. ...
Element: mouseover event - Web APIs
to the element or one of its child elements. Bubbles Yes Cancelable Yes Interface MouseEvent Event handler property onmouseover Examples The following example illustrates the difference between mouseover and mouseenter events. ...
Element: mouseup event - Web APIs
line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.
getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mousedown, mousemove, and mouseup myPics.addEventListener('mousedown', e => { x = e.offsetX; y = e.offsetY; isDrawing = true; }); myPics.addEventListener('mousemove', e => { if (isDrawing === true) { drawLine(context,...
Element: overflow event - Web APIs
les <div id="wrapper"> <div id="child"></div> </div> <br/> <label><input type="checkbox" id="toggle" checked/> Overflow</label> <style> #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.check...
Element.querySelector() - Web APIs
document is considered when applying selectors, so that levels outside the specified baseElement are still considered when locating matches. HTML <div> <h5>Original content</h5> <p> inside paragraph <span>inside span</span> inside paragraph </p> </div> <div> <h5>Output</h5> <div id="output"></div> </div> JavaScript var baseElement = document.querySelector("p"); document.
getElementById("output").innerHTML = (baseElement.querySelector("div span").innerHTML); Result The result looks like this: Notice how the "div span" selector still successfully matches the <span> element, even though the baseElement's child nodes do not include the div element (it is still part of the specified selector). More examples See Document.querySelector() for additional examples of the proper ...
Element.removeAttributeNS() - Web APIs
element. Syntax element.removeAttributeNS(namespace, attrName); Parameters namespace is a string that contains the namespace of the attribute. attrName is a string that names the attribute to be removed from the current node. ...
Element.removeAttributeNode() - Web APIs
The removeAttributeNode() method of the Element object removes the specified attribute from the current element. Syntax removedAttr = element.removeAttributeNode(attributeNode) attributeNode is the Attr node that needs to be removed. removedAttr is the removed Attr node. Example // Given: <div id="top" align="center" /> var d = document.
getElementById("top"); var d_align = d.getAttributeNode("align"); d.removeAttributeNode(d_align); // align is now removed: <div id="top" /> Notes If the removed attribute has a default value, it is immediately replaced. The replacing attribute has the same namespace URI and local name, as well as the original prefix, when applicable. There is no removeAttributeNodeNS method; the removeAttributeNode method can remove both namespaced attributes and non-names...
Element.scrollHeight - Web APIs
dius: 5px; width: 600px; padding: 5px; border: 2px #7FDF55 solid; } #rules { width: 600px; height: 130px; padding: 5px; border: #2A9F00 solid 2px; border-radius: 5px; } JavaScript function checkReading () { if (checkReading.read) { return; } checkReading.read = this.scrollHeight - this.scrollTop === this.clientHeight; document.registration.accept.disabled = document.
getElementById("nextstep").disabled = !checkReading.read; checkReading.noticeBox.innerHTML = checkReading.read ? "Thank you." : "Please, scroll and read the following text."; } onload = function () { var oToBeRead = document.
getElementById("rules"); checkReading.noticeBox = document.createElement("span"); document.registration.accept.checked = false; checkReading.noticeBox.id = "notice"; oToBeRead.
Element.scrollIntoView() - Web APIs
n Object with the following properties: behavior Optional Defines the transition animation. One of auto or smooth. Defaults to auto. block Optional Defines vertical alignment. One of start, center, end, or nearest. Defaults to start. inline Optional Defines horizontal alignment. One of start, center, end, or nearest. Defaults to nearest. Example var element = document.
getElementById("box"); element.scrollIntoView(); element.scrollIntoView(false); element.scrollIntoView({block: "end"}); element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"}); Notes The element may not be scrolled completely to the top or bottom depending on the layout of other elements. Specifications Specification Status Comment CSS Object Model (CSSOM)...
Element.scrollIntoViewIfNeeded() - Web APIs
ancestor. If false, the element will be aligned to the nearest edge of the visible area of the scrollable ancestor. Depending on which edge of the visible area is closest to the element, either the top of the element will be aligned to the top edge of the visible area, or the bottom edge of the element will be aligned to the bottom edge of the visible area. Example var element = document.
getElementById("my-el"); element.scrollIntoViewIfNeeded(); element.scrollIntoViewIfNeeded(true); // Centers the element in the visible area Specifications Not part of any specification. This is a proprietary, WebKit-specific method. ...
Element.scrollLeft - Web APIs
e scrolled, scrollLeft is set to the maximum. Example HTML <div id="container"> <div id="content">Click the button to slide right!</div> </div> <button id="slide" type="button">Slide right</button> CSS #container { width: 100px; height: 100px; border: 1px solid #ccc; overflow-x: scroll; } #content { width: 250px; background-color: #ccc; } JavaScript const button = document.
getElementById('slide'); button.onclick = function () { document.
getElementById('container').scrollLeft += 20; }; Result Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'scrollLeft' in that specification. Working Draft ...
Element.scrollWidth - Web APIs
margin-bottom: 2em; } </style> </head> <body> <div id="aDiv"> FooBar-FooBar-FooBar-FooBar </div> <button id="aButton"> Check for overflow </button> <div id="anotherDiv"> FooBar-FooBar-FooBar-FooBar </div> <button id="anotherButton"> Check for overflow </button> </body> <script> var buttonOne = document.
getElementById('aButton'), buttonTwo = document.
getElementById('anotherButton'), divOne = document.
getElementById('aDiv'), divTwo = document.
getElementById('anotherDiv'); //check to determine if an overflow is happening function isOverflowing(element) { return (element.scrollWidth > element.offsetWidth); } function alertOverflow(element) { if (isOverflowing(element)...
Element: select event - Web APIs
Event otherwise Event handler property onselect The event is not available for all elements in all languages. For example, in HTML, select events can be dispatched only on form <input type="text"> and <textarea> elements. ...
Element.setAttributeNS() - Web APIs
an attribute with the given namespace and name. Syntax element.setAttributeNS(namespace, name, value) namespace is a string specifying the namespace of the attribute. name is a string identifying the attribute by its qualified name; that is, a namespace prefix followed by a colon followed by a local name. value is the desired string value of the new attribute. ...
Element.setAttributeNode() - Web APIs
e specified element. Syntax var replacedAttr = element.setAttributeNode(attribute); attribute is the Attr node to set on the element. replacedAttr is the replaced attribute node, if any, returned by this function. Example This example copies the align attribute from one element to another. HTML <div id="one" align="left">one</div> <div id="two">two</div> JavaScript let d1 = document.
getElementById('one'); let d2 = document.
getElementById('two'); let a = d1.getAttributeNode('align'); d2.setAttributeNode(a.cloneNode(true)); // Returns: 'left' alert(d2.attributes[1].value); Notes If the attribute named already exists on the element, that attribute is replaced with the new one and the replaced one is returned. This method is seldom used, with Element.setAttribute() usually being used to ...
Element.setAttributeNodeNS() - Web APIs
Attr = element.setAttributeNodeNS(attributeNode) replacedAttr is the replaced attribute node, if any, returned by this function. attributeNode is an Attr node. Example // <div id="one" xmlns:myNS="http://www.mozilla.org/ns/specialspace" // myNS:special-align="utterleft">one</div> // <div id="two">two</div> var myns = "http://www.mozilla.org/ns/specialspace"; var d1 = document.
getElementById("one"); var d2 = document.
getElementById("two"); var a = d1.getAttributeNodeNS(myns, "special-align"); d2.setAttributeNodeNS(a.cloneNode(true)); alert(d2.attributes[1].value) // returns: `utterleft' Notes If the specified attribute already exists on the element, then that attribute is replaced with the new one and the replaced one is returned. Note that if you try to set without cloning the n...
Element: show event - Web APIs
a contextmenu event was 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.tagName - Web APIs
re returned in the same case in which they're written in the original XML file. If an XML document includes a tag "<SomeTag>", then the tagName property's value is "SomeTag". For Element objects, the value of tagName is the same as the value of the nodeName property the element object inherits from Node. Example HTML <span id="born">When I was born...</span> JavaScript var span = document.
getElementById("born"); console.log(span.tagName); In XHTML (or any other XML format), the original case will be maintained, so "span" would be output in case the original tag name was created lowercase. In HTML, "SPAN" would be output instead regardless of the case used while creating the original document. Specifications Specification Status Comment DOMThe definition of 'Element: t...
Element: underflow event - Web APIs
les <div id="wrapper"> <div id="child"></div> </div> <br/> <label><input type="checkbox" id="toggle" checked/> Overflow</label> <style> #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.check...
ElementCSSInlineStyle.style - Web APIs
perties for an element you should use Window.getComputedStyle() instead. The following code snippet demonstrates the difference between the values obtained using the element's style property and that obtained using the getComputedStyle() method: <!DOCTYPE HTML> <html> <body style="font-weight:bold;"> <div style="color:red" id="myElement">..</div> </body> </html> var element = document.
getElementById("myElement"); var out = ""; var elementStyle = element.style; var computedStyle = window.getComputedStyle(element, null); for (prop in elementStyle) { if (elementStyle.hasOwnProperty(prop)) { out += " " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n"; } } console.log(out) The output would be something like: ... fontWeight = '' > 'bold' color = 'red' > 'rg...
Event.eventPhase - Web APIs
d3 <div id="d4">d4</div> </div> </div> </div> <div id="divInfo"></div> CSS div { margin: 20px; padding: 4px; border: thin black solid; } #divInfo { margin: 18px; padding: 8px; background-color:white; font-size:80%; } JavaScript let clear = false, divInfo = null, divs = null, useCapture = false; window.onload = function () { divInfo = document.
getElementById('divInfo') divs = document.getElementsByTagName('div') chCapture = document.
getElementById('chCapture') chCapture.onclick = function () { RemoveListeners() AddListeners() } Clear() AddListeners() } function RemoveListeners() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divInfo") { d.removeEventListener("click", OnDivClick, true) ...
Event.msConvertURL() - Web APIs
ertURL(file, targetType, targetURL); 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.crea...
Event.timeStamp - Web APIs
ewer implementations, the value is a DOMHighResTimeStamp accurate to 5 microseconds (0.005 ms). In older implementations, the value is a DOMTimeStamp, accurate to a millisecond. Example HTML <p> Focus this iframe and press any key to get the current timestamp for the keypress event. </p> <p>timeStamp: <span id="time">-</span></p> JavaScript function getTime(event) { var time = document.
getElementById("time"); time.firstChild.nodeValue = event.timeStamp; } document.body.addEventListener("keypress", getTime); Result Reduced time precision To offer protection against timing attacks and fingerprinting, the precision of Event.timeStamp might get rounded depending on browser settings. In Firefox, the privacy.reduceTimerPrecision preference is enabled by default and defaults to 20us in Firef...
Event.type - Web APIs
list of available event types, see the event reference. Syntax let eventType = event.type; Value A DOMString containing the type of Event. Example This example logs the event type whenever you press a keyboard key or click a mouse button. ...
EventListener - Web APIs
vent() property function. This is shown in the example below. Properties This interface neither implements, nor inherits, any properties. Methods This interface doesn't inherit any methods. 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. 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...
Using Fetch - Web APIs
Body mixin defines the following methods to extract a body (implemented by both Request and Response). These all return a promise that is eventually resolved with the actual content. arrayBuffer() blob() json() text() formData() This makes usage of non-textual data much easier than it was with XHR. Request bodies can be set by passing body parameters: const form = new FormData(document.
getElementById('login-form')); fetch('/login', { method: 'POST', body: form }); Both request and response (and by extension the fetch() function), will try to intelligently determine the content type. A request will also automatically set a Content-Type header if none is set in the dictionary. Feature detection Fetch API support can be detected by checking for the existence of Headers, Request, Response...
File.getAsBinary() - Web APIs
ummary The getAsBinary method allows to access the file's data in raw binary format. Note: This method is obsolete; you should use the FileReader method readAsBinaryString() or readAsArrayBuffer() instead. Syntax var binary = instanceOfFile.getAsBinary(); Returns A string. ...
File.getAsText() - Web APIs
. Syntax var str = instanceOfFile.getAsText(encoding); Parameters encoding A string indicating the encoding to use for the returned data. If this string is empty, UTF-8 is assumed. Returns A string containing the file's data interpreted as text in the specified encoding. ...
File.lastModifiedDate - Web APIs
odifiedDate read-only property returns the last modified date of the file. Files without a known last modified date returns the current date . Syntax var time = instanceOfFile.lastModifiedDate Value A Date object indicating the date and time at which the file was last modified. ...
FormData() - Web APIs
div> <div> <label for="userfile">Upload file:</label> <input type="file" id="userfile" name="userfile"> </div> <input type="submit" value="Submit!"> </form> Note: Only successful form controls are included in a FormData object, i.e. those with a name, not disabled and checked (radio buttons and checkboxes) or selected (one or more options within a select). let myForm = document.
getElementById('myForm'); let formData = new FormData(myForm); Specifications Specification Status Comment XMLHttpRequestThe definition of 'FormData()' in that specification. Living Standard Initial definition ...
Guide to the Fullscreen API - Web APIs
'd like to present in full-screen mode (such as a <video>, for example), you can present it in full-screen mode by simply calling its requestFullscreen() method. Let's consider this <video> element: <video controls id="myvideo"> <source src="somevideo.webm"></source> <source src="somevideo.mp4"></source> </video> We can put that video into full-screen mode as follows: var elem = document.
getElementById("myvideo"); if (elem.requestFullscreen) { elem.requestFullscreen(); } This code checks for the existence of the requestFullscreen() method before calling it. Presentation differences It's worth noting a key difference here between the Gecko and WebKit implementations at this time: Gecko automatically adds CSS rules to the element to stretch it to fill the screen: "width: 100%; height: 100%".
GlobalEventHandlers.onchange - Web APIs
nction receives an Event object as its sole argument. Example This example logs the number of characters in an <input> element, every time you modify its contents and then change focus away from it. HTML <input type="text" placeholder="Type something here, then click outside of the field." size="50"> <p id="log"></p> JavaScript let input = document.querySelector('input'); let log = document.
getElementById('log'); input.onchange = handleChange; function handleChange(e) { log.textContent = `The field's value is ${e.target.value.length} character(s) long.`; } Result Specification Specification Status Comment HTML Living StandardThe definition of 'onchange' in that specification. Living Standard ...
GlobalEventHandlers.onclick - Web APIs
nction, 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 Getting the coordinates of clicks This example displays the coordinates at which the most recent mouse button click occurred. HTML <p>Click anywhere in this example.</p> <p id="log"></p> JavaScript let log = document.ge...
GlobalEventHandlers.ondblclick - Web APIs
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 Specification Status Comment HTML Living StandardThe definition of 'ondblclick' in that specification. Living Standard ...
GlobalEventHandlers.ondrag - Web APIs
ck; } </style> </head> <script> function drag_handler(ev) { console.log("Drag"); } function dragstart_handler(ev) { console.log("dragStart"); ev.dataTransfer.setData("text", ev.target.id); } function drop_handler(ev) { console.log("Drop"); ev.currentTarget.style.background = "lightyellow"; ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.
getElementById(data)); } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); } </script> <body> <h1>Examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <!-- <div class="source"> --> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it...
GlobalEventHandlers.ondragover - Web APIs
ck; } </style> </head> <script> function drag_handler(ev) { console.log("Drag"); } function dragstart_handler(ev) { console.log("dragStart"); ev.dataTransfer.setData("text", ev.target.id); } function drop_handler(ev) { console.log("Drop"); ev.currentTarget.style.background = "lightyellow"; ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.
getElementById(data)); } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); } </script> <body> <h1>Examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then rel...
GlobalEventHandlers.ondragstart - Web APIs
ck; } </style> </head> <script> function drag_handler(ev) { console.log("Drag"); } function dragstart_handler(ev) { console.log("dragStart"); ev.dataTransfer.setData("text", ev.target.id); } function drop_handler(ev) { console.log("Drop"); ev.currentTarget.style.background = "lightyellow"; ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.
getElementById(data)); } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); } </script> <body> <h1>Examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then rel...
GlobalEventHandlers.ondrop - Web APIs
ck; } </style> </head> <script> function drag_handler(ev) { console.log("Drag"); } function dragstart_handler(ev) { console.log("dragStart"); ev.dataTransfer.setData("text", ev.target.id); } function drop_handler(ev) { console.log("Drop"); ev.currentTarget.style.background = "lightyellow"; ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.
getElementById(data)); } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); } </script> <body> <h1>Examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div class="source"> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zo...
GlobalEventHandlers.ongotpointercapture - Web APIs
rcapture events. Syntax target.ongotpointercapture = functionRef; Value functionRef is a function name or a function expression. The function receives a PointerEvent object as its sole argument. Example function overHandler(event) { // Determine the target event's gotpointercapture handler let gotCaptureHandler = event.target.ongotpointercapture; } function init() { let el = document.
getElementById('target'); el.ongotpointercapture = overHandler; } Specifications Specification Status Comment Pointer Events - Level 2The definition of 'ongotpointercapture' in that specification. Recommendation ...
GlobalEventHandlers.oninput - Web APIs
unction name or a function expression. The function receives an InputEvent object as its sole argument. Example This example logs the number of characters in an <input> element, every time you modify its contents. HTML <input type="text" placeholder="Type something here to see its length." size="50"> <p id="log"></p> JavaScript let input = document.querySelector('input'); let log = document.
getElementById('log'); input.oninput = handleInput; function handleInput(e) { log.textContent = `The field's value is ${e.target.value.length} character(s) long.`; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'oninput' in that specification. Living Standard Initial definition ...
GlobalEventHandlers.onkeydown - Web APIs
Syntax target.onkeydown = functionRef; Value functionRef is a function name or a function expression. The function receives a KeyboardEvent object as its sole argument. Example This example logs the KeyboardEvent.code value whenever you press down a key inside the <input> element. HTML <input> <p id="log"></p> JavaScript const input = document.querySelector('input'); const log = document.
getElementById('log'); input.onkeydown = logKey; function logKey(e) { log.textContent += ` ${e.code}`; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'onkeydown' in that specification. Living Standard ...
GlobalEventHandlers.onkeypress - Web APIs
t.onkeypress = functionRef; Value functionRef is a function name or a function expression. The function receives a KeyboardEvent object as its sole argument. Examples Basic example This example logs the KeyboardEvent.code value whenever you press a key inside the <input> element. HTML <input> <p id="log"></p> JavaScript const input = document.querySelector('input'); const log = document.
getElementById('log'); input.onkeypress = logKey; function logKey(e) { log.textContent += ` ${e.code}`; } Result Filter keys with a regular expression This example filters the characters typed into a form field using a regular expression. HTML <label>Enter numbers only: <input> </label> JavaScript function numbersOnly(event) { return event.charCode === 0 || /\d/.test(String.fromCharCode(event.c...
GlobalEventHandlers.onkeyup - Web APIs
ed. Syntax target.onkeyup = functionRef; Value functionRef is a function name or a function expression. The function receives a KeyboardEvent object as its sole argument. Example This example logs the KeyboardEvent.code value whenever you release a key inside the <input> element. HTML <input> <p id="log"></p> JavaScript const input = document.querySelector('input'); const log = document.
getElementById('log'); input.onkeyup = logKey; function logKey(e) { log.textContent += ` ${e.code}`; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'onkeyup' in that specification. Living Standard ...
GlobalEventHandlers.onlostpointercapture - Web APIs
ture events. Syntax target.onlostpointercapture = functionRef; Value functionRef is a function name or a function expression. The function receives a PointerEvent object as its sole argument. Example function overHandler(event) { // Determine the target event's lostpointercapture handler let lostCaptureHandler = event.target.onlostpointercapture; } function init() { let el = document.
getElementById('target'); el.onlostpointercapture = overHandler; } Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onlostpointercapture' in that specification. Recommendation ...
GlobalEventHandlers.onpointercancel - Web APIs
onpointercancel = cancelHandler; var cancelHandler = targetElement.onpointercancel; Value cancelHandler The pointercancel event handler for element targetElement. Example This example shows two ways to use onpointercancel to handle an element's pointercancel events. <html> <script> function cancelHandler(ev) { // Process the pointercancel event } function init() { var el = document.
getElementById('target1'); el.onpointercancel = cancelHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointercancel="cancelHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointercancel' in that specification. Recommendation...
GlobalEventHandlers.onpointerdown - Web APIs
down 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. ...
GlobalEventHandlers.onpointerenter - Web APIs
ement.onpointerenter = enterHandler; var enterHandler = targetElement.onpointerenter; Value enterHandler The pointerenter event handler for element targetElement. Example This example shows two ways to use onpointerenter to set an element's pointerenter event handler. <html> <script> function enterHandler(ev) { // Process the pointerenter event } function init() { let el = document.
getElementById('target1'); el.onpointerenter = enterHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointerenter="enterHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointerenter' in that specification. Recommendation N...
GlobalEventHandlers.onpointerleave - Web APIs
aveHandler; var leaveHandler = EventTarget.onpointerleave; Value leaveHandler The EventListener which will be invoked to handle pointerleave events sent to the target. Example This example shows two ways to use onpointerleave to set an element's pointerleave event handler. <html> <script> function leaveHandler(ev) { // Process the pointerleave event } function init() { var el=document.
getElementById("target1"); el.onpointerleave = leaveHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointerleave="leaveHandler(event)"> Touch me ... </div> </body> </html> See Using Pointer Events for additional details. Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointerleave' i...
GlobalEventHandlers.onpointermove - Web APIs
ax targetElement.onpointermove = moveHandler; var moveHandler = targetElement.onpointermove; Value moveHandler The pointermove event handler for element targetElement. Example This example shows two ways to use onpointermove to set an element's pointermove event handler. <html> <script> function moveHandler(ev) { // Process the pointermove event } function init() { let el=document.
getElementById('target1'); el.onpointermove = moveHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointermove="moveHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointermove' in that specification. Recommendation Non-st...
GlobalEventHandlers.onpointerout - Web APIs
nts. Syntax targetElement.onpointerout = outHandler; var outHandler = targetElement.onpointerout; Value outHandler The pointerout event handler for element targetElement. Example This example shows two ways to use onpointerout to set an element's pointerout event handler. <html> <script> function outHandler(ev) { // Process the pointerout event } function init() { let el=document.
getElementById('target1'); el.onpointerout = outHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointerout="outHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointerout' in that specification. Recommendation Non-stable ...
GlobalEventHandlers.onpointerover - Web APIs
targetElement.onpointerover = overHandler; var overHandler = targetElement.onpointerover; Value overHandler The pointerover event handler for element targetElement. Example This example shows two ways to use onpointerover to set an element's pointerover event handler. <html> <script> function overHandler(ev) { // Process the pointerover event } function init() { let el = document.
getElementById('target1'); el.onpointerover = overHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointerover="overHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointerover' in that specification. Recommendation Non-st...
GlobalEventHandlers.onpointerup - Web APIs
erup events. Syntax targetElement.onpointerup = upHandler; var upHandler = targetElement.onpointerup; Value upHandler The pointerup event handler for element targetElement. Example This example shows two ways to use onpointerup to set an element's pointerup event handler. <html> <script> function upHandler(ev) { // Process the pointerup event } function init() { let el = document.
getElementById('target1'); el.onpointerup = upHandler; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" onpointerup="upHandler(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Pointer Events - Level 2The definition of 'onpointerup' in that specification. Recommendation Non-stable versi...
GlobalEventHandlers.onreset - Web APIs
nt object as its sole argument. Example This example logs the current Event.timeStamp whenever you reset the form. 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.onreset = logReset; Result Specification Specification Status Comment HTML Living StandardThe definition of 'onreset' in that specification. Living Standard ...
GlobalEventHandlers.onscroll - Web APIs
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 = logScroll; function logScroll(e) { log.textContent = `Scroll position: ${e.target.scrollTop}`; } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'onscroll' in that specification. Living Standard Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'onscrol...
GlobalEventHandlers.onselect - Web APIs
. Syntax target.onselect = functionRef; Value functionRef is a function name or a function expression. The function receives a UIEvent object as its sole argument. Examples This example logs the text you select inside a <textarea> element. ...
GlobalEventHandlers.ontouchcancel - Web APIs
his attribute is not widely implemented. Syntax var cancelHandler = someElement.ontouchcancel; Return value cancelHandler The touchcancel event handler for element someElement. Example This example shows two ways to use ontouchcancel to set an element's touchcancel event handler. <html> <script> function cancelTouch(ev) { // Process the event } function init() { let el = document.
getElementById('target1'); el.ontouchcancel = cancelTouch; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" ontouchcancel="cancelTouch(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. ...
GlobalEventHandlers.ontouchend - Web APIs
s Recommendation. This attribute is not widely implemented. Syntax var endHandler = targetElement.ontouchend; Return value endHandler The touchend event handler for element targetElement. Example This example shows two ways to use ontouchend to set an element's touchend event handler. <html> <script> function endTouch(ev) { // Process the event } function init() { var el=document.
getElementById("target1"); el.ontouchend = endTouch; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" ontouchend="endTouch(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. ...
GlobalEventHandlers.ontouchmove - Web APIs
dation. This attribute is not widely implemented. Syntax var moveHandler = someElement.ontouchmove; Return value moveHandler The touchmove event handler for element someElement. Example This example shows two ways to use ontouchmove to set an element's touchmove event handler. <html> <head> <script> function moveTouch(ev) { // Process the event } function init() { var el=document.
getElementById("target1"); el.ontouchmove = moveTouch; } </script> </head> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" ontouchmove="moveTouch(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. ...
GlobalEventHandlers.ontouchstart - Web APIs
tion. This attribute is not widely implemented. Syntax var startHandler = someElement.ontouchstart; Return value startHandler The touchstart event handler for element someElement. Example This example shows two ways to use ontouchstart to set an element's touchstart event handler. <html> <script> function startTouch(ev) { // Process the event } function init() { let el = document.
getElementById('target1'); el.ontouchstart = startTouch; } </script> <body onload="init();"> <div id="target1"> Touch me ... </div> <div id="target2" ontouchstart="startTouch(event)"> Touch me ... </div> </body> </html> Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. ...
HTMLAnchorElement.referrerPolicy - Web APIs
and the path (but not the fragment, password, or username). This case is unsafe as it can leak path information that has been concealed to third-party by using TLS. Examples var elt = document.createElement("a"); var linkText = document.createTextNode("My link"); elt.appendChild(linkText); elt.href = "https://developer.mozilla.org/"; elt.referrerPolicy = "no-referrer"; var div = document.
getElementById("divAround"); div.appendChild(elt); // When clicked, the link will not send a referrer header. Specifications Specification Status Comment Referrer PolicyThe definition of 'referrerPolicy attribute' in that specification. Candidate Recommendation Added the referrerPolicy property. Browser compatibility The compatibility table on this page is generated ...
HTMLAreaElement.referrerPolicy - Web APIs
case is unsafe as it can leak path information that has been concealed to third-party by using TLS. Examples <img usemap="#mapAround" width="100" height="100" src="/img/logo@2x.png" /> <map id="myMap" name="mapAround" />> var elt = document.createElement("area"); elt.href = "/img2.png"; elt.shape = "rect"; elt.referrerPolicy = "no-referrer"; elt.coords = "0,0,100,100"; var map = document.
getElementById("myMap"); map.appendChild(elt); // When clicked, the area's link will not send a referrer header. Specifications Specification Status Comment Referrer PolicyThe definition of 'referrerpolicy attribute' in that specification. Candidate Recommendation Added the referrerPolicy property. Browser compatibility The compatibility table on this page is genera...
HTMLButtonElement.labels - Web APIs
e <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 definition ...
HTMLCanvasElement.getContext() - Web APIs
text for "webgl" and "experimental-webgl", WebGL2RenderingContext for "webgl2" or ImageBitmapRenderingContext for "bitmaprenderer". If the contextType doesn't match a possible drawing context, null is returned. Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> You can get a 2d context of the canvas with the following code: var canvas = document.
getElementById('canvas'); var ctx = canvas.getContext('2d'); console.log(ctx); // CanvasRenderingContext2D { ... } Now you have the 2D rendering context for a canvas and you can draw within it. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLCanvasElement.getContext' in that specification. Living Standard No change since the latest snapsho...
HTMLCanvasElement.height - Web APIs
a negative, the default value of 150 is used. This is one of the two properties, the other being HTMLCanvasElement.width, that controls the size of the canvas. Syntax var pxl = canvas.height; canvas.height = pxl; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> You can get the height of the canvas with the following code: var canvas = document.
getElementById('canvas'); console.log(canvas.height); // 300 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLCanvasElement.height' in that specification. Living Standard No change since the latest snapshot, HTML5 HTML 5.1The definition of 'HTMLCanvasElement.height' in that specification. Recommendation HTML5The def...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
llback. type Optional A DOMString indicating the image format. The default type is image/png. Return value None. Examples Save to disk with mozFetchAsStream (Chrome context only) This technique also converts it to ico, however it will not work in Windows XP as WinXP cannot convert from PNG to ICO. It saves to the desktop it uses FileUtils.jsm. ...
HTMLCanvasElement.toDataURL() - Web APIs
sted data URI. Exceptions SecurityError The canvas's bitmap is not origin clean; at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded. ...
HTMLCanvasElement: webglcontextlost event - Web APIs
ebGL API is fired if the user agent detects that the drawing buffer associated 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 def...
HTMLCanvasElement: webglcontextrestored event - Web APIs
the context was lost are no longer valid. You need to reinitialize the 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. Recommendati...
HTMLCanvasElement.width - Web APIs
e a negative, the default value of 300 is used. This is one of the two properties, the other being HTMLCanvasElement.height, that controls the size of the canvas. Syntax var pxl = canvas.width; canvas.width = pxl; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> You can get the width of the canvas with the following code: var canvas = document.
getElementById('canvas'); console.log(canvas.width); // 300 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLCanvasElement.width' in that specification. Living Standard No change since the latest snapshot, HTML5 HTML 5.1The definition of 'HTMLCanvasElement.width' in that specification. Recommendation HTML5The defini...
HTMLDialogElement.close() - Web APIs
option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.
getElementById('updateDetails'); 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 ...
HTMLDialogElement.open - Web APIs
option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.
getElementById('updateDetails'); 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 ...
HTMLDialogElement.returnValue - Web APIs
<option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select> </label></p> <menu> <button>Cancel</button> <button>Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.
getElementById('updateDetails'); var dialog = document.
getElementById('favDialog'); dialog.returnValue = 'favAnimal'; function openCheck(dialog) { if (dialog.open) { console.log('Dialog open'); } else { console.log('Dialog closed'); } } function handleUserInput(returnValue) { if (returnValue === 'Cancel' || returnValue == null) ...
HTMLDialogElement.show() - Web APIs
option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.
getElementById('updateDetails'); 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 ...
HTMLDialogElement.showModal() - Web APIs
option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.
getElementById('updateDetails'); 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 ...
HTMLDialogElement - Web APIs
option>Red panda</option> <option>Spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (function() { var updateButton = document.
getElementById('updateDetails'); 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 ...
accessKeyLabel - Web APIs
The HTMLElement.accessKeyLabel read-only property returns a String that represents the element's assigned access key (if any); otherwise it returns an empty string. Syntax label = element.accessKeyLabel Example JavaScript var node = document.
getElementById('btn1'); if (node.accessKeyLabel) { node.title += ' [' + node.accessKeyLabel + ']'; } else { node.title += ' [' + node.accessKey + ']'; } node.onclick = function () { var p = document.createElement('p'); p.textContent = 'Clicked!'; node.parentNode.appendChild(p); }; HTML <button accesskey="h" title="Caption" id="btn1">Hover me</button> Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLElement.accessKeyLabel' in that specification. Living Standard N...
HTMLElement: beforeinput event - Web APIs
sync Sync Composed 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: change event - Web APIs
); Result Text input element 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.click() - Web APIs
lements higher in the document tree (or event chain) and fires their click events. Syntax element.click() Example Simulate a mouse-click when moving the mouse pointer over a checkbox: HTML <form> <input type="checkbox" id="myCheck" onmouseover="myFunction()" onclick="alert('click event occured')"> </form> JavaScript // On mouse-over, execute myFunction function myFunction() { document.
getElementById("myCheck").click(); } Specification Specification Status Comment HTML Living Standard Living Standard Document Object Model (DOM) Level 2 HTML Specification Obsolete Initial definition. ...
HTMLElement.dir - Web APIs
on is a string variable representing the text writing direction of the current element. newWritingDirection is a string variable representing the text writing direction value. Possible values for dir are ltr, for left-to-right, rtl, for right-to-left, and auto for specifying that the direction of the element must be determined based on the contents of the element. Example var parg = document.
getElementById("para1"); parg.dir = "rtl"; // change the text direction on a paragraph identified as "para1" Specifications Specification Status Comment HTML Living StandardThe definition of 'dir' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe def...
HTMLElement.hidden - Web APIs
are not hidden must not link to elements 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...
HTMLElement: input event - Web APIs
ge event, which only fires when the 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 spec...
HTMLElement.isContentEditable - Web APIs
returns a Boolean that is true if the contents of the element are editable; otherwise it returns false. Syntax editable = element.isContentEditable Example HTML <p id="myText1">Uneditable Paragraph</p> <p id="myText2" contentEditable="true">Editable Paragraph</p> <p id="infoText1">Can edit the first paragraph? </p> <p id="infoText2">Can edit the second paragraph? </p> JavaScript document.
getElementById('infoText1').innerHTML += document.
getElementById('myText1').isContentEditable; document.
getElementById('infoText2').innerHTML += document.
getElementById('myText2').isContentEditable; Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLElement.contenteditable' in that specification. Living Standard No change from lat...
HTMLElement.offsetTop - Web APIs
The HTMLElement.offsetTop read-only property returns the distance of the current element relative to the top of the offsetParent node. Syntax topPos = element.offsetTop; Parameters topPos is the number of pixels from the top of the closest relatively positioned parent element. Example var d = document.
getElementById("div1"); var topPos = d.offsetTop; if (topPos > 10) { // object is offset more // than 10 pixels from its parent } Specification Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'offsetTop' in that specification. Working Draft Browser compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://gi...
HTMLFormElement.length - Web APIs
ther elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. Syntax numControls = form.length; Value numControls is the number of form controls within the <form>. This is the same as the number of the elements in the HTMLFormControlsCollection returned by the elements property. Example if (document.
getElementById('form1').length > 1) { // more than one form control here } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: length' in that specification. Living Standard ...
HTMLFormElement.name - Web APIs
<form> element as a string. If your <form> element contains an element named name then that element overrides the form.name property, so that you can't access it. Internet Explorer (IE) does not allow the name attribute of an element created using createElement() to be set or modified using the name property. Syntax var string = form.name; form.name = string; Example var form1name = document.
getElementById('form1').name; if (form1name != document.form.form1) { // Browser doesn't support this form of reference } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: name' in that specification. Living Standard ...
HTMLFormElement.reset() - Web APIs
The HTMLFormElement.reset() method restores a form element's default values. This method does the same thing as clicking the form's reset button. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method. It does not reset other attributes in the input, such as disabled. Syntax HTMLFormElement.reset() Example document.
getElementById('myform').reset(); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLFormElement: reset' in that specification. Living Standard ...
HTMLFormElement: reset event - Web APIs
EventTarget.addEventListener() to listen for form resets, and logs the current 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 def...
HTMLFormElement: submit event - Web APIs
tamp 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.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...
HTMLHyperlinkElementUtils.hash - Web APIs
rty returns a USVString containing a '#' followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string, "". Syntax string = object.hash; object.hash = string; Examples <a id="myAnchor" href="/docs/HTMLHyperlinkElementUtils.href#Examples">Examples</a> <script> var anchor = document.
getElementById("myAnchor"); console.log(anchor.hash); // Returns '#Examples' </script> Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.hash' in that specification. Living Standard Initial definition ...
HTMLHyperlinkElementUtils.hostname - Web APIs
The HTMLHyperlinkElementUtils.hostname property is a USVString containing the domain of the URL. Syntax string = object.hostname; object.hostname = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/docs/HTMLHyperlinkElementUtils.hostname"> element be in the document var anchor = document.
getElementById("myAnchor"); var result = anchor.hostname; // Returns:'developer.mozilla.org' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.hostname' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.href - Web APIs
The HTMLHyperlinkElementUtils.href property is a stringifier that returns a USVString containing the whole URL, and allows the href to be updated. Syntax string = object.href; object.href = string; Examples // Lets imagine an <a id="myAnchor" href="https://developer.mozilla.org/HTMLHyperlinkElementUtils/href"> element is in the document var anchor = document.
getElementById("myAnchor"); var result = anchor.href; // Returns: 'https://developer.mozilla.org/HTMLHyperlinkElementUtils/href' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.href' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.password - Web APIs
ord property is a USVString containing the password specified before the domain name. If it is set without first setting the username property, it silently fails. Syntax string = object.password; object.password = string; Examples // Let's <a id="myAnchor" href="https://anonymous:flabada@developer.mozilla.org/docs/HTMLHyperlinkElementUtils.username"> be in the document var anchor = document.
getElementByID("myAnchor"); var result = anchor.password; // Returns:'flabada' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.password' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.pathname - Web APIs
The HTMLHyperlinkElementUtils.pathname property is a USVString containing an initial '/' followed by the path of the URL (or the empty string if there is no path). Syntax string = object.pathname; object.pathname = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/docs/HTMLHyperlinkElementUtils.pathname"> element be in the document var anchor = document.
getElementById("myAnchor"); var result = anchor.pathname; // Returns:'/docs/HTMLHyperlinkElementUtils.pathname' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.pathname' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.port - Web APIs
The HTMLHyperlinkElementUtils.port property is a USVString containing the port number of the URL. If the URL does not contain an explicit port number, it will be set to ''. Syntax string = object.port; object.port = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org:443/docs/HTMLHyperlinkElementUtils.port"> element be in the document var anchor = document.
getElementByID("myAnchor"); var result = anchor.port; // Returns:'443' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.port' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.protocol - Web APIs
The HTMLHyperlinkElementUtils.protocol property is a USVString representing the protocol scheme of the URL, including the final ':'. Syntax string = object.protocol; object.protocol = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/HTMLHyperlinkElementUtils.protocol"> element be in the document var anchor = document.
getElementById("myAnchor"); var result = anchor.protocol; // Returns:'https:' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.protocol' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.search - Web APIs
a '?' followed by the parameters of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring. Syntax string = object.search; object.search = string; Examples // Let an <a id="myAnchor" href="https://developer.mozilla.org/docs/HTMLHyperlinkElementUtils.search?q=123"> element be in the document var anchor = document.
getElementById("myAnchor"); var queryString = anchor.search; // Returns:'?q=123' // Further parsing: let params = new URLSearchParams(queryString); let q = parseInt(params.get("q")); // is the number 123 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.search' in that specification. Living Standard Initial definition. ...
HTMLHyperlinkElementUtils.username - Web APIs
The HTMLHyperlinkElementUtils.username property is a USVString containing the username specified before the domain name. Syntax string = object.username; object.username = string; Examples // Let's <a id="myAnchor" href="https://anonymous:flabada@developer.mozilla.org/docs/HTMLHyperlinkElementUtils.username"> be in the document var anchor = document.
getElementByID("myAnchor"); var result = anchor.username; // Returns:'anonymous' Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLHyperlinkElementUtils.username' in that specification. Living Standard Initial definition. ...
HTMLImageElement.referrerPolicy - Web APIs
e, that is roughly the scheme, the host and the port. "unsafe-url" meaning that the referrer will include the origin and the path (but not the fragment, password, or username). This case is unsafe as it can leak path information that has been concealed to third-party by using TLS. Examples var img = new Image(); img.src = 'img/logo.png'; img.referrerPolicy = 'origin'; var div = document.
getElementById('divAround'); div.appendChild(img); // Fetch the image using the origin as the referrer Specifications Specification Status Comment Referrer PolicyThe definition of 'referrerPolicy attribute' in that specification. Candidate Recommendation Added the referrerPolicy property. Browser compatibility The compatibility table on this page is generated from st...
HTMLImageElement.sizes - Web APIs
shadow: 0 0.5em 0.3em #888; margin-bottom: 1.25em; } JavaScript The JavaScript code handles the two buttons that let you toggle the third width option between 40em and 50em; this is done by handling the click event, using the JavaScript string object method replace() to replace the relevant portion of the sizes string. 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 ...
HTMLImageElement.x - Web APIs
> <th>Name</th> <th>Avatar</th> </tr> <tr> <td>12345678</td> <td>Johnny Rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> JavaScript The JavaScript code that fetches the image from the table and looks up its x and y values is below. let logBox = document.querySelector("pre"); let tbl = document.
getElementById("userinfo") let log = msg => { logBox.innerHTML += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.querySelector("img"); log(`Image's global X: ${image.x}`); log(`Image's global Y: ${image.y}`); This uses the <table>'s rows property to get a list of the rows in the table, from which it looks up row 1 (which, being a zero-based index, means the second row from the top). The...
HTMLImageElement.y - Web APIs
> <th>Name</th> <th>Avatar</th> </tr> <tr> <td>12345678</td> <td>Johnny Rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> JavaScript The JavaScript code that fetches the image from the table and looks up its x and y values is below. let logBox = document.querySelector("pre"); let tbl = document.
getElementById("userinfo") let log = msg => { logBox.innerHTML += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.querySelector("img"); log(`Image's global X: ${image.x}`); log(`Image's global Y: ${image.y}`); This uses the <table>'s rows property to get a list of the rows in the table, from which it looks up row 1 (which, being a zero-based index, means the second row from the top). The...
HTMLInputElement: invalid event - Web APIs
an invalid event fires because 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 ...
HTMLInputElement.labels - Web APIs
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 HTML5The definition of 'labels' in that specification. Recommendation ...
HTMLInputElement.multiple - Web APIs
The HTMLInputElement.multiple property indicates if an input can have more than one value. Firefox currently only supports multiple for <input type="file">. ...
HTMLInputElement.select() - Web APIs
lects all the text in a <textarea> element or in an <input> element that includes a text field. Syntax element.select(); Example Click the button in this example to select all the text in the <input> element. HTML <input type="text" id="text-box" size="20" value="Hello world!"> <button onclick="selectText()">Select text</button> JavaScript function selectText() { const input = document.
getElementById('text-box'); input.focus(); input.select(); } Result Notes Calling element.select() will not necessarily focus the input, so it is often used with HTMLElement.focus(). In browsers where it is not supported, it is possible to replace it with a call to HTMLInputElement.setSelectionRange() with parameters 0 and the input's value length: <input onClick="this.select();" value="Sample Text" ...
HTMLInputElement.setRangeText() - Web APIs
e selection. This is the default. Example Click the button in this example to replace part of the text in the text box. The newly inserted text will be highlighted (selected) afterwards. HTML <input type="text" id="text-box" size="30" value="This text has NOT been updated."> <button onclick="selectText()">Update text</button> JavaScript function selectText() { const input = document.
getElementById('text-box'); input.focus(); input.setRangeText('ALREADY', 14, 17, 'select'); } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLInputElement.setSelectionRange()' in that specification. Living Standard No change HTML5The definition of 'HTMLInputElement.setSelectionRange()' in that specification. Rec...
HTMLInputElement.setSelectionRange() - Web APIs
ward" "none" if the direction is unknown or irrelevant. Default value. Example Click the button in this example to select the third, fourth, and fifth characters in the text box ("zil" in the word "Mozilla"). HTML <input type="text" id="text-box" size="20" value="Mozilla"> <button onclick="selectText()">Select text</button> JavaScript function selectText() { const input = document.
getElementById('text-box'); input.focus(); input.setSelectionRange(2, 5); } Result Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLInputElement.setSelectionRange()' in that specification. Living Standard No change HTML 5.1The definition of 'HTMLInputElement.setSelectionRange()' in that specification. Recommendation ...
HTMLInputElement.webkitEntries - Web APIs
esenting one file which 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 ...
HTMLMediaElement.audioTracks - Web APIs
getTrackById() method. Each track is represented by a AudioTrack object which provides information about the track. Examples In this example, all of the audio tracks on a given element are muted. HTML The HTML establishes the element itself. <video id="video" src="somevideo.mp4"></video> JavaScript The JavaScript code handles muting the video element's audio tracks. var video = document.
getElementById("video"); for (var i = 0; i < video.audioTracks.length; i += 1) { video.audioTracks[i].enabled = false; } Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.audioTracks' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement.audioTracks' in that specification...
HTMLMediaElement.captureStream() - Web APIs
d 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 that specification. Working Draft Initial definition. ...
HTMLMediaElement.fastSeek() - Web APIs
e HTMLMediaElement.fastSeek() method quickly seeks the media to the new time with precision tradeoff. Note: If you need to seek with precision, you should set HTMLMediaElement.currentTime instead. Syntax HTMLMediaElement.fastSeek(time); Parameters time A double. Return value None. Example This example quickly seeks to 20-second position of the video element. let myVideo = document.
getElementById("myVideoElement"); myVideo.fastSeek(20); Specifications Specification Status Comment HTML Living StandardThe definition of 'fastSeek()' in that specification. Living Standard Initial definition; living specification. ...
HTMLMediaElement.networkState - Web APIs
the network. NETWORK_LOADING 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. ...
HTMLMediaElement.readyState - Web APIs
h enough--that the media can be 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. Recommen...
HTMLMeterElement.labels - Web APIs
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 HTML5The definition of 'labels' in that specification. Recommendation ...
HTMLObjectElement.setCustomValidity - Web APIs
ror The message to use for validity errors. Return value undefined Exceptions None. Examples In this example, we pass the ID of an input element, and set different error messages depending on whether the value is missing, too low or too high. Additionally you must call the reportValidity method on the same element or nothing will happen. ...
HTMLObjectElement.typeMustMatch - Web APIs
ustmatch attribute of the <object> element. It indicates if the resource linked by it must match the MIME type given by HTMLObjectElement.type in order for this resource to be used. Syntax var mustMatch = obj.typeMustMatch; obj.typeMustMatch = mustMatch; Example HTML <object id="obj" data="move.swf" type="application/x-shockwave-flash" typemustmatch></object> JavaScript let obj = document.
getElementById('obj'); console.log(obj.typeMustMatch); Specifications Specification Status Comment HTML5The definition of 'HTMLObjectElement' in that specification. Recommendation The W3C specification is a latest of a previous version of HTML Living Standard First snapshot with this property. ...
HTMLElement.blur() - Web APIs
.blur() method removes keyboard focus from the current element. Syntax element.blur(); Examples Remove focus from a text input HTML <input type="text" id="myText" value="Sample Text"> <br><br> <button type="button" onclick="focusInput()">Click me to gain focus</button> <button type="button" onclick="blurInput()">Click me to lose focus</button> JavaScript function focusInput() { document.
getElementById('myText').focus(); } function blurInput() { document.
getElementById('myText').blur(); } Result Specification Specification Status Comment HTML Living StandardThe definition of 'blur' in that specification. Living Standard HTML 5.1The definition of 'blur' in that specification. Recommendation HTML5The definition of 'blur' in that s...
HTMLOrForeignElement.tabIndex - Web APIs
d assign tabIndex to 0, in the order they appear. Elements that are disabled do not participate in the tabbing order. Values don't need to be sequential, nor must they begin with any particular value. They may even be negative, though each browser trims very large values. Syntax element.tabIndex = index; var index = element.tabIndex; Value index is an integer Example const b1 = document.
getElementById('button1'); b1.tabIndex = 1; Specifications Specification Status Comment HTML Living StandardThe definition of 'tabindex' in that specification. Living Standard No change from Document Object Model (DOM) Level 2 HTML Specification. Document Object Model (DOM) Level 2 HTML SpecificationThe definition of 'tabindex' in that specification. Obsolete ...
HTMLOutputElement.labels - Web APIs
e <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 HTML5The definition of 'labels' in that specification. Recommendatio...
HTMLProgressElement.labels - Web APIs
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 HTML5The definition of 'labels' in that specification. Recommend...
HTMLSelectElement.autofocus - Web APIs
after the document load, has no visible effect. SyntaxEdit aBool = aSelectElement.autofocus; // Get the value of autofocus aSelectElement.autofocus = aBool; // Set the value of autofocus Example HTML <select id="mySelect" autofocus> <option>Option 1</option> <option>Option 2</option> </select> JavaScript // Check if the autofocus attribute on the <select> var hasAutofocus = document.
getElementById('mySelect').autofocus; Specifications Specification Status Comment HTML Living StandardThe definition of 'autofocus' in that specification. Living Standard HTML 5.2The definition of 'autofocus' in that specification. Recommendation ...
HTMLSelectElement.form - Web APIs
="Search..."> </form> Javascript A property available on all form elements, "type" returns the type of the calling form element. For SELECT, the two possible values are "select-one" or "select-multiple", depending on the type of selection list. The below code gives all SELECT elements in a particular form a CSS class of "selectclass": <script type="text/javascript"> var form_element = document.
getElementById('subscribe_form'); var vist = form_element.style; if (vist.display=='' || vist.display=='none') { vist.display = 'block'; } else { vist.display = 'none'; } </script> Specifications Specification Status Comment HTML Living StandardThe definition of 'form' in that specification. Living Standard HTML5The definition of 'HTMLSelectElement' in that specif...
HTMLSelectElement.labels - Web APIs
n 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 HTML5The definition of 'labels' in that specification. Recommendatio...
HTMLSelectElement.options - Web APIs
t. 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 HTML5The definition of 'options' in that specification. Recommendatio...
HTMLSelectElement.remove() - Web APIs
The HTMLSelectElement.remove() method removes the element at the specified index from the options collection for this select element. Syntax collection.remove(index); Parameters index is a long for the index of the HTMLOptionElement to remove from the collection. If the index is not found the method has no effect. ...
HTMLSelectElement - Web APIs
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> */ var select = document.
getElementById('s'); // return the index of the selected option console.log(select.selectedIndex); // 1 // return the value of the selected option console.log(select.options[select.selectedIndex].value) // Second A better way to track changes to the user's selection is to watch for the change event to occur on the <select>. This will tell you when the value changes, and you can then update anything you need...
HTMLStyleElement.media - Web APIs
= medium Parameters medium is a string describing a single medium or a comma-separated list. Example <!doctype html> <html> <head> <link id="LinkedStyle" rel="stylesheet" href="document.css" type="text/css" media="screen" /> <style id="InlineStyle" rel="stylesheet" type="text/css" media="screen, print"> p { color: blue; } </style> </head> <body> <script> alert('LinkedStyle: ' + document.
getElementById('LinkedStyle').media); // 'screen' alert('InlineStyle: ' + document.
getElementById('InlineStyle').media); // 'screen, print' </script> </body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLStyleElement' in that specification. Living Standard HTML 5.1The definition of 'HTMLStyleElement' in that specif...
HTMLTableElement.align - Web APIs
The HTMLTableElement.align property represents the alignment of the table. Syntax HTMLTableElement.align = alignment; var alignment = HTMLTableElement.align; Parameters alignment DOMString with one of the following values: left center right Example // Set the alignmnet of a table var t = document.
getElementById('TableA'); t.align = 'center'; Specification W3C DOM 2 HTML Specification HTMLTableElement .align. ...
HTMLTableElement.border - Web APIs
The HTMLTableElement.border property represents the border width of the <table> element. Syntax HTMLTableElement.border = border; var border = HTMLTableElement.border; border is a string representing the width of the border in pixels. Example // Set the width of a table border to 2 pixels var t = document.
getElementById('TableA'); t.border = '2'; Specification W3C DOM 2 HTML Specification HTMLTableElement .border. This attribute is deprecated in HTML 4.0. ...
HTMLTableElement.cellPadding - Web APIs
The HTMLTableElement.cellPadding property represents the padding around the individual cells of the table. Syntax HTMLTableElement.cellPadding = padding; var padding = HTMLTableElement.cellPadding; padding is either a number of pixels (e.g. "10") or a percentage value (e.g. "10%"). Example // Set cell padding to 10 pixels let t = document.
getElementById('TableA'); t.cellPadding = '10'; Specification W3C DOM 2 HTML Specification HTMLTableElement .cellPadding. ...
HTMLTableElement.cellSpacing - Web APIs
esenting a table's cells. Any two cells are separated by the sum of the cellSpacing of each of the two cells. Syntax HTMLTableElement.cellSpacing = spacing; var spacing = HTMLTableElement.cellSpacing; Value A DOMString which is either a number of pixels (such as "10") or a percentage value (like "10%"). Example This example sets cell spacing for a given table to 10 pixels. var t = document.
getElementById('TableA'); t.cellSpacing = "10"; Specification W3C DOM 2 HTML Specification HTMLTableElement .cellSpacing. ...
HTMLTableRowElement.insertCell() - Web APIs
new cell in the new row. (To be valid HTML, a <tr> must have at least one <td> element.) Finally, we add some text to the cell using Document.createTextNode() and Node.appendChild(). ...
HTMLTextAreaElement.labels - Web APIs
ement. 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 HTML5The definition of 'labels' in that specification. Recommend...
HTMLTimeElement.dateTime - Web APIs
Living Standard No change from HTML 5.1. HTML 5.1The definition of 'HTMLTimeElement' in that specification. Recommendation No change from HTML5. HTML5The definition of 'HTMLTimeElement...
HTMLVideoElement.getVideoPlaybackQuality() - Web APIs
lity(); Return value A VideoPlaybackQuality object providing information about the video element's current playback quality. Example This example updates an element to indicate the total number of video frames that have elapsed so far in the playback process. This value includes any dropped or corrupted frames, so it's not the same as "total number of frames played." var videoElem = document.
getElementById("my_vid"); var counterElem = document.
getElementById("counter"); var quality = videoElem.getVideoPlaybackQuality(); counterElem.innerText = quality.totalVideoFrames; Specifications Specification Status Comment Media Playback QualityThe definition of 'HTMLVideoElement.getVideoPlaybackQuality()' in that specification. Editor's Draft Initial definition. ...
HTMLVideoElement.msHorizontalMirror - Web APIs
ent.msHorizontalMirror: boolean; Value Boolean value set to true flips the video playback horizontally. Video perspective is flipped on a horizontal axis - this may be useful for playback of a webcam video, providing the user with better mirroring of their real behaviors (ie. ...
HTMLVideoElement.videoHeight - Web APIs
e element's readyState isn't HAVE_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 ...
HTMLVideoElement.videoWidth - Web APIs
e element's readyState isn't HAVE_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 ...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
quently referred to as a "local context." Using the ill-advised eval() function also creates a new execution context. Each context is, in essence, a level of scope within your code. As one of these code segments begins execution, a new context is constructed in which to run it; that context is then destroyed when the code exits. ...
Dragging and Dropping Multiple Items - Web APIs
output(" Item " + i + ":\n"); var types = dt.mozTypesAt(i); for (var t = 0; t < types.length; t++) { output(" " + types[t] + ": "); try { var data = dt.mozGetDataAt(types[t], i); output("(" + (typeof data) + ") : <" + data + " >\n"); } catch (ex) { output("<<error>>\n"); dump(ex); } } } } function output(text) { document.
getElementById("output").textContent += text; dump(text); } </script> </head> <body> <div id="output" style="min-height: 100px; white-space: pre; border: 1px solid black;" ondragenter="document.
getElementById('output').textContent = ''; event.stopPropagation(); event.preventDefault();" ondragover="event.stopPropagation(); event.preventDefault();" ondrop="event.stopPropagation(); event.prevent...
History.back() - Web APIs
1). If there is no previous 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 Compatibilit...
History.forward() - Web APIs
n the session history. It has 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 ...
Ajax navigation example - Web APIs
!bIsLoading) { return; } oReq.abort(); closeReq(); } function ajaxError () { alert("Unknown error."); } function ajaxLoad () { var vMsg, nStatus = this.status; switch (nStatus) { case 200: vMsg = JSON.parse(this.responseText); document.title = oPageInfo.title = vMsg.page; document.
getElementById(sTargetId).innerHTML = vMsg.content; if (bUpdateURL) { history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url); bUpdateURL = false; } break; default: vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "Unknown"); switch (Math.floor(nStatus / 100)) { ...
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
to the canvas as well. This method was previously named transferImageBitmap(), but was renamed in a spec change. The old name is being kept as an alias to avoid code breakage. Syntax void ImageBitmapRenderingContext.transferFromImageBitmap(bitmap) Parameters bitmap An ImageBitmap object to transfer. Examples HTML <canvas id="htmlCanvas"></canvas> JavaScript var htmlCanvas = document.
getElementById("htmlCanvas").getContext("bitmaprenderer"); // Draw a WebGL scene offscreen var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext("webgl"); // ... some drawing using the gl context ... // Transfer the current frame to the visible canvas var bitmap = offscreen.transferToImageBitmap(); htmlCanvas.transferFromImageBitmap(bitmap); Specifications Specification ...
ImageData() - Web APIs
This example instantiates an ImageData object with pixel colors defined by an array. HTML <canvas id="canvas"></canvas> JavaScript The array (arr) has a length of 40000: it consists of 10,000 pixels, each of which is defined by 4 values. The ImageData constructor specifies a width of 200 for the new object, so its height defaults to 10,000 divided by 200, which is 50. ...
ImageData.data - Web APIs
0 Filling a blank ImageData object This example creates and fills a new ImageData object with colorful pixels. HTML <canvas id="canvas"></canvas> JavaScript Since each pixel consists of four values within the data array, the for loop iterates by multiples of four. The values associated with each pixel are R (red), G (green), B (blue), and A (alpha), in that order. ...
Index - Web APIs
od of the Document interface returns an array of all Animation objects currently in effect whose target elements are descendants of the document. This array includes CSS Animations, CSS Transitions, and Web Animations. 918 Document.getBoxObjectFor() API, DOM, Method, Obsolete, Reference Returns a boxObject (x, y, width, height) for a specified element. 919 Document.
getElementById() API, DOM, Document, Elements, Method, Reference, Web,
getElementById, id The Document method
getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly. 920 Document.getElementsByClassName() A...
InputEvent.inputType - Web APIs
HTML <p id="log">Input type: </p> <div contenteditable="true" style="margin: 20px;padding: 20px;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 Spe...
IntersectionObserver.unobserve() - Web APIs
.unobserve(target); Parameters target The Element to cease observing. If the specified element isn't being observed, this method does nothing and no exception is thrown. Return value undefined. Example This snippet simply shows an observer being created, an element being observed, and then being unobserved. var observer = new IntersectionObserver(callback); observer.observe(document.
getElementById("elementToObserve")); /* ... */ observer.unobserve(document.
getElementById("elementToObserve")); Specifications Specification Status Comment Intersection ObserverThe definition of 'IntersectionObserver.unobserve()' in that specification. Working Draft Initial definition. ...
KeyboardEvent.initKeyEvent() - Web APIs
l, // viewArg, Specifies UIEvent.view. This value may be null. false, // ctrlKeyArg, false, // altKeyArg, false, // shiftKeyArg, false, // metaKeyArg, 9, // keyCodeArg, 0); // charCodeArg); document.
getElementById('blah').dispatchEvent(event); Specification This implementation of keyboard events is based on the key events spec in the early versions of DOM 2 Events, later removed from that spec. The initKeyEvent is the current Gecko equivalent of the DOM Level 3 Events (initially drafted and also deprecated in favor of KeyboardEvent() Keyboard.initKeyboardEvent() method with the following arguments : t...
KeyboardEvent.key - Web APIs
re id="console-log"></pre> </div> </div> CSS .fx { -webkit-display: flex; display: flex; margin-left: -20px; margin-right: -20px; } .fx > div { padding-left: 20px; padding-right: 20px; } .fx > div:first-child { width: 30%; } .flex { -webkit-flex: 1; flex: 1; } #test-target { display: block; width: 100%; margin-bottom: 10px; } JavaScript let textarea = document.
getElementById('test-target'), consoleLog = document.
getElementById('console-log'), btnClearConsole = document.
getElementById('btn-clear-console'); function logMessage(message) { document.
getElementById("console-log").innerHTML += message + "<br>"; } textarea.addEventListener('keydown', (e) => { if (!e.repeat) logMessage(`Key "${e.key}" pressed [event: keydown]`); else logMessage(`Key "${e.key}...
Location: hash - Web APIs
e Location interface returns a USVString containing a '#' followed by the fragment identifier of the URL. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string, "". Syntax string = object.hash; object.hash = string; Examples <a id="myAnchor" href="/docs/Location.href#Examples">Examples</a> <script> var anchor = document.
getElementById("myAnchor"); console.log(anchor.hash); // Returns '#Examples' </script> Specifications Specification Status Comment HTML Living StandardThe definition of 'hash' in that specification. Living Standard Initial definition ...
Location: hostname - Web APIs
The hostname property of the Location interface is a USVString containing the domain of the URL. Syntax string = object.hostname; object.hostname = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/docs/Location.hostname"> element be in the document var anchor = document.
getElementById("myAnchor"); var result = anchor.hostname; // Returns:'developer.mozilla.org' Specifications Specification Status Comment HTML Living StandardThe definition of 'hostname' in that specification. Living Standard Initial definition. ...
Location: href - Web APIs
fier that returns a USVString containing the whole URL, and allows the href to be updated. Setting the value of href navigates to the provided URL. If you want redirection, use Location.replace(). Syntax string = object.href; object.href = string; Examples // Lets imagine an <a id="myAnchor" href="https://developer.mozilla.org/Location/href"> element is in the document var anchor = document.
getElementById("myAnchor"); var result = anchor.href; // Returns: 'https://developer.mozilla.org/Location/href' Specifications Specification Status Comment HTML Living StandardThe definition of 'href' in that specification. Living Standard Initial definition. ...
Location: password - Web APIs
rty of the Location interface is a USVString containing the password specified before the domain name. If it is set without first setting the username property, it silently fails. Syntax string = object.password; object.password = string; Examples // Let's <a id="myAnchor" href="https://anonymous:flabada@developer.mozilla.org/docs/location.username"> be in the document var anchor = document.
getElementByID("myAnchor"); var result = anchor.password; // Returns:'flabada' ...
Location: pathname - Web APIs
The pathname property of the Location interface is a USVString containing an initial '/' followed by the path of the URL (or the empty string if there is no path). Syntax string = object.pathname; object.pathname = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/docs/Location.pathname"> element be in the document var anchor = document.
getElementById("myAnchor"); var result = anchor.pathname; // Returns:'/docs/Location.pathname' Specifications Specification Status Comment HTML Living StandardThe definition of 'pathname' in that specification. Living Standard Initial definition. ...
Location: port - Web APIs
The port property of the Location interface is a USVString containing the port number of the URL. If the URL does not contain an explicit port number, it will be set to ''. Syntax string = object.port; object.port = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org:443/docs/Location.port"> element be in the document var anchor = document.
getElementByID("myAnchor"); var result = anchor.port; // Returns:'443' Specifications Specification Status Comment HTML Living StandardThe definition of 'Location.port' in that specification. Living Standard Initial definition. ...
Location: protocol - Web APIs
The protocol property of the Location interface is a USVString representing the protocol scheme of the URL, including the final ':'. Syntax string = object.protocol; object.protocol = string; Examples // Let's an <a id="myAnchor" href="https://developer.mozilla.org/Location.protocol"> element be in the document var anchor = document.
getElementById("myAnchor"); var result = anchor.protocol; // Returns:'https:' Specifications Specification Status Comment HTML Living StandardThe definition of 'protocol' in that specification. Living Standard Initial definition. ...
Location: search - Web APIs
tring containing a '?' followed by the parameters of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring. Syntax string = object.search; object.search = string; Examples // Let an <a id="myAnchor" href="https://developer.mozilla.org/docs/Location.search?q=123"> element be in the document var anchor = document.
getElementById("myAnchor"); var queryString = anchor.search; // Returns:'?q=123' // Further parsing: let params = new URLSearchParams(queryString); let q = parseInt(params.get("q")); // is the number 123 Specifications Specification Status Comment HTML Living StandardThe definition of 'search' in that specification. Living Standard Initial definition. ...
Location: toString() - Web APIs
The toString() stringifier method of the Location interface returns a USVString containing the whole URL. It is a read-only version of Location.href. ...
Location: username - Web APIs
The username property of the Location interface is a USVString containing the username specified before the domain name. Syntax string = object.username; object.username = string; Examples // Let's <a id="myAnchor" href="https://anonymous:flabada@developer.mozilla.org/docs/Location.username"> be in the document var anchor = document.
getElementByID("myAnchor"); var result = anchor.username; // Returns:'anonymous' ...
MSCandidateWindowShow - Web APIs
d only register for this event once per element (the handler 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...
MediaDevices.getSupportedConstraints() - Web APIs
traints supported by the user agent are included in the list, each of these Boolean properties has the value true. Example This example outputs a list of the constraints supported by your browser. ...
MediaDevices.getUserMedia() - Web APIs
video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); Frame rate Lower frame-rates may be desirable in some cases, like WebRTC transmissions with bandwidth restrictions. var constraints = { video: { frameRate: { ideal: 10, max: 15 } } }; Front and back camera On mobile phones. var front = false; document.
getElementById('flip-button').onclick = function() { front = !front; }; var constraints = { video: { facingMode: (front? "user" : "environment") } }; Specifications Specification Status Comment Media Capture and StreamsThe definition of 'MediaDevices.getUserMedia()' in that specification. Candidate Recommendation Initial definition ...
msExtendedCode - Web APIs
. In the event of an error, 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. msExtendedCode is a read-only proprietary property specific to Internet Explorer and Microsoft Edge. Value Type: long; The platform specific error code. Example var video1 = object.
getElementById("video1"); video1.addEventListener('error', function () { var error = video1.error.msExtendedCode; //... }, false); video.addEventListener('canplay', function () { video1.play(); }, false); ...
MediaStream.onaddtrack - Web APIs
addtrack event which has occurred. The MediaStreamTrack representing the track which was added is specified in the event's track property. Example This example adds a listener which, when a new track is added to the stream, appends a new item to a list of tracks; the new item shows the track's kind ("audio" or "video") and label. stream.onaddtrack = function(event) { let trackList = document.
getElementById("tracks"); let label = document.createElement("li"); label.innerHTML = event.track.kind + ": " + event.track.label; trackList.appendChild(label); }; Specifications Specification Status Comment Media Capture and StreamsThe definition of 'MediaStream.onaddtrack' in that specification. Candidate Recommendation Initial specification. ...
MediaStream.onremovetrack - Web APIs
t accepts as input a MediaStreamTrackEvent object representing the removetrack event which has occurred. The MediaStreamTrack representing the track which was removed is specified in the event's track property. Example This example adds a listener which, when a track is removed from the stream, logs the track that was removed. stream.onremovetrack = function(event) { let trackList = document.
getElementById("tracks"); let label = document.createElement("li"); label.innerHTML = "Removed: " + event.track.kind + ": " + event.track.label; trackList.appendChild(label); }; Specifications Specification Status Comment Media Capture and StreamsThe definition of 'MediaStream.onremovetrack' in that specification. Candidate Recommendation Initial specification. ...
MediaStreamTrack.onended - Web APIs
= function; Value A function to serve as an EventHandler for the ended event. The event handler function receives a single parameter: the event object, which is a simple Event object. 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. track.onended = function(event) { let statusElem = document.
getElementById("status-icon"); statusElem.src = "/images/stopped-icon.png"; } Specifications Specification Status Comment Media Capture and StreamsThe definition of 'MediaStreamTrack.onended' in that specification. Candidate Recommendation Initial specification. ...
Recording a media element - Web APIs
th: 160px; padding: 0px; } .right { margin-left: 10px; float: left; width: 160px; padding: 0px; } .bottom { clear: both; padding-top: 10px; } JavaScript content Now let's have a look at the JavaScript code; this is where the majority of the action happens, after all! Setting up global variables We start by establishing some global variables we'll need. let preview = document.
getElementById("preview"); let recording = document.
getElementById("recording"); let startButton = document.
getElementById("startButton"); let stopButton = document.
getElementById("stopButton"); let downloadButton = document.
getElementById("downloadButton"); let logElement = document.
getElementById("log"); let recordingTimeMS = 5000; Most of these are references to elements we need to work with. The last, re...
MediaStream Recording API - Web APIs
based on desired criteria. In this code snippet, enumerateDevices() is used to examine the available input devices, locate those which are audio input devices, and create <option> elements that are then added to a <select> element representing an input source picker. navigator.mediaDevices.enumerateDevices() .then(function(devices) { devices.forEach(function(device) { let menu = document.
getElementById("inputdevices"); if (device.kind == "audioinput") { let item = document.createElement("option"); item.innerHTML = device.label; item.value = device.deviceId; menu.appendChild(item); } }); }); Code similar to this can be used to let the user restrict the set of devices they wish to use. For more information To learn more about using the MediaStream Recording AP...
MediaTrackSupportedConstraints.aspectRatio - Web APIs
ry (and its value is always true) if the user agent supports the aspectRatio constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().aspectRatio) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'aspectRatio' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.autoGainControl - Web APIs
perty isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example This example simply displays whether or not your browser supports the autoGainControl constraint. HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().autoGainControl) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'autoGainControl' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.channelCount - Web APIs
y (and its value is always true) if the user agent supports the channelCount constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().channelCount) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'channelCount' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.deviceId - Web APIs
onary (and its value is always true) if the user agent supports the deviceId constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().deviceId) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'deviceId' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.echoCancellation - Web APIs
nd its value is always true) if the user agent supports the echoCancellation constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().echoCancellation) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'echoCancellation' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.facingMode - Web APIs
s present in the dictionary (and its value is always true) if the user agent supports the facingMode constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML <div id="result"> </div> CSS #result { font: 14px "Arial", sans-serif; } JavaScript let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().facingMode) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'facingMode' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.frameRate - Web APIs
he dictionary if the user agent supports the frameRate constraint. If the property isn't present, the user agent doesn't allow specifying limits on the frame rate for video tracks. If this property is present, its value is always true. Example This simple example looks to see if your browser supports constraining the frame rate when requesting video tracks. ...
MediaTrackSupportedConstraints.groupId - Web APIs
ionary (and its value is always true) if the user agent supports the groupId constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().groupId) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'groupId' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.height - Web APIs
tionary (and its value is always true) if the user agent supports the height constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().height) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'height' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.latency - Web APIs
ionary (and its value is always true) if the user agent supports the latency constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().latency) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'latency' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
erty isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example This example simply displays whether or not your browser supports the noiseSuppression constraint. HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().noiseSuppression) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'noiseSuppression' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.sampleRate - Web APIs
ary (and its value is always true) if the user agent supports the sampleRate constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().sampleRate) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'sampleRate' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.sampleSize - Web APIs
ary (and its value is always true) if the user agent supports the sampleSize constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().sampleSize) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'sampleSize' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.width - Web APIs
ctionary (and its value is always true) if the user agent supports the width constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example HTML content <div id="result"> </div> CSS content #result { font: 14px "Arial", sans-serif; } JavaScript content let result = document.
getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().width) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } Result Specifications Specification Status Comment Media Capture and StreamsThe definition of 'width' in that specification. Candidate Recommendation Initial specification. ...
MouseEvent.movementX - Web APIs
vent.movementX; 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.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
reenY - previousEvent.screenY. 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.region - Web APIs
returns the id of the canvas hit region affected by the event. If no hit region is affected, null is returned. Syntax var hitRegion = instanceOfMouseEvent.region Return value A DOMString representing the id of the hit region. ...
msPlayToSource - Web APIs
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. }); ...
MutationObserver - Web APIs
rds() Removes all pending notifications from the MutationObserver's notification queue and returns them in a new Array of MutationRecord objects. Mutation Observer & customize resize event listener & demo https://codepen.io/webgeeker/full/YjrZgg/ Example The following example was adapted from this blog post. ...
Navigator.productSub - Web APIs
The Navigator.productSub read-only property returns the build number of the current browser. Syntax prodSub = window.navigator.productSub prodSub is a string. Example <script> function prodsub() { var dt = document.
getElementById("d").childNodes[0]; dt.data = window.navigator.productSub; } </script> <button onclick="prodsub();">productSub</button> // returns: 20010725 Notes On IE, this property returns undefined. On Apple Safari and Google Chrome this property always returns 20030107. Specifications Specification Status Comment HTML Living StandardThe definition of 'NavigatorID: productSub' in that specification. Living Standard Initial definition ...
Node.cloneNode() - Web APIs
false. You should always provide an explicit value for backward and forward compatibility. With Gecko 28.0 (Firefox 28 / Thunderbird 28 / SeaMonkey 2.25 / Firefox OS 1.3)), the console warned developers not 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 ...
Node.hasChildNodes() - Web APIs
The Node.hasChildNodes() method returns a Boolean value indicating whether the given Node has child nodes or not. Syntax bool = node.hasChildNodes(); Return value A Boolean that is true if the node has child nodes, and false otherwise. ...
Node.isSupported() - Web APIs
2 Conformance Section. version Is a DOMString containing the version number of the feature to test. In DOM Level 2, version 1, this is the string 2.0. If the version is not specified, supporting any version of the feature will cause the method to return true. Example <div id="doc"> </div> <script> // Get an element and check to see if its supports the DOM2 HTML Module. var main = document.
getElementById('doc'); var output = main.isSupported('HTML', '2.0'); </script> Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.isSupported()' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification. Document Object Model (DOM) Level 2 Core Specifi...
Node.lastChild - Web APIs
The Node.lastChild read-only property returns the last child of the node. If its parent is an element, then the child is generally an element node, a text node, or a comment node. It returns null if there are no child elements. Syntax var childNode = node.lastChild; Example var tr = document.
getElementById("row1"); var corner_td = tr.lastChild; Specifications Specification Status Comment DOMThe definition of 'Node.lastChild' in that specification. Living Standard No change Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.lastChild' in that specification. Obsolete No change Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'Node.lastChild' in that specification. Obsolete No change ...
Node.nextSibling - Web APIs
han the actual element the author intended to get. See Whitespace in the DOM and W3C DOM 3 FAQ: Why are some Text nodes empty? for more information. Element.nextElementSibling may be used to obtain the next element skipping any whitespace nodes, other between-element text, or comments. Example <div id="div-1">Here is div-1</div> <div id="div-2">Here is div-2</div> <script> var el = document.
getElementById('div-1').nextSibling, i = 1; console.group('Siblings of div-1:'); while (el) { console.log(i, '. ', el.nodeName); el = el.nextSibling; i++; } console.groupEnd(); </script> /************************************************** The console displays the following: Siblings of div-1 1. #text 2. DIV 3. #text 4. SCRIPT **************************************...
Node.previousSibling - Web APIs
The Node.previousSibling read-only property returns the node immediately preceding the specified one in its parent's childNodes list, or null if the specified node is the first in that list. Syntax previousNode = node.previousSibling; Example <img id="b0"> <img id="b1"> <img id="b2"> console.log(document.
getElementById("b1").previousSibling); // <img id="b0"> console.log(document.
getElementById("b2").previousSibling.id); // "b1" Notes Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a whitespace text node rather than the actual element the author intended to get. See Whitespace in the DOM and W3C DOM 3 FAQ: Why are some Text nodes e...
Node.replaceChild() - Web APIs
ibutes, or any content var sp1 = document.createElement("span"); // Give it an id attribute called 'newSpan' sp1.id = "newSpan"; // Create some content for the new element. var sp1_content = document.createTextNode("new replacement span element."); // Apply that content to the new element sp1.appendChild(sp1_content); // Build a reference to the existing node to be replaced var sp2 = document.
getElementById("childSpan"); var parentDiv = sp2.parentNode; // Replace existing node sp2 with the new span element sp1 parentDiv.replaceChild(sp1, sp2); // Result: // <div> // <span id="newSpan">new replacement span element.</span> // </div> Specifications Specification Status Comment DOMThe definition of 'Node: replaceChild' in that specification. Living Standard ...
Node - Web APIs
tional callback function that receives a Node as its only argument. If omitted, eachNode returns an Array of every node contained within rootNode (including the root itself). Sample usage The following example prints the textContent properties of each <span> tag in a <div> element named "box": <div id="box"> <span>Foo</span> <span>Bar</span> <span>Baz</span> </div> const box = document.
getElementById("box") eachNode(box, function(node) { if (null != node.textContent) { console.log(node.textContent) } }) The above will result in the following strings printing to the user's console: "\n\t", "Foo", "\n\t", "Bar", "\n\t", "Baz" Note: Whitespace forms part of a Text node, meaning indentation and newlines form separate Text between the Element nodes. Realistic usage The following dem...
NodeFilter.acceptNode() - Web APIs
who is expected to write an object implementing the NodeFilter interface, tailoring the acceptNode() method to its needs, and using it with some TreeWalker or NodeIterator objects. Syntax result = nodeFilter.acceptNode(node) Parameters node Is a Node being the object to check against the filter. ...
NodeFilter - Web APIs
s with FILTER_SKIP. FILTER_SKIP Value to be returned by NodeFilter.acceptNode() for nodes to be skipped by the NodeIterator or TreeWalker object. The children of skipped nodes are still considered. This is treated as "skip this node but not its children". ...
NodeList - Web APIs
be circumvented by using Array.prototype.forEach() -- see this document's Example. Live vs. Static NodeLists Although they are both considered NodeLists, there are 2 varieties of NodeList: live and static. Live NodeLists In some cases, the NodeList is live, which means that changes in the DOM automatically update the collection. For example, Node.childNodes is live: const parent = document.
getElementById('parent'); let child_nodes = parent.childNodes; console.log(child_nodes.length); // let's assume "2" parent.appendChild(document.createElement('div')); console.log(child_nodes.length); // outputs "3" Static NodeLists In other cases, the NodeList is static, where any changes in the DOM does not affect the content of the collection. The ubiquitous document.querySelectorAll() method returns a sta...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
to the specified one in its parent's children list, or null if the specified element is the first one in the list. Syntax prevNode = elementNodeReference.previousElementSibling; Example <div id="div-01">Here is div-01</div> <div id="div-02">Here is div-02</div> <li>This is a list item</li> <li>This is another list item</li> <div id="div-03">Here is div-03</div> <script> let el = document.
getElementById('div-03').previousElementSibling; document.write('<p>Siblings of div-03</p><ol>'); while (el) { document.write('<li>' + el.nodeName + '</li>'); el = el.previousElementSibling; } document.write('</ol>'); </script> This example outputs the following into the page when it loads: Siblings of div-03 1. LI 2. LI 3. DIV 4. DIV Polyfills Polyfill for Internet Explorer 8...
Page Visibility API - Web APIs
") { // Opera 12.10 and Firefox 18 and later support hidden = "hidden"; visibilityChange = "visibilitychange"; } else if (typeof document.msHidden !== "undefined") { hidden = "msHidden"; visibilityChange = "msvisibilitychange"; } else if (typeof document.webkitHidden !== "undefined") { hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; } 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) { co...
ParentNode.childElementCount - Web APIs
ate pure interfaces, ParentNode and ChildNode. In this case, childElementCount moved to ParentNode. This is a fairly technical change that shouldn't affect compatibility. Syntax var count = node.childElementCount; count The return value, which is an unsigned long (simply an integer) type. node An object representing a Document, DocumentFragment, or Element. Example var foo = document.
getElementById('foo'); if (foo.childElementCount > 0) { // Do something } Polyfill for IE8 & IE9 & Safari This property is completely unsupported prior to IE9. In IE9 and Safari, it is unsupported in the Document and DocumentFragment objects. ;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.childElementCount == null) { Object.defineProperty(cons...
ParentNode.children - Web APIs
e.children; Value An HTMLCollection which is a live, ordered collection of the DOM elements which are children of node. You can access the individual child nodes in the collection by using either the item() method on the collection, or by using JavaScript array-style notation. If the node has no element children, then children is an empty list with a length of 0. Example const foo = document.
getElementById('foo'); for (let i = 0; i < foo.children.length; i++) { console.log(foo.children[i].tagName); } Polyfill // Overwrites native 'children' prototype. // Adds Document & DocumentFragment support for IE9 & Safari. // Returns array instead of HTMLCollection. ;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.children == null) { Object.defineP...
ParentNode.firstElementChild - Web APIs
that are children, they have been moved into two separate pure interfaces, ParentNode and ChildNode. In this case, firstElementChild moved to ParentNode. This is a fairly technical change that shouldn't affect compatibility. Syntax var element = node.firstElementChild; Example <ul id="foo"> <li>First (1)</li> <li>Second (2)</li> <li>Third (3)</li> </ul> <script> var foo = document.
getElementById('foo'); // yields: First (1) console.log(foo.firstElementChild.textContent); </script> Polyfill for IE8, IE9 and Safari // Overwrites native 'firstElementChild' prototype. // Adds Document & DocumentFragment support for IE9 & Safari. ;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.firstElementChild == null) { Object.defin...
ParentNode.lastElementChild - Web APIs
that are children, they have been moved into two separate pure interfaces, ParentNode and ChildNode. In this case, lastElementChild moved to ParentNode. This is a fairly technical change that shouldn't affect compatibility. Syntax const element = node.lastElementChild Example <ul id="foo"> <li>First (1)</li> <li>Second (2)</li> <li>Third (3)</li> </ul> <script> const foo = document.
getElementById('foo'); console.log(foo.lastElementChild.textContent); // logs: Third (3) </script> Polyfill The code below adds support of lastElementChild() to Document and DocumentFragment in Internet Explorer and Safari. // Overwrites native 'lastElementChild' prototype. // Returns array instead of HTMLCollection. ;(function(constructor) { if(constructor && constructor.prototype && constructor.
Path2D.addPath() - Web APIs
separate Path2D objects, each of which contains a rectangle made using the rect() method. We then create a matrix using document.createElementNS() and createSVGMatrix(). We then add the second path to the first using addPath(), also applying the matrix to move the second path to the right. Finally, we draw the first path (which now contains both rectangles) using fill(). ...
PaymentRequest.show() - Web APIs
ck if the the user supports the `methods` if (!await request.canMakePayment()) { return; // no, so use a web form instead. } // Let's update the total as the sheet is shown const updatedDetails = { total: { label: "Total", amount: { value: "20", currency: "AUD" }, }, }; const response = await request.show(updatedDetails); // Check response, etc... } document.
getElementById("buyButton").onclick = requestPayment; Specifications Specification Status Comment Payment Request APIThe definition of 'show(optional detailsPromise)' in that specification. Candidate Recommendation Initial definition. ...
PluginArray - Web APIs
eloading documents. Examples The following example function returns the version of the Shockwave Flash plugin. ...
Pointer Lock API - Web APIs
gone off the edges of the canvas. If so, it makes the ball wrap around to the opposite edge. It also includes a check whether a requestAnimationFrame() call has previously been made, and if so, calls it again as required, and calls the canvasDraw() function that updates the canvas scene. A tracker is also set up to write out the X and Y values to the screen, for reference. ...
Multi-touch interaction - Web APIs
Array(); Register event handlers Event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup. The handler for pointerup is used for the pointercancel, pointerout and pointerleave events, since these four events have the same semantics in this application. function set_handlers(name) { // Install event handlers for the given element var el=document.
getElementById(name); el.onpointerdown = pointerdown_handler; el.onpointermove = pointermove_handler; // Use same handler for pointer{up,cancel,out,leave} events since // the semantics for these events - in this app - are the same. el.onpointerup = pointerup_handler; el.onpointercancel = pointerup_handler; el.onpointerout = pointerup_handler; el.onpointerleave = pointerup_handler; } function init() { ...
Pinch zoom gestures - Web APIs
); var prevDiff = -1; Register event handlers Event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup. The handler for pointerup is used for the pointercancel, pointerout and pointerleave events since these four events have the same semantics in this application. function init() { // Install event handlers for the pointer target var el=document.
getElementById("target"); el.onpointerdown = pointerdown_handler; el.onpointermove = pointermove_handler; // Use same handler for pointer{up,cancel,out,leave} events since // the semantics for these events - in this app - are the same. el.onpointerup = pointerup_handler; el.onpointercancel = pointerup_handler; el.onpointerout = pointerup_handler; el.onpointerleave = pointerup_handler; } Pointer down ...
Using Pointer Events - Web APIs
Touches array to find the touch matching the given identifier, then returns that touch's index into the array. function ongoingTouchIndexById(idToFind) { for (var i = 0; i < ongoingTouches.length; i++) { var id = ongoingTouches[i].identifier; if (id == idToFind) { return i; } } return -1; // not found } Showing what's going on function log(msg) { var p = document.
getElementById('log'); p.innerHTML = msg + "\n" + p.innerHTML; } Specifications Specification Status Comment Pointer Events - Level 2The definition of 'PointerEvent' in that specification. Recommendation Non-stable version. Pointer EventsThe definition of 'PointerEvent' in that specification. Obsolete Initial definition. ...
ProgressEvent - Web APIs
itself, not headers and other overhead. Methods Also inherits methods from its parent Event. ProgressEvent.initProgressEvent() Initializes a ProgressEvent created using the deprecated Document.createEvent("ProgressEvent") method. Examples The following example adds a ProgressEvent to a new XMLHTTPRequest and uses it to display the status of the request. ...
RTCDTMFToneChangeEvent.tone - Web APIs
r.toneBuffer is empty). Syntax var tone = dtmfToneChangeEvent.tone; Example 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>". dtmfSender.ontonechange = function( ev ) { let tone = ev.tone; if (tone === "") { tone = "<none>" } document.
getElementById("playingTone").innerText = tone; }; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDTMFToneChangeEvent.tone' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannel.bufferedAmount - Web APIs
ntly queued to be sent over the data channel but have not yet been sent. Example The snippet below includes a function which changes the contents of a block with the ID "bufferSize" to a string indicating the number of bytes currently buffered on an RTCDataChannel. var dc = peerConnection.createDataChannel("File Transfer"); /* ... */ function showBufferedAmount(channel) { let el = document.
getElementbyId("bufferSize"); el.innerHTML = channel.bufferedAmount + " bytes"; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.bufferedAmount' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannel.label - Web APIs
Web site or app when the data channel was created, as specified when RTCPeerConnection.createDataChannel() was called to create the channel. Example This sample creates a data channel on an RTCPeerConnection, then, some time later, sets the content of a UI element to display the channel's name. var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("my channel"); /* ... */ document.
getElementById("channel-name").innerHTML = "<span class='channelName'>" + dc.label + "</span>"; Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.label' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannel.onclose - Web APIs
hannel is created, then handlers for the open and close events are set up to enable and disable user interface objects based on the state of the channel. This way, the message entry field and the send button are only enabled for use when the connection is actually open. let pc = new RTCPeerConnection(); let dc = pc.createDataChannel("MessageChannel")}}; dc.onopen = function(event) { document.
getElementById("messageBox").disabled = false; document.
getElementById("sendButton").disabled = false; }; dc.onclose = function(event) { document.
getElementById("messageBox").disabled = true; document.
getElementById("sendButton").disabled = true; } /* Now negotiate the connection, etc... */ Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Betw...
RTCDataChannel.onopen - Web APIs
self, of type Event. Example This example adds a new data channel to an existing RTCPeerConnection, myPeerConnection. It then establishes an open event handler which updates some user interface elements to prepare them for being used to send messages over the data channel. let dc = myPeerConnection.createDataChannel("Message Channel"); dc.onopen = function(event) { let messageBox = document.
getElementById("messageBox"); let sendButton = document.
getElementById("sendButton"); messageBox.disabled = false; messageBox.focus(); sendButton.disabled = false; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.onopen' in that specification. Candidate Recommendation Initial specific...
RTCPeerConnection.onaddstream - Web APIs
wait for a particular stream to be accepted or rejected using SDP negotiation. Example This code, based on an older version of our Signaling and video calling sample, responds to addstream events by setting the video source for a <video> element to the stream specified in the event, and then enabling a "hang up" button in the app's user interface. pc.onaddstream = function(event) { document.
getElementById("received_video").srcObject = event.stream; document.
getElementById("hangup-button").disabled = false; }; You can also use addEventListener() to add a handler for addstream events to an RTCPeerConnection. ...
RTCPeerConnection.onicegatheringstatechange - Web APIs
tion. The status is simply presented as text in a <div> element: <div id="iceStatus"></div> The actual event handler looks like this: pc.onicegatheringstatechange = function() { let label = "Unknown"; switch(pc.iceGatheringState) { case "new": case "complete": label = "Idle"; break; case "gathering": label = "Determining route"; break; } document.
getElementById("iceStatus").innerHTML = label; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCPeerConnection.onicegatheringstatechange' in that specification. Candidate Recommendation Initial specification. ...
RTCPeerConnection.ontrack - Web APIs
representing the new track, the RTCRtpReceiver and RTCRtpTransceiver, and a list of MediaStream objects which indicates which stream or streams the track is part of.. Example This example, taken from the code for the article Signaling and video calling, connects the incoming track to the <video> element which will be used to display the incoming video. pc.ontrack = function(event) { document.
getElementById("received_video").srcObject = event.streams[0]; document.
getElementById("hangup-button").disabled = false; }; The first line of our ontrack event handler takes the first stream in the incoming track and sets the srcobject attribute to that. This connects that stream of video to the element so that it begins to be presented to the user. The second line of code simply enables a "hang up" button...
RTCPeerConnection.removeTrack() - Web APIs
idStateError The connection is 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. ...
RTCRtpReceiver.getStats() - Web APIs
atsReport object containing the collected statistics. The returned statistics include those from all streams which are coming in through the RTCRtpReceiver, as well as any of their dependencies. Example This simple example obtains the statistics for an RTCRtpReceiver and updates an element's innerText to display the number of packets lost. receiver.getStats().then(function(stats) { document.
getElementById("lostpackets").innerText = stats.packetsLost; }); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpReceiver.getStats()' in that specification. Candidate Recommendation Initial specification. ...
RTCRtpSender.getStats() - Web APIs
rned RTCStatsReport accumulates the statistics for all of the streams being sent using the RTCRtpSender, as well as the statistics for any dependencies those streams have. Example This simple example obtains the statistics for an RTCRtpSender and updates an element's innerText to display the current round trip time for requests on the sender. sender.getStats().then(function(stats) { document.
getElementById("currentRTT").innerText = stats.roundTripTime; }); Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpSender.getStats()' in that specification. Candidate Recommendation Initial specification. ...
RTCTrackEvent - Web APIs
k() 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. ...
Range.toString() - Web APIs
ough an alert dialog is ineffective. Syntax text = range.toString(); Example HTML <p>This example logs <b>everything</b> between the bold <b>words</b>. Look at the output below.</p> <p id="log"></p> JavaScript const range = document.createRange(); range.setStartBefore(document.getElementsByTagName('b').item(0), 0); range.setEndAfter(document.getElementsByTagName('b').item(1), 0); document.
getElementById('log').textContent = range.toString(); Result Specifications Specification Status Comment DOMThe definition of 'Range.toString()' in that specification. Living Standard No change. Document Object Model (DOM) Level 2 Traversal and Range SpecificationThe definition of 'Range.toString()' in that specification. Obsolete Initial specification. ...
cx - Web APIs
e's center. If unspecified, the effect is as if the value is set to 0. Syntax var xCoordinate = element.cx; Value An SVGAnimatedLength representing the x-coordinate of the circle's center. Example SVG <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="200" height="200"> <circle cx="50" cy="50" r="50" fill="gold" id="circle"/> </svg> JavaScript const circle = document.
getElementById('circle'); console.log(circle.cx); Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGCircleElement.cx' in that specification. Candidate Recommendation No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'SVGCircleElement.cx' in that specification. Recommendation Initial def...
cy - Web APIs
e's center. If unspecified, the effect is as if the value is set to 0. Syntax var yCoordinate = element.cy; Value An SVGAnimatedLength representing the y-coordinate of the circle's center. Example SVG <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="200" height="200"> <circle cy="50" cy="50" r="50" fill="gold" id="circle"/> </svg> JavaScript const circle = document.
getElementById('circle'); console.log(circle.cy); Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGCircleElement.cy' in that specification. Candidate Recommendation No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'SVGCircleElement.cy' in that specification. Recommendation Initial def...
r - Web APIs
defines the radius of the circle. If unspecified, the effect is as if the value is set to 0. Syntax var radius = element.r; Value An SVGAnimatedLength representing the radius of the circle. Example SVG <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="200" height="200"> <circle r="50" r="50" r="50" fill="gold" id="circle"/> </svg> JavaScript const circle = document.
getElementById('circle'); console.log(circle.r); Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGCircleElement.r' in that specification. Candidate Recommendation No change Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'SVGCircleElement.r' in that specification. Recommendation Initial defini...
SVGCircleElement - Web APIs
tent <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 250" width="250" height="250"> <circle cx="100" cy="100" r="50" fill="gold" id="circle" onclick="clickCircle();"/> </svg> JavaScript content This function clickCircle() is called when the circle is clicked. It randomly increases or decreases the radius of the circle element. ...
SVGEllipseElement - Web APIs
element. Methods This interface doesn't implement any specific methods, but inherits methods from its parent interface, SVGGeometryElement. Example SVG content <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <ellipse cx="100" cy="100" rx="100" ry="60" id="ellipse" onclick="outputSize();"/> </svg> JavaScript content function outputSize() { var ellipse = document.
getElementById("ellipse"); // Outputs "horizontal radius: 100 vertical radius: 60" console.log( 'horizontal radius: ' + ellipse.rx.baseVal.valueAsString, 'vertical radius: ' + ellipse.ry.baseVal.valueAsString ) } Result Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGEllipseElement' in that specification. Candid...
SVGGeometryElement.isPointInFill() - Web APIs
whether the given point is within the fill or not. Example SVG <svg viewBox="0 0 100 100" width="150" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> </svg> JavaScript var circle = document.
getElementById('circle'); // Point not in circle console.log('Point at 10,10:', circle.isPointInFill(new DOMPoint(10, 10))); // Point in circle console.log('Point at 40,30:', circle.isPointInFill(new DOMPoint(40, 30))); Result Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGGeometryElement.isPointInFill()' in that specification. ...
SVGGeometryElement.isPointInStroke() - Web APIs
Example SVG <svg viewBox="0 0 100 100" width="150" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> <circle cx="83" cy="17" r="5" fill="seagreen"/> </svg> JavaScript var circle = document.
getElementById('circle'); // Point not in circle console.log('Point at 10,10:', circle.isPointInStroke(new DOMPoint(10, 10))); // Point in circle but not stroke console.log('Point at 40,30:', circle.isPointInStroke(new DOMPoint(40, 30))); // Point in circle stroke console.log('Point at 83,17:', circle.isPointInStroke(new DOMPoint(83, 17))); Result Specifications Specification Status Comme...
SVGLength - Web APIs
= 5 SVG_LENGTHTYPE_CM = 6 SVG_LENGTHTYPE_MM = 7 SVG_LENGTHTYPE_IN = 8 SVG_LENGTHTYPE_PT = 9 SVG_LENGTHTYPE_PC = 10 Normative document SVG 1.1 (2nd Edition) Example <svg height="200" onload="start();" version="1.1" width="200" xmlns="http://www.w3.org/2000/svg"> <script type="text/javascript"><![CDATA[ function start() { var rect = document.
getElementById("myRect"); var val = rect.x.baseVal; // read x in pixel and cm units console.log("value: " + val.value + ", valueInSpecifiedUnits: " + val.unitType + ": " + val.valueInSpecifiedUnits + ", valueAsString: " + val.valueAsString); // set x = 20pt and read it out in pixel and pt units val.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PT, 20); console.log("value...
SVGRectElement - Web APIs
Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGRectElement' in that specification. Candidate R...
SVGSVGElement - Web APIs
e object is initialized to an identity matrix transform (SVG_TRANSFORM_MATRIX). SVGSVGElement.createSVGTransformFromMatrix() Creates an SVGTransform object outside of any document trees. The object is initialized to the given matrix transform (i.e., SVG_TRANSFORM_MATRIX). The values from the parameter matrix are copied, the matrix parameter is not adopted as SVGTransform::matrix. SVGSVGElement.
getElementById() Searches this SVG document fragment (i.e., the search is restricted to a subset of the document tree) for an Element whose id is given by elementId. If an Element is found, that Element is returned. If no such element exists, returns null. Behavior is not defined if more than one element has this id. Specifications Specification Status Comment Scalable Vector Gra...
SVGViewElement - Web APIs
nipulate them. Properties This interface also inherits properties from its parent interface, SVGElement. SVGViewElement.viewTarget An SVGStringList corresponding to the viewTarget attribute of the given <view> element. A list of DOMString values which contain the names listed in the viewTarget attribute. Each of the DOMString values can be associated with the corresponding element using the
getElementById() method call. Methods This interface doesn't implement any specific methods, but inherits methods from its parent interface, SVGElement. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGViewElement' in that specification. Candidate Recommendation Removed a mixin SVGExternalResourcesRequired Scalable Vect...
Selection.setBaseAndExtent() - Web APIs
mber" value="0"> </p> <p> <label for="fOffset">Focus offset</label> <input id="fOffset" name="fOffset" type="number" value="0"> </p> <p><button>Capture selection</button></p> </div> <p><strong>Output</strong>: <span class="output"></span></p> The JavaScript looks like so: var one = document.querySelector('.one'); var two = document.querySelector('.two'); var aOffset = document.
getElementById('aOffset'); var fOffset = document.
getElementById('fOffset'); var button = document.querySelector('button'); var output = document.querySelector('.output'); var selection; button.onclick = function() { try { selection = document.getSelection(); selection.setBaseAndExtent(one, aOffset.value, two, fOffset.value); var text = selection.toString(); output.textContent = text; } ...
SpeechSynthesis.getVoices() - Web APIs
es = speechSynthesis.getVoices(); for(var i = 0; i < voices.length; i++) { var option = document.createElement('option'); option.textContent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textContent += ' -- DEFAULT'; } option.setAttribute('data-lang', voices[i].lang); option.setAttribute('data-name', voices[i].name); document.
getElementById("voiceSelect").appendChild(option); } } populateVoiceList(); if (typeof speechSynthesis !== 'undefined' && speechSynthesis.onvoiceschanged !== undefined) { speechSynthesis.onvoiceschanged = populateVoiceList; } HTML <select id="voiceSelect"></select> Specifications Specification Status Comment Web Speech APIThe definition of 'getVoices()' in that specification.
Storage.getItem() - Web APIs
ng containing the value of the key. If the key does not exist, null is returned. Example The following function retrieves three data items from local storage, then uses them to set custom styles on a page. function setStyles() { var currentColor = localStorage.getItem('bgcolor'); var currentFont = localStorage.getItem('font'); var currentImage = localStorage.getItem('image'); document.
getElementById('bgcolor').value = currentColor; document.
getElementById('font').value = currentFont; document.
getElementById('image').value = currentImage; htmlElem.style.backgroundColor = '#' + currentColor; pElem.style.fontFamily = currentFont; imgElem.setAttribute('src', currentImage); } Note: To see this used within a real world example, see our Web Storage Demo. Specifications Spec...
StorageEstimate.quota - Web APIs
of storage space available for use by the application. Example In this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user. HTML content <label> You're currently using about <output id="percent"> </output>% of your available storage. </label> JavaScript content navigator.storage.estimate().then(function(estimate) { document.
getElementById("percent").value = (estimate.usage / estimate.quota * 100).toFixed(2); }); Result Specifications Specification Status Comment StorageThe definition of 'quota' in that specification. Living Standard Initial definition ...
StorageEstimate.usage - Web APIs
of storage space available for use by the application. Example In this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user. HTML content <label> You're currently using about <output id="percent"> </output>% of your available storage. </label> JavaScript content navigator.storage.estimate().then(function(estimate) { document.
getElementById("percent").value = (estimate.usage / estimate.quota * 100).toFixed(2); }); Result Specifications Specification Status Comment StorageThe definition of 'usage' in that specification. Living Standard Initial definition ...
StorageManager.estimate() - Web APIs
adding to homescreen, or accepting push notifications Example In this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user. HTML content <label> You're currently using about <output id="percent"> </output>% of your available storage. </label> JavaScript content navigator.storage.estimate().then(function(estimate) { document.
getElementById("percent").value = (estimate.usage / estimate.quota * 100).toFixed(2); }); Result Specifications Specification Status Comment StorageThe definition of 'estimate()' in that specification. Living Standard Initial definition. ...
TextDecoder.prototype.decode() - Web APIs
s, and false for the final chunk or if the data is not chunked. It defaults to false. Example This example encodes and decodes the euro symbol, EUR. HTML <p>Encoded value: <span id="encoded-value"></span></p> <p>Decoded value: <span id="decoded-value"></span></p> JavaScript const encoder = new TextEncoder(); const array = encoder.encode('EUR'); // Uint8Array(3) [226, 130, 172] document.
getElementById('encoded-value').textContent = array; const decoder = new TextDecoder(); const str = decoder.decode(array); // String "EUR" document.
getElementById('decoded-value').textContent = str; Result Specifications Specification Status Comment EncodingThe definition of 'TextDecoder.decode()' in that specification. Living Standard Initial definition. ...
TextMetrics.width - Web APIs
The read-only width property of the TextMetrics interface contains the text's advance width (the width of that inline box) in CSS pixels. Examples Given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a TextMetrics object using the following code: const canvas = document.
getElementById('canvas'); const ctx = canvas.getContext('2d'); let text = ctx.measureText('foo'); // TextMetrics object text.width; // 16; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.width' in that specification. ...
TextRange - Web APIs
seen by the user). TextRange.setEndPoint() Sets the end point of the current range based on the bounds of other TextRange. Example The following example is valid under IE9. The example gets the TextRange through document.selection, and sets the specified element to be selected. IE9 supports the standard alternative Range. var range = document.selection.createRange(); var element = document.
getElementById("test"); range.moveToElementText(element); range.select(); // Selected "SomeTextToBeSelected" <!DOCTYPE html> <html> <head> <title>TextRange Example</title> </head> <body> <p id="test">SomeTextToBeSelected</p> </body> </html> Notes Use TextRange to Operate the Selection Valid only under IE9. The selection interface should be used first, if the browser allows it. document.selection prop...
TimeRanges.end() - Web APIs
Returns the time offset at which a specified time range ends. Syntax endTime = TimeRanges.end(index) Parameters index is the range number to return the ending time for. Exceptions INDEX_SIZE_ERR A DOMException thrown if the specified index doesn't correspond to an existing range. Example Given a video element with the ID "myVideo": var v = document.
getElementById("myVideo"); var buf = v.buffered; var numRanges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // The one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } This example looks at the time ranges and looks to see if the entire video has been loaded. Specifications Specification Status ...
TimeRanges.length - Web APIs
The TimeRanges.length read-only property returns the number of ranges in the object. Syntax length = TimeRanges.length; Example Given a video element with the ID "myVideo": var v = document.
GetElementById("myVideo"); var buf = v.buffered; var numRanges = buf.length; if (buf.length == 1) { // Only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // The one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } This example looks at the time ranges and looks to see if the entire video has been loaded. Specifications Specification Status Comment HTML Living StandardThe definition of 'TimeRanges.length()' in that specification. Living Standard Initial definition ...
TimeRanges.start() - Web APIs
Returns the time offset at which a specified time range begins. Syntax startTime = TimeRanges.start(index) Parameters index is the range number to return the starting time for. Exceptions INDEX_SIZE_ERR A DOMException thrown if the specified index doesn't correspond to an existing range. Example Given a video element with the ID "myVideo": var v = document.
getElementById("myVideo"); var buf = v.buffered; var numRanges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // The one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } This example looks at the time ranges and looks to see if the entire video has been loaded. Specifications Specification S...
Touch.clientX - Web APIs
ouch on an element with an id of source, moves within 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 th...
Touch.clientY - Web APIs
ouch on an element with an id of source, moves within 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 th...
Touch.pageX - Web APIs
pet, we assume the user initiates 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.changed...
Touch.pageY - Web APIs
pet, we assume the user initiates 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.changed...
Touch.radiusX - Web APIs
ockwise about its center. The 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.trans...
Touch.screenX - Web APIs
to the screen in CSS pixels. In 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); ...
Touch.target - Web APIs
when contact is first placed on 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...
TouchList.item() - Web APIs
ex of the Touch object to retrieve. 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
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. ...
Multi-touch interaction - Web APIs
for processing outside of the event where they were fired. // Log events flag var logEvents = false; // Touch Point cache var tpCache = new Array(); Register event handlers Event handlers are registered for all four touch event types. The touchend and touchcancel event types use the same handler. ...
validityState.badInput - Web APIs
nly badInput property of a ValidityState object indicates if the user has provided input that the browser is unable to convert. For example, if you have a number input element whose content is a string. Note: While this is unsupported in Internet Explorer, any non-numeric value will be dismissed from the field if it is a number input. Example <input type="number" id="age"> var input = document.
getElementById("age"); if (input.validity.badInput) { console.log("Bad input detected..."); } else { console.log("Content of input ok."); } Specifications Specification Status Comment HTML Living StandardThe definition of 'ValidityState.badInput' in that specification. Living Standard Live Standard HTML 5.1The definition of 'ValidityState.badInput' in that specifica...
VideoPlaybackQuality.corruptedVideoFrames - Web APIs
ed video frame. If a corrupted frame is dropped, then both corruptedVideoFrames and droppedVideoFrames are incremented. Example This example determines the percentage of frames which have been corrupted, and if the value is greater than 5%, calls a funciton called downgradeVideo() that would be implemented to switch to a different video that might tax the network less. var videoElem = document.
getElementById("my_vid"); var quality = videoElem.getVideoPlaybackQuality(); if (quality.corruptedVideoFrames/quality.totalVideoFrames > 0.05) { downgradeVideo(videoElem); } Specifications Specification Status Comment Media Playback QualityThe definition of 'VideoPlaybackQuality: corruptedVideoFrames' in that specification. Editor's Draft ...
VideoPlaybackQuality.creationTime - Web APIs
ee Performance.now(). Example This example calls getVideoPlaybackQuality() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been lost by either corruption or being dropped. If that exceeds 10% (0.1), a function called lostFramesThresholdExceeded() is called to, perhaps, update a quality indicator to show an increase in frame loss. var videoElem = document.
getElementById("my_vid"); var quality = videoElem.getVideoPlaybackQuality(); if ((quality.corruptedVideoFrames + quality.droppedVideoFrames)/quality.totalVideoFrames > 0.1) { lostFramesThresholdExceeded(); } Specifications Specification Status Comment Media Playback QualityThe definition of 'VideoPlaybackQuality.corruptedVideoFrames' in that specification. Editor's Draft Init...
VideoPlaybackQuality.totalVideoFrames - Web APIs
reloaded or replaced. Example This example calls getVideoPlaybackQuality() to obtain a VideoPlaybackQuality object, then determines what percentage of frames have been lost by either corruption or being dropped. If that exceeds 10% (0.1), a function called lostFramesThresholdExceeded() is called to, perhaps, update a quality indicator to show an increase in frame loss. var videoElem = document.
getElementById("my_vid"); var quality = videoElem.getVideoPlaybackQuality(); if ((quality.corruptedVideoFrames + quality.droppedVideoFrames)/quality.totalVideoFrames > 0.1) { lostFramesThresholdExceeded(); } A similar algorithm might be used to attempt to switch to a lower-resolution video that requires less bandwidth, in order to avoid dropping frames. Specifications Specification Status C...
Visual Viewport API - Web APIs
ultiple invocations of the transfrom that can occur when onresize and onscroll fire at the same time. Using requestAnimationFrame() ensures that the transform ocurrs before the next render. let pendingUpdate = false; function viewportHandler(event) { if (pendingUpdate) return; pendingUpdate = true; requestAnimationFrame(() => { pendingUpdate = false; var layoutViewport = document.
getElementById('layoutViewport'); // Since the bar is position: fixed we need to offset it by the // visual viewport's offset from the layout viewport origin. var viewport = event.target; var offsetLeft = viewport.offsetLeft; var offsetTop = viewport.height - layoutViewport.getBoundingClientRect().height + viewport.offsetTop; // You could also do this by...
WEBGL_debug_renderer_info - Web APIs
is disabled. This extension is available to both, WebGL1 and WebGL2 contexts. Constants ext.UNMASKED_VENDOR_WEBGL Vendor string of the graphics driver. ext.UNMASKED_RENDERER_WEBGL Renderer string of the graphics driver. ...
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
GL_debug_shaders').getTranslatedShaderSource(shader); Parameters shader A WebGLShader to get the translated source from. Return value A String containing the translated shader source. An empty string is returned, if: no source has been defined or, WebGLRenderingContext.compileShader() has not yet been called or, the translation for the shader failed. ...
WEBGL_lose_context.loseContext() - Web APIs
you to simulate losing the context of a WebGLRenderingContext context. 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' i...
WEBGL_lose_context.restoreContext() - Web APIs
The WEBGL_lose_context.restoreContext() method is part of the 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
o Using Extensions in the WebGL tutorial. Availability: This extension 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 specifi...
WebGLBuffer - Web APIs
does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLBuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindBuffer() WebGLRenderingContext.createBuffer() WebGLRenderingContext.deleteBuffer() WebGLRenderingContext.isBuffer() Examples Creating a buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLBuffer' in that specification. Recommendation Initial definition. ...
WebGLContextEvent.statusMessage - Web APIs
The read-only WebGLContextEvent.statusMessage 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
rent interface, Event. WebGLContextEvent.statusMessage A read-only 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. ...
WebGLFramebuffer - Web APIs
properties of its own and its content is not directly accessible. When working with WebGLFramebuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindFramebuffer() WebGLRenderingContext.createFramebuffer() WebGLRenderingContext.deleteFramebuffer() WebGLRenderingContext.isFramebuffer() Examples Creating a frame buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createFramebuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLFramebuffer' in that specification. Recommendation Initial definition. ...
WebGLRenderbuffer - Web APIs
ties of its own and its content is not directly accessible. When working with WebGLRenderbuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindRenderbuffer() WebGLRenderingContext.createRenderbuffer() WebGLRenderingContext.deleteRenderbuffer() WebGLRenderingContext.isRenderbuffer() Examples Creating a render buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createRenderbuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderbuffer' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.bindBuffer() - Web APIs
n attempt to bind the buffer to another target will throw an INVALID_OPERATION error and the current buffer binding will remain the same. A WebGLBuffer which has been marked for deletion with deleteBuffer cannot be (re-)bound. An attempt to do so will generate an INVALID_OPERATION error, and the current binding will remain untouched. Examples Binding a buffer to a target var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); Getting current bindings To check the current buffer bindings, query the ARRAY_BUFFER_BINDING and ELEMENT_ARRAY_BUFFER_BINDING constants. gl.getParameter(gl.ARRAY_BUFFER_BINDING); gl.getParameter(gl.ELEMENT_ARRAY_BUFFER_BINDING); Specifications Specification ...
WebGLRenderingContext.bindFramebuffer() - Web APIs
destination for drawing, rendering, clearing, and writing operations. gl.READ_FRAMEBUFFER: Used as a source for reading operations. framebuffer A WebGLFramebuffer object to bind. Return value None. Exceptions A gl.INVALID_ENUM error is thrown if target is not gl.FRAMEBUFFER, gl.DRAW_FRAMEBUFFER, or gl.READ_FRAMEBUFFER. Examples Binding a frame buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); Getting current bindings To check the current frame buffer binding, query the FRAMEBUFFER_BINDING constant. gl.getParameter(gl.FRAMEBUFFER_BINDING); Specifications Specification Status Comment WebGL 1.0The definition of 'bindFra...
WebGLRenderingContext.bindRenderbuffer() - Web APIs
r); Parameters target A GLenum specifying the binding point (target). Possible values: gl.RENDERBUFFER: Buffer data storage for single images in a renderable internal format. renderbuffer A WebGLRenderbuffer object to bind. Return value None. Exceptions A gl.INVALID_ENUM error is thrown if target is not gl.RENDERBUFFER. Examples Binding a renderbuffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer); Getting current bindings To check the current renderbuffer binding, query the RENDERBUFFER_BINDING constant. gl.getParameter(gl.RENDERBUFFER_BINDING); Specifications Specification Status Comment WebGL 1.0The definition of '...
WebGLRenderingContext.bindTexture() - Web APIs
available additionally: gl.TEXTURE_3D: A three-dimensional texture. gl.TEXTURE_2D_ARRAY: A two-dimensional array texture. texture A WebGLTexture object to bind. Return value None. Exceptions A gl.INVALID_ENUM error is thrown if target is not gl.TEXTURE_2D, gl.TEXTURE_CUBE_MAP, gl.TEXTURE_3D, or gl.TEXTURE_2D_ARRAY. Examples Binding a texture var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); Getting current bindings To check the current texture binding, query the gl.TEXTURE_BINDING_2D or gl.TEXTURE_BINDING_CUBE_MAP constants. gl.getParameter(gl.TEXTURE_BINDING_2D); Specifications Specification Status Comment WebGL 1.0The definition ...
WebGLRenderingContext.bufferData() - Web APIs
ading the buffer. length Optional A GLuint defaulting to 0. Return value None. Exceptions A gl.OUT_OF_MEMORY error is thrown if the context is unable to create a data store with the given size. A gl.INVALID_VALUE error is thrown if size is negative. A gl.INVALID_ENUM error is thrown if target or usage are not one of the allowed enums. Examples Using bufferData var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, 1024, gl.STATIC_DRAW); Getting buffer information To check the current buffer usage and buffer size, use the WebGLRenderingContext.getBufferParameter() method. gl.getBufferParameter(gl.ARRAY_BUFFER, gl.BUFFER_SIZE); gl.getBufferParameter(gl.ARR...
WebGLRenderingContext.bufferSubData() - Web APIs
int specifying the element index offset where to start reading the buffer. length Optional A GLuint defaulting to 0. Return value None. Exceptions A gl.INVALID_VALUE error is thrown if the data would be written past the end of the buffer or if data is null. A gl.INVALID_ENUM error is thrown if target is not one of the allowed enums. Examples Using bufferSubData var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, 1024, gl.STATIC_DRAW); gl.bufferSubData(gl.ARRAY_BUFFER, 512, data); Specifications Specification Status Comment WebGL 1.0The definition of 'bufferSubData' in that specification. Recommendation Initial definition fo...
WebGLRenderingContext.canvas - Web APIs
t. It might be null if it is not associated with a <canvas> element or an OffscreenCanvas object. Syntax gl.canvas; Return value Either a HTMLCanvasElement or OffscreenCanvas object or null. Examples Canvas element Given this <canvas> element: <canvas id="canvas"></canvas> You can get back a reference to it from the WebGLRenderingContext using the canvas property: var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.canvas; // HTMLCanvasElement Offscreen canvas Example using the experimental OffscreenCanvas object. var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext('webgl'); gl.canvas; // OffscreenCanvas Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderingContext.canvas...
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
x of renderbuffers and textures. When using the OVR_multiview2 extension, the following value can be returned additionally: ext.FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR: If baseViewIndex is not the same for all framebuffer attachment points where the value of FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is not NONE, the framebuffer is considered incomplete. Examples var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); // ... gl.checkFramebufferStatus(gl.FRAMEBUFFER); Specifications Specification Status Comment WebGL 1.0The definition of 'checkFramebufferStatus' in that specification. Recommendation Initial definition for WebGL. OpenGL ES 2.0The definition of 'glCheckFramebufferS...
WebGLRenderingContext.createBuffer() - Web APIs
The WebGLRenderingContext.createBuffer() method of the WebGL API creates and initializes a WebGLBuffer storing data such as vertices or colors. Syntax WebGLBuffer gl.createBuffer(); Parameters None. Return value A WebGLBuffer storing data such as vertices or colors. Examples Creating a buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'createBuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenBuffers' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.createFramebuffer() - Web APIs
The WebGLRenderingContext.createFramebuffer() method of the WebGL API creates and initializes a WebGLFramebuffer object. Syntax WebGLFramebuffer gl.createFramebuffer(); Parameters None. Return value A WebGLFramebuffer object. Examples Creating a frame buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'createFramebuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenFramebuffers' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.createRenderbuffer() - Web APIs
The WebGLRenderingContext.createRenderbuffer() method of the WebGL API creates and initializes a WebGLRenderbuffer object. Syntax WebGLRenderbuffer gl.createRenderbuffer(); Parameters None. Return value A WebGLRenderbuffer object that stores data such an image, or can be source or target of an rendering operation. Examples Creating a render buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderBuffer = gl.createRenderBuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'createRenderbuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenRenderbuffers' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.createTexture() - Web APIs
The WebGLRenderingContext.createTexture() method of the WebGL API creates and initializes a WebGLTexture object. Syntax WebGLTexture gl.createTexture(); Parameters None. Return value A WebGLTexture object to which images can be bound to. Examples See also the WebGL tutorial on Using textures in WebGL. Creating a texture var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); Specifications Specification Status Comment WebGL 1.0The definition of 'createTexture' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenTextures' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.deleteBuffer() - Web APIs
The WebGLRenderingContext.deleteBuffer() method of the WebGL API deletes a given WebGLBuffer. This method has no effect if the buffer has already been deleted. Syntax void gl.deleteBuffer(buffer); Parameters buffer A WebGLBuffer object to delete. Return value None. Examples Deleting a buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); // ... gl.deleteBuffer(buffer); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteBuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteBuffers' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.deleteFramebuffer() - Web APIs
The WebGLRenderingContext.deleteFramebuffer() method of the WebGL API deletes a given WebGLFramebuffer object. This method has no effect if the frame buffer has already been deleted. Syntax void gl.deleteFramebuffer(framebuffer); Parameters framebuffer A WebGLFramebuffer object to delete. Return value None. Examples Deleting a frame buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); // ... gl.deleteFramebuffer(framebuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteFramebuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteFramebuffers' in that specification. Standard Man ...
WebGLRenderingContext.deleteProgram() - Web APIs
The WebGLRenderingContext.deleteProgram() method of the WebGL API deletes a given WebGLProgram object. This method has no effect if the program has already been deleted. Syntax void gl.deleteProgram(program); Parameters program A WebGLProgram object to delete. Return value None. Examples Deleting a program var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var program = gl.createProgram(); // ... gl.deleteProgram(program); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteProgram' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteProgram' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.deleteRenderbuffer() - Web APIs
The WebGLRenderingContext.deleteRenderbuffer() method of the WebGL API deletes a given WebGLRenderbuffer object. This method has no effect if the render buffer has already been deleted. Syntax void gl.deleteRenderbuffer(renderbuffer); Parameters renderbuffer A WebGLRenderbuffer object to delete. Return value None. Examples Deleting a renderbuffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); // ... gl.deleteRenderbuffer(renderbuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteRenderbuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteRenderbuffers' in that specification. Sta...
WebGLRenderingContext.deleteTexture() - Web APIs
The WebGLRenderingContext.deleteTexture() method of the WebGL API deletes a given WebGLTexture object. This method has no effect if the texture has already been deleted. Syntax void gl.deleteTexture(texture); Parameters texture A WebGLTexture object to delete. Return value None. Examples Deleting a texture var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); // ... gl.deleteTexture(texture); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteTexture' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteTextures' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.drawingBufferHeight - Web APIs
current drawing buffer. It should match the height attribute of the <canvas> element associated with this context, but might differ if the implementation is not able to provide the requested height. Syntax gl.drawingBufferHeight; Examples Given this <canvas> element: <canvas id="canvas"></canvas> You can get the height of the drawing buffer with the following lines: var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.drawingBufferHeight; // 150 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderingContext.drawingBufferHeight' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.drawingBufferWidth - Web APIs
the current drawing buffer. It should match the width attribute of the <canvas> element associated with this context, but might differ if the implementation is not able to provide the requested width. Syntax gl.drawingBufferWidth; Examples Given this <canvas> element: <canvas id="canvas"></canvas> You can get the width of the drawing buffer with the following lines: var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.drawingBufferWidth; // 300 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderingContext.drawingBufferWidth' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.getContextAttributes() - Web APIs
bGLContextAttributes object that contains the actual context parameters. Might return null, if the context is lost. Syntax gl.getContextAttributes(); Return value A WebGLContextAttributes object that contains the actual context parameters, or null if the context is lost. ...
WebGLRenderingContext.getExtension() - Web APIs
rameters name A String for the name of the WebGL extension to enable. Return value A WebGL extension object, or null if name does not match (case-insensitive) to one of the strings in WebGLRenderingContext.getSupportedExtensions. Examples Once a WebGL extension is enabled, you are able to use the methods, properties or constants that this extension object provides. var canvas = document.
getElementById('canvas'); gl = canvas.getContext('webgl'); gl.getExtension('WEBGL_lose_context').loseContext(); WebGL extensions Extensions for the WebGL API are registered in the WebGL Extension Registry. The current extensions are: ANGLE_instanced_arrays EXT_blend_minmax EXT_color_buffer_float EXT_color_buffer_half_float EXT_disjoint_timer_query EXT_float_blend EXT_frag_depth EXT_sRGB EXT_sh...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
, gl.MEDIUM_INT, or gl.HIGH_INT. Return value A WebGLShaderPrecisionFormat object or null, if an error occurs. Exceptions gl.INVALID_ENUM if the shader or precision types aren't recognized. gl.INVALID_OPERATION if the shader compiler isn't supported. Examples The following code gets the precision format of a gl.VERTEX_SHADER with a gl.MEDIUM_FLOAT precision type. var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT); // WebGLShaderPrecisionFormat { rangeMin: 127, rangeMax: 127, precision: 23 } Specifications Specification Status Comment WebGL 1.0The definition of 'getShaderPrecisionFormat' in that specification. Recommendation Initial definition. OpenGL ES ...
WebGLRenderingContext.isBuffer() - Web APIs
The WebGLRenderingContext.isBuffer() method of the WebGL API returns true if the passed WebGLBuffer is valid and false otherwise. Syntax GLboolean gl.isBuffer(buffer); Parameters buffer A WebGLBuffer to check. Return value A GLboolean indicating whether or not the buffer is valid. Examples Creating a buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.isBuffer(buffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isBuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsBuffer' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.isFramebuffer() - Web APIs
The WebGLRenderingContext.isFramebuffer() method of the WebGL API returns true if the passed WebGLFramebuffer is valid and false otherwise. Syntax GLboolean gl.isFramebuffer(framebuffer); Parameters framebuffer A WebGLFramebuffer to check. Return value A GLboolean indicating whether or not the frame buffer is valid. Examples Checking a frame buffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); gl.isFramebuffer(framebuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isFramebuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsFramebuffer' in that specification. Standard Man page of the...
WebGLRenderingContext.isProgram() - Web APIs
The WebGLRenderingContext.isProgram() method of the WebGL API returns true if the passed WebGLProgram is valid, false otherwise. Syntax GLboolean gl.isProgram(program); Parameters program A WebGLProgram to check. Return value A GLboolean indicating whether or not the program is valid. Examples Checking a program var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var program = gl.createProgram(); // ... gl.isProgram(program); Specifications Specification Status Comment WebGL 1.0The definition of 'isProgram' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsProgram' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.isRenderbuffer() - Web APIs
The WebGLRenderingContext.isRenderbuffer() method of the WebGL API returns true if the passed WebGLRenderbuffer is valid and false otherwise. Syntax GLboolean gl.isRenderbuffer(renderbuffer); Parameters renderbuffer A WebGLRenderbuffer to check. Return value A GLboolean indicating whether or not the renderbuffer is valid. Examples Checking a renderbuffer var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); gl.isRenderbuffer(renderbuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isRenderbuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsRenderbuffer' in that specification. Standard Man...
WebGLRenderingContext.isShader() - Web APIs
The WebGLRenderingContext.isShader() method of the WebGL API returns true if the passed WebGLShader is valid, false otherwise. Syntax GLboolean gl.isShader(shader); Parameters shader A WebGLShader to check. Return value A GLboolean indicating whether or not the shader is valid. Examples Checking a shader var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var shader = gl.createShader(gl.VERTEX_SHADER); // ... gl.isShader(shader); Specifications Specification Status Comment WebGL 1.0The definition of 'isShader' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsShader' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.isTexture() - Web APIs
The WebGLRenderingContext.isTexture() method of the WebGL API returns true if the passed WebGLTexture is valid and false otherwise. Syntax GLboolean gl.isTexture(texture); Parameters texture A WebGLTexture to check. Return value A GLboolean indicating whether or not the texture is valid. Examples Checking a texture var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); gl.isTexture(texture); Specifications Specification Status Comment WebGL 1.0The definition of 'isTexture' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsTexture' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.readPixels() - Web APIs
an accepted value. A gl.INVALID_OPERATION error is thrown if type is gl.UNSIGNED_SHORT_5_6_5 and format is not gl.RGB. type is gl.UNSIGNED_SHORT_4_4_4_4 and format is not gl.RGBA. type does not match the typed array type of pixels. A gl.INVALID_FRAMEBUFFER_OPERATION error is thrown if the currently bound framebuffer is not framebuffer complete. ...
WebGLRenderingContext - Web APIs
The WebGLRenderingContext interface provides an interface to the OpenGL ES 2.0 graphics rendering context for the drawing surface of an HTML <canvas> element. To get an access to a WebGL context for 2D and/or 3D graphics rendering, call getContext() on a <canvas> element, supplying "webgl" as the argument: var canvas = document.
getElementById('myCanvas'); var gl = canvas.getContext('webgl'); Once you have the WebGL rendering context for a canvas, you can render within it. The WebGL tutorial has more information, examples, and resources on how to get started with WebGL. If you require a WebGL 2.0 context, see WebGL2RenderingContext; this supplies access to an implementation of OpenGL ES 3.0 graphics. Constants See the WebGL constants page. The WebGL context The following properties and method...
WebGLShaderPrecisionFormat.precision - Web APIs
The read-only WebGLShaderPrecisionFormat.precision property returns the number of bits of precision that can be represented. For integer formats this value is always 0. Examples var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision; // 23 gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).precision; // 0 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat.precision' in that specification. Recommendation Initial definition. ...
WebGLShaderPrecisionFormat.rangeMax - Web APIs
The read-only WebGLShaderPrecisionFormat.rangeMax property returns the base 2 log of the absolute value of the maximum value that can be represented. Examples var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).rangeMax; // 127 gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).rangeMax; // 24 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat.rangeMax' in that specification. Recommendation Initial definition. ...
WebGLShaderPrecisionFormat.rangeMin - Web APIs
The read-only WebGLShaderPrecisionFormat.rangeMin property returns the base 2 log of the absolute value of the minimum value that can be represented. Examples var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).rangeMin; // 127 gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).rangeMin; // 24 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat.rangeMin' in that specification. Recommendation Initial definition. ...
WebGLShaderPrecisionFormat - Web APIs
ngeMax Read only The base 2 log of the absolute value of the maximum value that can be represented. WebGLShaderPrecisionFormat.precision Read only The number of bits of precision that can be represented. For integer formats this value is always 0. Examples A WebGLShaderPrecisionFormat object is returned by the WebGLRenderingContext.getShaderPrecisionFormat() method. var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT); // WebGLShaderPrecisionFormat { rangeMin: 127, rangeMax: 127, precision: 23 } Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat' in that specification. Recommendation Initial definition. ...
WebGLTexture - Web APIs
ot define any methods or properties of its own and its content is not directly accessible. When working with WebGLTexture objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindTexture() WebGLRenderingContext.createTexture() WebGLRenderingContext.deleteTexture() WebGLRenderingContext.isTexture() Examples Creating a texture var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLTexture' in that specification. Recommendation Initial definition. ...
WebGLUniformLocation - Web APIs
am. Description The WebGLUniformLocation object does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLUniformLocation objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.getUniformLocation() WebGLRenderingContext.uniform() Examples Getting an uniform location var canvas = document.
getElementById('canvas'); var gl = canvas.getContext('webgl'); var location = gl.getUniformLocation(WebGLProgram, 'uniformName'); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLUniformLocation' in that specification. Recommendation Initial definition. ...
Simple color animation - Web APIs
stopAnimation, false); button.addEventListener("click", startAnimation, false); verb.innerHTML="start"; // Stop animation by clearing the timer. clearInterval(timer); } // Call stopAnimation() once to setup the initial event // handlers for canvas and button. ...
Matrix math for the web - Web APIs
o a matrix3d. Bear in mind that even though the matrix is made up of 4 rows and 4 columns, it collapses into a single line of 16 values. Matrices are always stored in one-dimensional lists in JavaScript. // Create the matrix3d style property from a matrix array function matrixArrayToCssMatrix(array) { return 'matrix3d(' + array.join(',') + ')'; } // Grab the DOM element let moveMe = document.
getElementById('move-me'); // Returns a result like: "matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 50, 100, 0, 1);" let matrix3dRule = matrixArrayToCssMatrix(translationMatrix); // Set the transform moveMe.style.transform = matrix3dRule; View on JSFiddle Scale matrix A scale matrix makes something larger or smaller in one or more of the three dimensions: width, height, and depth. In typical (cartesian) ...
WebGL model view projection - Web APIs
ample will create a custom WebGLBox object that will draw a 2D box on the screen. Note: The code for each WebGLBox example is available in this github repo and is organized by section. In addition there is a JSFiddle link at the bottom of each section. ...
Window: blur event - Web APIs
L <p id="log">Click on this document to give it focus.</p> CSS .paused { background: #ddd; color: #555; } JavaScript function pause() { document.body.classList.add('paused'); log.textContent = 'FOCUS LOST!'; } function play() { document.body.classList.remove('paused'); log.textContent = 'This document has focus. Click outside the document to lose focus.'; } const log = document.
getElementById('log'); window.addEventListener('blur', pause); window.addEventListener('focus', play); Result Specifications Specification 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.clearImmediate() - Web APIs
diate. This method is not 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.crypto - Web APIs
r IE 11 Value An instance of the Crypto interface, providing access to general-purpose cryptography and a strong random-number generator. Example This example uses the Window.crypto property to access the getRandomValues() method. ...
Window.customElements - Web APIs
Specification Specification Status Comment HTML Living StandardThe definition of 'window.customElements' in that specification. Living Standa...
Window.devicePixelRatio - Web APIs
ore often, when a screen has a higher pixel depth than simply double the standard resolution of 96 or 76 DPI. Examples Correcting resolution in a <canvas> A <canvas> can appear too blurry on retina screens. Use window.devicePixelRatio to determine how much extra pixel density should be added to allow for a sharper image. HTML <canvas id="canvas"></canvas> JavaScript var canvas = document.
getElementById('canvas'); var ctx = canvas.getContext('2d'); // Set display size (css pixels). var size = 200; canvas.style.width = size + "px"; canvas.style.height = size + "px"; // Set actual size in memory (scaled to account for extra pixel density). var scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas. canvas.width = Math.floor(size * scale); canvas.height = Math.floo...
Window: focus event - Web APIs
L <p id="log">Click on this document to give it focus.</p> CSS .paused { background: #ddd; color: #555; } JavaScript function pause() { document.body.classList.add('paused'); log.textContent = 'FOCUS LOST!'; } function play() { document.body.classList.remove('paused'); log.textContent = 'This document has focus. Click outside the document to lose focus.'; } const log = document.
getElementById('log'); window.addEventListener('blur', pause); window.addEventListener('focus', play); Result Specifications Specification 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.requestAnimationFrame() - Web APIs
example, an element is animated for 2 seconds (2000 milliseconds). The element moves at a speed of 0.1px/ms to the right, so its relative position (in CSS pixels) can be calculated in function of the time elapsed since the start of the animation (in milliseconds) with 0.1 * elapsed. The element's final position is 200px (0.1 * 2000) to the right of its initial position. const element = document.
getElementById('some-element-you-want-to-animate'); let start; function step(timestamp) { if (start === undefined) start = timestamp; const elapsed = timestamp - start; // `Math.min()` is used here to make sure that the element stops at exactly 200px. element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)'; if (elapsed < 2000) { // Stop the animation after 2 seconds w...
Window.sessionStorage - Web APIs
n. Example The following snippet accesses the current origin's session Storage object and adds data to it with Storage.setItem(). sessionStorage.setItem('myCat', 'Tom'); The following example autosaves the contents of a text field, and if the browser is refreshed, restores the text field content so that no writing is lost. ...
self.createImageBitmap() - Web APIs
e A Promise which resolves to an ImageBitmap object containing bitmap data from the given rectangle. Example Creating sprites from a sprite sheet This example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas. A sprite sheet is an image containing multiple smaller images, each of which you want to be able to render separately. ...
Using the slider role - Accessibility
a-valuemin="1" aria-valuemax="7" aria-valuenow="2" aria-valuetext="Monday"> </div> </div> The code snippet below shows a function that responds to user input and updates the aria-valuenow and aria-valuetext attributes: var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var updateSlider = function (newValue) { var handle = document.
getElementById("day-handle"); handle.setAttribute("aria-valuenow", newValue.toString()); handle.setAttribute("aria-valuetext", dayNames[newValue]); }; Working Examples: Slider example Notes ARIA attributes used aria-valuemin aria-valuemax aria-valuenow aria-valuetext aria-orientation Related ARIA techniques Compatibility TBD: Add support information for common UA and AT produc...
ARIA: timer role - Accessibility
der a site with a simple clock, showing hours and minutes. The clock is updated each minute, with the new remaining time simply overwriting the current content. <div id="clock" role="timer" aria-live="off">20</div> <button onclick="startTimer('clock')">start</button> /* basic JavaScript to update a timer */ function startTimer(timerName) { // get the number of seconds let timer = document.
getElementById(timerName), seconds = parseInt(timer.innerText); // remove a second // updated the content of timer timer.innerText = --seconds // if timer != 0, setTimeout if (seconds) { setTimeout( function() { startTimer(timerName); }, 1000); } } The first time the function executes, the entirety of the string that is added will be announced. On subsequent calls, only the ...
ARIA: checkbox role - Accessibility
ckbox()" tabindex="0" aria-labelledby="chk1-label"></span> <label id="chk1-label" onclick="changeCheckbox()" onKeyPress="changeCheckbox()">Remember my preferences</label> CSS [role="checkbox"] { padding:5px; } [aria-checked="true"]::before { content: "[x]"; } [aria-checked="false"]::before { content: "[ ]"; } JavaScript function changeCheckbox(event) { let item = document.
getElementById('chkPref'); switch(item.getAttribute('aria-checked')) { case "true": item.setAttribute('aria-checked', "false"); break; case "false": item.setAttribute('aria-checked', "true"); break; } } Accessibility concerns When the checkbox role is added to an element, the user agent should do the following: Expose the element as ...
ARIA - Accessibility
ttributes specify the minimum and maximum values for the progress bar, and the aria-valuenow describes the current state of it and therefore must be kept updated with JavaScript. Along with placing them directly in the markup, ARIA attributes can be added to the element and updated dynamically using JavaScript code like this: // Find the progress bar <div> in the DOM. var progressBar = document.
getElementById("percent-loaded"); // Set its ARIA roles and states, // so that assistive technologies know what kind of widget it is. progressBar.setAttribute("role", "progressbar"); progressBar.setAttribute("aria-valuemin", 0); progressBar.setAttribute("aria-valuemax", 100); // Create a function that can be called at any time to update // the value of the progress bar. function updateProgress(percentComplete...
::slotted() - CSS: Cascading Style Sheets
person-name">NAME MISSING</slot> <ul> <li><slot name="person-age">AGE MISSING</slot></li> <li><slot name="person-occupation">OCCUPATION MISSING</slot></li> </ul> </div> </template> A custom element -- <person-details> -- is defined like so: customElements.define('person-details', class extends HTMLElement { constructor() { super(); let template = document.
getElementById('person-template'); let templateContent = template.content; const shadowRoot = this.attachShadow({mode: 'open'}); let style = document.createElement('style'); style.textContent = 'div { padding: 10px; border: 1px solid gray; width: 200px; margin: 10px; }' + 'h2 { margin: 0 0 10px; }' + 'ul { margin: 0; }' + ...
:disabled - CSS: Cascading Style Sheets
"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++) { billingItems[i].disabled = !billingItems[i].disabled; } } Result Specifications Specificati...
Coordinate systems - CSS: Cascading Style Sheets
vents we watch. Displaying the coordinates As we'll see in the HTML, the inner box (the one we're watching for events on) contains several paragraphs; one for each of the four coordinate systems we'll be reporting on. let inner = document.querySelector(".inner"); let log = document.querySelector(".log"); function setCoords(e, type) { let idX = type + "X"; let idY = type + "Y"; document.
getElementById(idX).innerText = e[idX]; document.
getElementById(idY).innerText = e[idY]; } A reference to the <div> inside the inner box which contains the paragraphs that will show the coordinate information is fetched into log. The setCoords() function is designed to accept as input a MouseEvent and the name of the origin to use when obtaining the coordinates. The implementation is then quite simple. The...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
shows how you'd achieve the aforementioned JavaScript technique: .slidein { animation-duration: 5s; animation-name: slidein; animation-iteration-count: infinite; } .stopped { animation-name: none; } @keyframes slidein { 0% { margin-left: 0%; } 50% { margin-left: 50%; } 100% { margin-left: 0%; } } <h1 id="watchme">Click me to stop</h1> let watchme = document.
getElementById('watchme') watchme.className = 'slidein' const listener = (e) => { watchme.className = 'slidein stopped' } watchme.addEventListener('click', () => watchme.addEventListener('animationiteration', listener, false) ) Demo https://jsfiddle.net/morenoh149/5ty5a4oy/ ...
Border-image generator - CSS: Cascading Style Sheets
ar elem = document.querySelectorAll('.ui-checkbox'); var size = elem.length; for (var i = 0; i < size; i++) new CheckBox(elem[i]); }; return { init : init, setValue : setValue, subscribe : subscribe, unsubscribe : unsubscribe }; })(); window.addEventListener("load", function() { BorderImage.init(); }); var BorderImage = (function BorderImage() { var getElemById = document.
getElementById.bind(document); var subject; var preview; var guidelines = []; var positions = ['top', 'right', 'bottom', 'left']; var makeDraggable = function makeDraggable(elem) { var offsetTop; var offsetLeft; elem.setAttribute('data-draggable', 'true'); var dragStart = function dragStart(e) { if (e.target.getAttribute('data-draggable') !== 'true' || e.target !== elem || e.button !== ...
Box-shadow generator - CSS: Cascading Style Sheets
document.querySelectorAll('.ui-checkbox'); var size = elem.length; for (var i = 0; i < size; i++) new CheckBox(elem[i]); } return { init : init, setValue : setValue, subscribe : subscribe, unsubscribe : unsubscribe } })(); window.addEventListener("load", function(){ BoxShadow.init(); }); var BoxShadow = (function BoxShadow() { function getElemById(id) { return document.
getElementById(id); } /** * RGBA Color class */ function Color() { this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; } Color.prototype.copy = function copy(obj) { if(obj instanceof Color !== true) { console.log("Typeof instance not Color"); return; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; thi...
Using CSS transitions - CSS: Cascading Style Sheets
ansition to. Using transitions to make JavaScript functionality smooth Transitions are a great tool to make things look much smoother without having to do anything to your JavaScript functionality. 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...
align-content - CSS: Cascading Style Sheets
nsafe center</option> <option value="safe right">safe right</option> <option value="unsafe right">unsafe right</option> <option value="safe end">safe end</option> <option value="unsafe end">unsafe end</option> <option value="safe flex-end">safe flex-end</option> <option value="unsafe flex-end">unsafe flex-end</option> </select> </div> JavaScript var values = document.
getElementById('values'); var display = document.
getElementById('display'); var container = document.
getElementById('container'); values.addEventListener('change', function (evt) { container.style.alignContent = evt.target.value; }); display.addEventListener('change', function (evt) { container.className = evt.target.value; }); Result Specifications Specification Status Comment ...
align-items - CSS: Cascading Style Sheets
</option> <option value="safe end">safe end</option> <option value="unsafe end">unsafe end</option> <option value="safe self-end">safe self-end</option> <option value="unsafe self-end">unsafe self-end</option> <option value="safe flex-end">safe flex-end</option> <option value="unsafe flex-end">unsafe flex-end</option> </select> </div> JavaScript var values = document.
getElementById('values'); var display = document.
getElementById('display'); var container = document.
getElementById('container'); values.addEventListener('change', function (evt) { container.style.alignItems = evt.target.value; }); display.addEventListener('change', function (evt) { container.className = evt.target.value; }); Result Specifications Specification Status Comment ...
border-image-slice - CSS: Cascading Style Sheets
t">30</output> </li> </ul> CSS .wrapper { width: 400px; height: 300px; } div > div { width: 300px; height: 200px; border-width: 30px; border-style: solid; border-image: url(https://udn.realityripple.com/samples/56/bb98f533ef.png); border-image-slice: 30; border-image-repeat: round; } li { display: flex; place-content: center; } JavaScript const widthSlider = document.
getElementById('width'); const sliceSlider = document.
getElementById('slice'); const widthOutput = document.
getElementById('width-output'); const sliceOutput = document.
getElementById('slice-output'); const divElem = document.querySelector('div > div'); widthSlider.addEventListener('input', () => { const newValue = widthSlider.value + 'px'; divElem.style.borderWidth = newValue; widthOutput.textContent = ...
flex - CSS: Cascading Style Sheets
? | <'flex-basis'> ] Examples Setting flex: auto HTML <div id="flex-container"> <div class="flex-item" id="flex">Flex box (click to toggle raw box)</div> <div class="raw-item" id="raw">Raw box</div> </div> CSS #flex-container { display: flex; flex-direction: row; } #flex-container > .flex-item { flex: auto; } #flex-container > .raw-item { width: 5rem; } var flex = document.
getElementById("flex"); var raw = document.
getElementById("raw"); flex.addEventListener("click", function() { raw.style.display = raw.style.display == "none" ? "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 Specifi...
font - CSS: Cascading Style Sheets
ize") + getCheckedValue("line_height") + " " + getCheckedValue("font_family"); return shortText; } getCheckedValue = function(radio_name) { oRadio = document.forms[0].elements[radio_name]; for (var i = 0; i < oRadio.length; i++) { if(oRadio[i].checked) { var propInput = "input_" + radio_name, curElemName = "input_" + radio_name, curElem = document.
getElementById(curElemName); curElem.value = oRadio[i].value; return oRadio[i].value; } } } setCss = function () { getProperties(); injectCss(shortText); } injectCss = function(cssFragment) { old = document.body.getElementsByTagName("style"); if (old.length > 1) { old[1].parentElement.removeChild(old[1]); } css = document.createElement("style"); css.innerHTML = ".fontShort...
mask-repeat - CSS: Cascading Style Sheets
: 10px; } HTML Content <div id="masked"> </div> <select id="repetition"> <option value="repeat-x">repeat-x</option> <option value="repeat-y">repeat-y</option> <option value="repeat" selected>repeat</option> <option value="space">space</option> <option value="round">round</option> <option value="no-repeat">no-repeat</option> </select> JavaScript Content var repetition = document.
getElementById("repetition"); repetition.addEventListener("change", function (evt) { document.
getElementById("masked").style.maskRepeat = evt.target.value; }); Result Multiple mask image support You can specify a different <repeat-style> for each mask image, separated by commas: .examplethree { mask-image: url('mask1.png'), url('mask2.png'); mask-repeat: repeat-x, repeat-y; } Each image is match...
place-items - CSS: Cascading Style Sheets
ue="left auto">left auto</option> <option value="right normal">right normal</option> <option value="baseline normal">baseline normal</option> <option value="first baseline auto">first baseline auto</option> <option value="last baseline normal">last baseline normal</option> <option value="stretch auto">stretch auto</option> </select> </div> JavaScript var values = document.
getElementById('values'); var display = document.
getElementById('display'); var container = document.
getElementById('container'); values.addEventListener('change', function (evt) { container.style.placeItems = evt.target.value; }); display.addEventListener('change', function (evt) { container.className = evt.target.value; }); CSS #container { height:200px; width: 240px; place-items: center; /* Y...
transform-style - CSS: Cascading Style Sheets
.right { background: rgba(210,0,0,.7); transform: rotateY(90deg) translateZ(50px); } .left { background: rgba(0,0,210,.7); transform: rotateY(-90deg) translateZ(50px); } .top { background: rgba(210,210,0,.7); transform: rotateX(90deg) translateZ(50px); } .bottom { background: rgba(210,0,210,.7); transform: rotateX(-90deg) translateZ(50px); } JavaScript const cube = document.
getElementById('example-element'); const checkbox = document.
getElementById('preserve'); checkbox.addEventListener('change', () => { if(checkbox.checked) { cube.style.transformStyle = 'preserve-3d'; } else { cube.style.transformStyle = 'flat'; } }) Result Specifications Specification Status Comment CSS Transforms Level 2The definition of 'transform-style' in that ...
will-change - CSS: Cascading Style Sheets
itial valueautoApplies toall elementsInheritednoComputed valueas specifiedAnimation 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. ...
Adding captions and subtitles to HTML5 video - Developer guides
ontrols, this button is hidden, and we need to define our own. Browsers do vary as to what they support, so we will be attempting to bring a more unified UI to each browser where possible. There's more on browser compatibility issues later on. Initial setup As with all the other buttons, one of the first things we need to do is store a handle to the subtitles' button: var subtitles = document.
getElementById('subtitles'); We also initially turn off all subtitles, in case the browser turns any of them on by default: for (var i = 0; i < video.textTracks.length; i++) { video.textTracks[i].mode = 'hidden'; } The video.textTracks property contains an array of all the text tracks attached to the video. We loop through each one and set its mode to hidden. Note: The WebVTT API gives us access to all t...
Creating and triggering events - Developer guides
s: true, detail: { text: () => textarea.value } })) }); Triggering built-in events This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. View the example in action. function simulateClick() { const event = new MouseEvent('click', { view: window, bubbles: true, cancelable: true }); const cb = document.
getElementById('checkbox'); const cancelled = !cb.dispatchEvent(event); if (cancelled) { // A handler called preventDefault. alert("cancelled"); } else { // None of the handlers called preventDefault. alert("not cancelled"); } } ...
Making content editable - Developer guides
pboard.sites", "https://www.mozilla.org"); user_pref("capability.policy.allowclipboard.Clipboard.cutcopy", "allAccess"); user_pref("capability.policy.allowclipboard.Clipboard.paste", "allAccess"); Example: A simple but complete rich text editor <!doctype html> <html> <head> <title>Rich Text Editor</title> <script type="text/javascript"> var oDoc, sDefTxt; function initDoc() { oDoc = document.
getElementById("textBox"); sDefTxt = oDoc.innerHTML; if (document.compForm.switchMode.checked) { setDocMode(true); } } function formatDoc(sCmd, sValue) { if (validateMode()) { document.execCommand(sCmd, false, sValue); oDoc.focus(); } } function validateMode() { if (!document.compForm.switchMode.checked) { return true ; } alert("Uncheck \"Show HTML\"."); oDoc.focus(); return false; } function s...
User input and controls - Developer guides
found in Managing screen orientation. Fullscreen You might need to present an element of your application (such as a <video>, for example) in fullscreen mode. You can achieve this by calling Element.requestFullscreen() on that element. ...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
<option>Red panda</option> <option>Spider monkey</option> </select> </label></p> <menu> <button value="cancel">Cancel</button> <button id="confirmBtn" value="default">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <output aria-live="polite"></output> JavaScript var updateButton = document.
getElementById('updateDetails'); var favDialog = document.
getElementById('favDialog'); var outputBox = document.querySelector('output'); var selectEl = document.querySelector('select'); var confirmBtn = document.
getElementById('confirmBtn'); // "Update details" button opens the <dialog> modally updateButton.addEventListener('click', function onOpen() { if (typeof favDialog.showModal === "function") { fav...
<input type="time"> - HTML: Hypertext Markup Language
e"> <p> Value of the <code>time</code> input: <code> "<span id="value">n/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 in...
<script>: The Script element - HTML: Hypertext Markup Language
data in HTML You can also use the <script> element to embed data in HTML with server-side rendering by specifying a valid non-JavaScript MIME type in the type attribute. <!-- Generated by the server --> <script id="data" type="application/json">{"userId":1234,"userName":"John Doe","memberSince":"2000-01-01T00:00:00.000Z"}</script> <!-- Static --> <script> const userInfo = JSON.parse(document.
getElementById("data").text); console.log("User information: %o", userInfo); </script> Specifications Specification Status Comments HTML Living StandardThe definition of '<script>' in that specification. Living Standard Removed the charset attribute HTML5The definition of '<script>' in that specification. Recommendation HTML 4.01 SpecificationThe d...
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 infor...
CSP: script-src - HTTP
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 that matches the inline block can...
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.
Regular expressions - JavaScript
the remembered match of a dash, forward slash, or decimal point \1, followed by four digits \d{4}. The Change event activated when the user presses Enter sets the value of RegExp.input. HTML <p> Enter your phone number (with area code) and then click "Check". <br> The expected format is like ###-###-####. ...
Memory Management - JavaScript
se of memory leaks. function f() { var x = {}; var y = {}; x.a = y; // x references y y.a = x; // y references x return 'azerty'; } f(); Real-life example Internet Explorer 6 and 7 are known to have reference-counting garbage collectors for DOM objects. Cycles are a common mistake that can generate memory leaks: var div; window.onload = function() { div = document.
getElementById('myDivElement'); div.circularReference = div; div.lotsOfData = new Array(10000).join('*'); }; In the above example, the DOM element "myDivElement" has a circular reference to itself in the "circularReference" property. If the property is not explicitly removed or nulled, a reference-counting garbage collector will always have at least one reference intact and will keep the DOM element in me...
SyntaxError: missing variable name - JavaScript
able names There are a few variable names that are reserved keywords. You can't use these. Sorry :( var debugger = "whoop"; // SyntaxError: missing variable name Declaring multiple variables Pay special attention to commas when declaring multiple variables. Is there an excess comma? Did you accidentally add commas instead of semicolons? var x, y = "foo", var x, = "foo" var first = document.
getElementById('one'), var second = document.
getElementById('two'), // SyntaxError: missing variable name The fixed version: var x, y = "foo"; var x = "foo"; var first = document.
getElementById('one'); var second = document.
getElementById('two'); Arrays Array literals in JavaScript need square brackets around the values. This won't work: var arr = 1,2,3,4,5; // SyntaxError: missing variable name This ...
getter - JavaScript
azy" or "memozied" by nature; you must implement this technique if you desire this behavior. In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value gets returned. get notifier() { delete this.notifier; return this.notifier = document.
getElementById('bookmarked-notification-anchor'); }, For Firefox code, see also the XPCOMUtils.jsm code module, which defines the defineLazyGetter() function. get vs. defineProperty While using the get keyword and Object.defineProperty() have similar results, there is a subtle difference between the two when used on classes. When using get the property will be defined on the instance's prototype, while usin...
Array.prototype[@@iterator]() - JavaScript
t as the initial value of the values() property. Syntax arr[Symbol.iterator]() Return value The initial value given by the values() iterator. By default, using arr[Symbol.iterator] will return the values() function. ...
Proxy - JavaScript
, newval) { let oldval = obj[prop]; if (prop === 'selected') { if (oldval) { oldval.setAttribute('aria-selected', 'false'); } if (newval) { newval.setAttribute('aria-selected', 'true'); } } // The default behavior to store the value obj[prop] = newval; // Indicate success return true; } }); let i1 = view.selected = document.
getElementById('item-1'); //giving error here, i1 is null console.log(i1.getAttribute('aria-selected')); // 'true' let i2 = view.selected = document.
getElementById('item-2'); console.log(i1.getAttribute('aria-selected')); // 'false' console.log(i2.getAttribute('aria-selected')); // 'true' Note: even if selected: !null, then giving oldval.setAttribute is not a function Value correction and an extra prope...
WebAssembly.Global() constructor - JavaScript
nce being created using the WebAssembly.Global() constructor. It is being defined as a mutable i32 type, with a value of 0. The value of the global is then changed, first to 42 using the Global.value property, and then to 43 using the incGlobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value). ...
WebAssembly.Global - JavaScript
nce being created using the WebAssembly.Global() constructor. It is being defined as a mutable i32 type, with a value of 0. The value of the global is then changed, first to 42 using the Global.value property, and then to 43 using the incGlobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value). ...
Logical OR assignment (||=) - JavaScript
ration would evaluate the right-hand side. In other words, x ||= y is equivalent to: x || (x = y); And not equivalent to the following which would always perform an assignment: x = x || y; Note that this behavior is different to mathematical and bitwise assignment operators. Examples Setting default content If the "lyrics" element is empty, set the innerHTML to a default value: document.
getElementById('lyrics').innerHTML ||= '<i>No lyrics.</i>' Here the short-circuit is especially beneficial, since the element will not be updated unnecessarily and won't cause unwanted side-effects such as additional parsing or rendering work, or loss of focus, etc. Note: Pay attention to the value returned by the API you're checking against. If an empty string is returned (a falsy value), ||= must be used, o...
for - JavaScript
point. var i = 0; for (;;) { if (i > 3) break; console.log(i); i++; } Using for without a statement The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead. ...
Progressive web app structure - Progressive web apps (PWAs)
var entry = template.replace(/POS/g,(i+1)) .replace(/SLUG/g,games[i].slug) .replace(/NAME/g,games[i].name) .replace(/AUTHOR/g,games[i].author) .replace(/TWITTER/g,games[i].twitter) .replace(/WEBSITE/g,games[i].website) .replace(/GITHUB/g,games[i].github); entry = entry.replace('<a href=\'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.requestPermissi...
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
a made of a circle and rectangle, assigns it the ID #clipping-path-1, then references it in the CSS. The clip path can be assigned to any element with the target class. You can make changes to the SVG in real time and see them immediately affect the rendering of the HTML. For example, you can resize the circle in the clip path established above: function toggleRadius() { var circle = document.
getElementById("circle"); circle.r.baseVal.value = 0.40 - circle.r.baseVal.value; } Example: Filtering This demonstrates applying a filter to HTML content using SVG. It establishes several filters, which are applied with CSS to three elements in both the normal and mouse hover states. <p class="target" style="background: lime;"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmo...
Scripting - SVG: Scalable Vector Graphics
document.embeds["name_of_svg"].getSVGDocument(); to get a reference to an embedded SVG document instead. The best way to get access to the Document representing an SVG document is to look at HTMLIFrameElement.contentDocument (if the document is presented in an <iframe>) or HTMLObjectElement.contentDocument (if the document is presented in an <object> element), like this: var svgDoc = document.
getElementById("iframe_element").contentDocument; In addition, the <iframe>, <embed>, and <object> elements offer a method, getSVGDocument(), which returns the XMLDocument representing the element's embedded SVG or null if the element doesn't represent an SVG document. You can also use document.
getElementById("svg_elem_name").getSVGDocument(), which gives the same result. You may find documentation referrin...
XPath snippets - XPath
> <address street="123 west st" city="seattle" state="wa" country="usa"/> <address street="321 south avenue" city="denver" state="co" country="usa"/> </person> </people> You can now "query" the document with XPath expressions. Although walking the DOM tree can achieve similar results, using XPath expressions is much quicker and more powerful. If you can rely on id attributes, document.
getElementById() is still powerful, but it's not nearly as powerful as XPath. Here are some examples. Example: JavaScript code with the custom evaluateXPath() utility function // display the last names of all people in the doc var results = evaluateXPath(people, "//person/@last-name"); for (var i in results) alert("Person #" + i + " has the last name " + results[i].value); // get the 2nd person node resul...
XPath
of addressing (pointing to) different parts of an XML document. It can also be used to test addressed nodes within a document to determine whether they match a pattern or not. XPath is mainly used in XSLT, but can also be used as a much more powerful way of navigating through the DOM of any XML-like language document using XPathExpression, such as HTML and SVG, instead of relying on the Document.
getElementById() or ParentNode.querySelectorAll() methods, the Node.childNodes properties, and other DOM Core features. XPath uses a path notation (as in URLs) for navigating through the hierarchical structure of an XML document. It uses a non-XML syntax so that it can be used in URIs and XML attribute values. Note: Support for XPath varies widely; it's supported reasonably well in Firefox (although there ar...