demo2s-5
Must Watch!
MustWatch
DOM Get Elements by Name
HTMLDocument getElementsByName() returns all elements that have a given name attribute.
The getElementsByName() method is most often used with radio buttons,
all of which must have the same name to
ensure the correct value gets sent to the server, as the following example shows:
<fieldset>
<legend>Which color do you prefer?</legend>
<ul>
<li>
<input type="radio" value="red" name="color" id="colorRed">
<label for="colorRed">Red</label>
</li>
<li>
<input type="radio" value="green" name="color" id="colorGreen">
<label for="colorGreen">Green</label>
</li>
<li>
<input type="radio" value="blue" name="color" id="colorBlue">
<label for="colorBlue">Blue</label>
</li>
</ul>
</fieldset>
In this code, the radio buttons all have a name attribute of "color" even though their IDs are
different.
The IDs allow the <label> elements to be applied to the radio buttons, and the name attribute
ensures that only one of the three values will be sent to the server.
These radio buttons can all then be retrieved using the following line of code:
let radios = document.getElementsByName("color");
The getElementsByName() method returns an HTMLCollection.
In this context, the namedItem() method always retrieves the first item since all
items have the same name.
DOM document querySelector() Method
The querySelector() method accepts a CSS query and returns the first descendant element that
matches the pattern or null if there is no matching element.
Here is an example.
Get the body element.
let body = document.querySelector("body");
Get the element with the ID myDiv.
let myDiv = document.querySelector("#myDiv");
Get first element with a class of "selected".
let selected = document.querySelector(".selected");
Get first image with class of "button".
let img = document.body.querySelector("img.button");
When the querySelector() method is used on the Document type, it starts trying to match the
pattern from the document element; when used on an Element type, the query attempts to make a match
from the descendants of the element only.
If there's a syntax error or an unsupported selector in the query, then querySelector() throws an error.
DOM document querySelectorAll() Method
The querySelectorAll() method accepts the
CSS query and returns all matching nodes.
This method returns a static instance of NodeList.
The return value is a NodeList with all of the expected properties and methods
as a snapshot of elements rather than a dynamic query.
This implementation eliminates most of the performance
overhead associated with the use of NodeList objects.
Any call to querySelectorAll() with a valid CSS query will return a NodeList object regardless of
the number of matching elements; if there are no matches, the NodeList is empty.
The querySelectorAll() method is available on the Document,
DocumentFragment, and Element types.
Here are some examples:
Get all <em> elements in a <div>, similar to getElementsByTagName("em").
let ems = document.getElementById("myDiv").querySelectorAll("em");
Get all elements that have "selected" as a class.
let selecteds = document.querySelectorAll(".selected");
Get all <strong> elements inside of <p> elements.
let strongs = document.querySelectorAll("p strong");
The resulting NodeList object may be iterated over using iteration, item(),
or bracket notation to retrieve individual elements.
Here's an example:
let strongElements = document.querySelectorAll("p strong");
All three of the following loops will have the same effect:
for (let strong of strongElements) {
strong.className = "important";
}
for (let i = 0; i < strongElements.length; ++i) {
strongElements.item(i).className = "important";
}
for (let i = 0; i < strongElements.length; ++i) {
strongElements [i].className = "important";
}
querySelectorAll() throws an error when the CSS selector is not
supported by the browser or if there's a syntax error in the selector.
DOM Document Get element by class name via getElementsByClassName() Method
HTML5 getElementsByClassName() is available on the document object and on all HTML elements.
The getElementsByClassName() method accepts a single argument,
which is a string containing one
or more class names, and returns a NodeList containing all elements that have all of the specified
classes applied.
If multiple class names are specified, then the order is considered unimportant.
Here are some examples.
Get all elements with a class containing "username" and "current"
It does not matter if one is declared before the other
let allCurrentUsernames = document.getElementsByClassName("username current");
Get all elements with a class of "selected" that exist in myDiv's subtree
.getElementById("myDiv")
.getElementsByClassName("selected");
When this method is called, it will return only elements in the subtree of the root from which it was
called.
Calling getElementsByClassName() on document always returns all elements with matching
class names, whereas calling it on an element will return only descendant elements.
This method is useful for attaching events to classes of elements rather than using IDs or tag names.
Since the returned value is a NodeList, there are the same performance issues
as when you're using getElementsByTagName() and other DOM methods that
return NodeList objects.
The getElementsByClassName() method is implemented in all
modern browsers.
DOM matches() Method
matches() method accepts a single argument, a CSS selector,
and returns true if the given element matches the selector or false if not.
For example:
if (document.body.matches ("body.page1")){
// true
}
This method checks if an element would be returned by querySelector() or
querySelectorAll() when you already have the element reference.
Edge, Chrome, Firefox, Safari, and Opera fully support it.
DOM Document Children Collections
The document object has several special collections.
Each of these collections is an HTMLCollection
object and provides faster access to common parts of the document, as described here:
Name | Description |
document.anchors | Contains all <a> elements with a name attribute in the document. |
document.applets | Contains all <applet> elements in the document. This collection is deprecated because the <applet> element is no longer recommended for use. |
document.forms | Contains all <form> elements in the document. The same as document.getElementsByTagName("form"). |
document.images | Contains all <img> elements in the document. The same as document.getElementsByTagName("img"). |
document.links | Contains all <a> elements with an href attribute in the document. |
These special collections are always available on HTMLDocument objects and,
like all HTMLCollection objects, are constantly updated to match the contents of the current document.
DOM Implementation Conformance Detection
Because there are multiple levels and multiple parts of the DOM,
it became necessary to determine exactly
what parts of the DOM a browser has implemented.
The document.implementation property is an
object containing information and functionality tied directly to the browser's implementation of the DOM.
DOM Level 1 specifies only one method on document.implementation, which is hasFeature().
The hasFeature() method accepts two arguments:
the name and
version of the DOM feature to check for.
If the browser supports the named feature and version, this method returns
true, as with this example:
let hasXmlDom = document.implementation.hasFeature("XML", "1.0");
The various values that can be tested are listed in the following table.
Feature | Supported Versions | Description |
Core | 1.0, 2.0, 3.0 | Basic DOM that spells out the use of a hierarchical tree to represent documents |
XML | 1.0, 2.0, 3.0 | XML extension of the Core that adds support for CDATA sections, processing instructions, and entities |
HTML | 1.0, 2.0 | HTML extension of XML that adds support for HTML-specific elements and entities |
Views | 2.0 | Accomplishes formatting of a document based on certain styles |
Style Sheets | 2.0 | Relates style sheets to documents |
CSS | 2.0 | Support for Cascading Style Sheets Level 1 |
CSS2 | 2.0 | Support for Cascading Style Sheets Level 2 |
Events | 2.0, 3.0 | Generic DOM events |
UI Events | 2.0, 3.0 | User interface events |
Text Events | 3.0 | Events fired from text input devices |
Mouse Events | 2.0, 3.0 | Events caused by the mouse (click, mouseover, and so on) |
Mutation Events | 2.0, 3.0 | Events fired when the DOM tree is changed |
Mutation Name Events | 3.0 | Events fired when DOM elements or element attributes are renamed |
HTML Events | 2.0 | HTML 4.01 events |
Range | 2.0 | Objects and methods for manipulating a range in a DOM tree |
Traversal | 2.0 | Methods for traversing a DOM tree |
LS | 3.0 | Loading and saving between files and DOM trees synchronously |
LS-Async | 3.0 | Loading and saving between files and DOM trees asynchronously |
Validation | 3.0 | Methods to modify a DOM tree and still make it valid |
XPath | 3.0 | Language for addressing parts of an XML document |
If hasFeature() returns true it does not mean that
the implementation conforms to all the specifications it claims to.
We should use capability detection in addition to hasFeature() before using specific parts of the DOM.
DOM Document Writing
The document object can write to the output stream of a web page via
four methods:
write(),
writeln(),
open(), and
close().
The write() and writeln() methods each accept a string argument to write to the output
stream.
write() simply adds the text as is.
writeln() appends a new-line character (\n) to
the end of the string.
These two methods can be used as a page is being loaded to dynamically add
content to the page, as shown in the following example:
document.write("<strong>" + (new Date()).toString() + "</strong>");
Open in separate window
View full source code
<head>
<title>document.write() Example</title>
</head>
<body>
<p>The current date and time is:
<script type="text/javascript">
document.write("<strong>" + (new Date()).toString() + "</strong>");
</script>
</p>
</body>
</html>
This example outputs the current date and time as the page is being loaded.
The date is enclosed by a
<strong> element, which is treated the same as if it were included in the HTML portion of the page,
meaning that a DOM element is created and can later be accessed.
Any HTML that is output via
write() or writeln() is treated this way.
The write() and writeln() methods are often used to dynamically include external resources such as
JavaScript files.
<html>
<head>
<title>document.write() Example</title>
</head>
<body>
<script type="text/javascript">
document.write("<script type=\"text/javascript\" src=\"file.js\">" +
"<\/script>");
</script>
</body>
</html>
The string "<\/script>" no longer registers as a closing tag for the outermost <script> tag, so
there is no extra content output to the page.
If document.write() is called after the page has been completely loaded,
the content overwrites the entire page, as shown in the following example:
window.onload = function(){
document.write("Hello world!");
};
Open in separate window
View full source code
<head>
<title>document.write() Example</title>
</head>
<body>
<p>This is some content that you won't get to see because it will be
overwritten.</p>
<script type="text/javascript">
window.onload = function(){
document.write("Hello world!");
};
</script>
</body>
</html>
In this example, the window.onload event handler is used to delay the execution of the function until
the page is completely loaded.
When that happens, the string "Hello world!" overwrites the entire
page content.
The open() and close() methods are used to open and close the web page output stream,
respectively.
Neither method is required to be used when write() or writeln() is used during the course
of page loading.
Note
Document writing is not supported in strict XHTML documents.
For pages that are served with the application/xml+xhtml content type, these
methods will not work.
DOM DocumentType Type
A DocumentType object contains all of the information about the document's doctype and has the
following characteristics:
Item | Value |
nodeType | 10 |
nodeName | the name of the doctype. |
nodeValue | null |
parentNode | a Document. |
Child nodes | not supported. |
DocumentType objects cannot be created dynamically in DOM Level 1; they are created only as the
document's code is being parsed.
For browsers that support it, the DocumentType object is stored in
document.doctype.
DOM Level 1 describes three properties for DocumentType objects:
Property | Meaning |
name entities notations | the name of the doctype a NamedNodeMap of entities described by the doctype; a NamedNodeMap of notations described by the doctype. |
Because documents
in browsers typically use an HTML or XHTML doctype, the entities and notations lists are
typically empty.
They are filled only with inline doc types.
This property is filled with the name of the doctype, which is the
text that appears immediately after <!DOCTYPE.
Consider the following HTML 4.01 strict doctype:
<!DOCTYPE HTML PUBLIC "-// W3C// DTD HTML 4.01// EN"
"http:// www.w3.org/TR/html4/strict.dtd">
For this doctype, the name property is "HTML":
console.log(document.doctype.name); // "HTML"
DOM DocumentFragment Type
Rhe DocumentFragment type has no representation in markup.
The DOM defines a document fragment as a "lightweight" document, capable of containing
and manipulating nodes without all of the additional overhead of a complete document.
DocumentFragment nodes have the following characteristics:
Item | Value |
nodeType | 11 |
nodeName | #document-fragment |
nodeValue | null |
parentNode | null |
Child nodes | may be Element, ProcessingInstruction, Comment, Text, CDATASection, or EntityReference. |
A document fragment cannot be added to a document directly.
It acts as a repository for other nodes that may need to be added to the document.
Document fragments are created using the document.createDocumentFragment() method,
shown here:
let fragment = document.createDocumentFragment();
Document fragments inherit all methods from Node and are used to perform
DOM manipulations that are to be applied to a document.
If a node from the document is added to a document
fragment, that node is removed from the document tree and won't be rendered by the browser.
New nodes that are added to a document fragment are also not part of the document tree.
The contents of a document fragment can be added to a document via
appendChild() or insertBefore().
When a document fragment is passed in as an argument to either of these methods,
all of the document fragment's child nodes are added in that spot;
the document fragment itself is never added to the document tree.
Example
For example, consider the following HTML:
<ul id="myList"></ul>
Suppose you would like to add three list items to this <ul> element.
Adding each item directly to the
element causes the browser to re-render the page with the new information.
To avoid this, the following code example uses a document fragment to create the list items
and then add them all at the same time:
let fragment = document.createDocumentFragment();
let ul = document.getElementById("myList");
for (let i = 0; i < 3; ++i) {
let li = document.createElement("li");
li.appendChild(document.createTextNode(`Item ${i + 1}`));
fragment.appendChild(li);
}
ul.appendChild(fragment);
This example begins by creating a document fragment and retrieving a reference to the <ul> element.
The for loop creates three list items, each with text indicating which item they are.
To do this, an <li> element is created and then a text node is created and added to that element.
The <li> element is then added to the document fragment using appendChild().
When the loop is complete, all
of the items are added to the <ul> element by calling appendChild() and passing in the document
fragment.
At that point, the document fragment's child nodes are all removed and placed onto the
<ul> element.
DOM Character Set Properties
The characterSet property indicates the actual character set being used by
the document and can also be used to specify a new character set.
By default, this value is "UTF-16".
Its value may be changed by
using <meta> elements or response headers or through setting the characterSet property directly.
Here's an example:
console.log(document.characterSet); // "UTF-16"
document.characterSet = "UTF-8";
DOM Compatibility Mode
The browser can render a document in either standards
or quirks mode, we can determine in which mode
the browser was rendering the page.
The property on the document named compatMode can indicate
what rendering mode the browser is in.
The compatMode property tells you how the browser has handled
the content in the document.
The compatMode property will return one of two values, as described
in the following table.
Value | Description |
CSS1Compat | The document conforms to a valid HTML specification. |
BackCompat | The document contains nonstandard features and has triggered the quirks mode. |
The following example shows how to use the compatMode.
When in standards mode,
document.compatMode is equal to CSS1Compat; when in quirks mode,
document.compatMode is BackCompat:
if (document.compatMode == "CSS1Compat"){
console.log("Standards mode");
} else {
console.log("Quirks mode");
}
The compatMode property was added to HTML5 to formalize its implementation.
DOM head Property
HTML5 introduces document.head to point to the <head> element of a document to complement
document.body, which points to the <body> element of the document.
You can retrieve a reference to the <head> element using this property:
let head = document.head;
DOM Document import node
The Document importNode() takes a node from a different document and import
it into a new document so
that it can be added into the document structure.
Every node has an ownerDocument property that indicates the document it belongs to.
If a method such as appendChild() is called and
a node with a different ownerDocument is passed in, an error will occur.
Calling importNode() on
a node from a different document returns a new version of the node that is owned by the
current document.
The importNode() method accepts two
arguments: the node to clone and a Boolean value indicating if the child nodes should also be copied.
The result is a duplicate of the node that is suitable for use in the document.
Here is an example:
// import node and all children
let newNode = document.importNode(oldNode, true);
document.body.appendChild(newNode);
This method is used more frequently with XML documents.
DOM HTMLDocument ready State Property
The document.readyState property gives you information about the current stage in the process of
loading and parsing the HTML document.
Remember that, by default, the browser executes your scripts
as soon as it encounters the script element in the document, but that script execution can be deferred
using the defer attribute.
It can be useful to know what stage the browser has got to in loading and
processing the HTML.
The readyState property on the document object is supported by all modern browsers.
This property was formalized in HTML5.
The readyState property for document has two possible values:
State | Meaning |
loading | The document is loading. |
complete | The document is completely loaded. |
interactive | The document has been parsed, but the browser is still loading linked resources (images, media files, and so on). |
The value of the readyState property moves from loading to interactive to complete as the browser
loads and processes the document.
This property is most useful in conjunction with the
readystatechange event, which is triggered each time the value of the readyState property changes.
The best way to use the document.readyState property is as an indicator that the document has loaded.
We can also add an onload event handler to
set a flag indicating that the document was loaded.
Basic usage:
if (document.readyState == "complete"){
// Do stuff
}
Example
Using the Document Ready State to Defer Script Execution.
<!DOCTYPE HTML>
<html>
<head>
<script>
document.onreadystatechange = function() {
if (document.readyState == "interactive") {
document.getElementById("pressme").onclick = function() {
document.getElementById("results").innerHTML =
"Button Pressed";
}
}
}
</script>
</head>
<body>
<button id="pressme">Press Me</button>
<pre id="results"></pre>
</body>
</html>
This script uses the document ready state to defer execution of a function until the document
reaches the interactive stage.
This script relies on being able to find elements in the document that
have not been loaded by the browser at the point where the script is being executed.
By deferring
execution until the document has been completely loaded, we can be sure that the elements will be found.
This is an alternative to putting the script element at the end of the document.
DOM Document scrollIntoView() Method
The browsers implemented several methods that control scrolling in different ways.
The scrollIntoView() method exists on all HTML elements and scrolls the browser
window or container element so the element is visible in the viewport.
If an argument of true is supplied, it specifies alignToTop
and the window scrolls so that the top of the element is at the top of the viewport.
If an argument of false is supplied, it specifies alignToTop and
the window scrolls so that the bottom of the element is at the top of the viewport.
If an object argument is supplied, the user can provide values
for the behavior property, which specifies how the scroll should occur:
auto, instant, or smooth (supported by Firefox), and
the block property is the same as alignToTop.
If no argument is supplied, the element is scrolled so that it is fully
visible in the viewport but may not be aligned at the top.
For example.
Ensures this element is visible.
document.forms[0].scrollIntoView();
These behave identically.
document.forms[0].scrollIntoView(true);
document.forms[0].scrollIntoView({block: true});
This attempts to scroll the element smoothly into view:
document.forms[0].scrollIntoView({behavior: 'smooth', block: true});
Note that setting focus to an element also causes the browser to scroll the element into view so that
the focus can properly be displayed.
DOM Document namespace method
The Document type includes the following namespace-specific methods:
Method | Meaning |
createElementNS(namespaceURI, tagName) | Creates a new element with the given tagName as part of the namespace indicated by namespaceURI. |
createAttributeNS(namespaceURI, attributeName) | Creates a new attribute node as part of the namespace indicated by namespaceURI. |
getElementsByTagNameNS(namespaceURI, tagName) | Returns a NodeList of elements with the given tagName that are also a part of the namespace indicated by namespaceURI. |
These methods are used by passing in the namespace URI of the namespace,
as shown in the following example.
create a new SVG element.
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
create new attribute for a random namespace.
let att = document.createAttributeNS("http://www.demo2s.com", "demo");
get all XHTML elements.
let elems = document.getElementsByTagNameNS(
"http://www.w3.org/1999/xhtml", "*");
The namespace-specific methods are necessary only when there are two or more namespaces in a
given document.
DOM DocumentType namespace properties
The DocumentType type adds three new properties: publicId, systemId, and internalSubset.
The publicId and systemId properties represent data that is readily available in a doctype but
were inaccessible using DOM Level 1.
Consider the following HTML doctype:
<!DOCTYPE HTML PUBLIC "-// W3C// DTD HTML 4.01// EN"
"http://www.w3.org/TR/html4/strict.dtd">
In this doctype, the publicId is "-// W3C// DTD HTML 4.01// EN" and the systemId is
http://www.w3.org/TR/html4/strict.dtd.
Browsers that support DOM Level 2 should be able to run the following JavaScript code:
console.log(document.doctype.publicId);
console.log(document.doctype.systemId);
The internalSubset property accesses any additional definitions that are included in the doctype, as
shown in the following example:
<!DOCTYPE html PUBLIC "-// W3C// DTD XHTML 1.0 Strict// EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
[<!ELEMENT name (#PCDATA)>] >
For this code, document.doctype.internalSubset returns
"<!ELEMENT name (#PCDATA)>".
Internal subsets are rarely used in HTML and are slightly more common in XML.
Working with DOM Element Objects
HTMLElement objects provide a set of properties that you can use to read and modify data about the
element that is being represented.
The following table describes these properties.
Property | Description | Returns |
checked | Gets or sets the presence of the checked attribute | boolean |
classList | Gets or sets the list of classes to which the element belongs | DOMTokenList |
className | Gets or sets the list of classes to which the element belongs | string |
dir | Gets or sets the value of the dir attribute | string |
disabled | Gets or sets the presence of the disabled attribute | boolean |
hidden | Gets or sets the presence of the hidden attribute | boolean |
id | Gets or sets the value of the id attribute | string |
lang | Gets or sets the value of the lang attribute | string |
spellcheck | Gets or sets the presence of the spellcheck attribute | boolean |
tabIndex | Gets or sets the value of the tabindex attribute | number |
tagName | Returns the tag name (indicating the element type) | string |
title | Gets or sets the value of the title attribute | string |
The following code shows the use of some of the basic data properties listed in the table.
let results = document.getElementById("results");
let elem = document.getElementById("textblock");
results.innerHTML += "tag: " + elem.tagName + "\n";
results.innerHTML += "id: " + elem.id + "\n";
results.innerHTML += "dir: " + elem.dir + "\n";
results.innerHTML += "lang: " + elem.lang + "\n";
results.innerHTML += "hidden: " + elem.hidden + "\n";
results.innerHTML += "disabled: " + elem.disabled + "\n";
Open in separate window
View full source code
<html>
<head>
<style>
p {border: medium double black;}
</style>
</head>
<body>
<p id="textblock" dir="ltr" lang="en-US">
test<!-- w w w . d e m o 2s . c o m-->
<span id="banana">banana</span>
test<span id="apple">LEGO</span>,
<span="orange">Star War</span>
test
</p>
<pre id="results"></pre>
<script>
let results = document.getElementById("results");
let elem = document.getElementById("textblock");
results.innerHTML += "tag: " + elem.tagName + "\n";
results.innerHTML += "id: " + elem.id + "\n";
results.innerHTML += "dir: " + elem.dir + "\n";
results.innerHTML += "lang: " + elem.lang + "\n";
results.innerHTML += "hidden: " + elem.hidden + "\n";
results.innerHTML += "disabled: " + elem.disabled + "\n";
</script>
</body>
</html>
Working with Classes via DOM HTMLElement
You can deal with the classes that an element belongs to in two ways.
The first is to use the className property, which returns a list of the classes.
You add or remove classes by changing the value of the string.
You can see both reading and modifying the classes in the following code.
A common use for classes is to target elements with styles.
Using the className Property.
document.getElementById("pressme").onclick = function(e) {
document.getElementById("textblock").className += " newclass";
};
Open in separate window
View full source code
<html>
<head>
<style>
p {<!-- w w w .d e m o 2 s . c o m-->
border: medium double black;
}
p.newclass {
background-color: grey;
color: white;
}
</style>
</head>
<body>
<p id="textblock" class="yourdata numbers">
This is a test.
</p>
<button id="pressme">Press Me</button>
<script>
document.getElementById("pressme").onclick = function(e) {
document.getElementById("textblock").className += " newclass";
};
</script>
</body>
</html>
In this example, clicking the button triggers the script, which appends a new class to the list for the
element.
Notice that we need to add a leading space to the value we appended to the className property
value.
This is because the browser expects a list of classes, each separated by a space.
The browser will
apply styles whose selectors are class-based when we make a change like this.
Working with Class List via DOM HTMLElement
The className property is easy to use when you want to quickly add classes to an element, but it
becomes hard work if you want to do anything else, such as removing a class.
Fortunately, you can use
the classList property, which returns a DOMTokenList object.
This object defines some useful methods and properties that allow you to manage
the class list, as described in the following table.
Member | Description | Returns |
add(<class>) | Adds the specified class to the element | void |
contains(<class>) | Returns true if the element belongs to the specified class | boolean |
length | Returns the number of classes to which the element belongs | number |
remove(<class>) | Removes the specified class from the element | boid |
toggle(<class>) | Adds the class if it is not present and removes it if it is present | boolean |
In addition to these properties and methods, you can also retrieve classes by index,
using array-style notation.
The use of the DOMTokenList object is shown in the following code.
Using the classList Property.
let results = document.getElementById("results");
document.getElementById("toggle").onclick = toggleClass;
listClasses();
function listClasses() {
let classlist = document.getElementById("textblock").classList;
results.innerHTML = "Current classes: "
for (let i = 0; i < classlist.length; i++) {
results.innerHTML += classlist[i] + " ";
}
}
function toggleClass() {
document.getElementById("textblock").classList.toggle("newclass");
listClasses();
}
Open in separate window
View full source code
<html>
<head>
<style>
p {<!-- w w w .d e m o 2 s . c o m -->
border: medium double black;
}
p.newclass {
background-color: grey;
color: white;
}
</style>
</head>
<body>
<p id="textblock" class="yourdata numbers">
This is a test.
</p>
<pre id="results"></pre>
<button id="toggle">Toggle Class</button>
<script>
let results = document.getElementById("results");
document.getElementById("toggle").onclick = toggleClass;
listClasses();
function listClasses() {
let classlist = document.getElementById("textblock").classList;
results.innerHTML = "Current classes: "
for (let i = 0; i < classlist.length; i++) {
results.innerHTML += classlist[i] + " ";
}
}
function toggleClass() {
document.getElementById("textblock")
.classList.toggle("newclass");
listClasses();
}
</script>
</body>
</html>
In this example, the listClasses() function uses the classList property to obtain and enumerate the
classes that the <p> element belongs to, using the array-style indexer to retrieve class names.
The toggleClass() function, which is invoked when the button is clicked, uses the toggle() method to
add and remove a class called newclass.
DOM Working with Element Attributes vis HTMLElement
There are properties for some of the most important global attributes,
but there is also support for reading and setting any attribute on an element.
The following table describes the available methods and
properties defined by the HTMLElement object for this purpose.
Member | Description | Returns |
attributes | Returns the attributes applied to the element | Attr[] |
dataset | Returns the data-* attributes | string[<name>] |
getAttribute(<name>) | Returns the value of the specified attribute | string |
hasAttribute(<name>) | Returns true if the element has the specified attribute | boolean |
removeAttribute(<name>) | Removes the specified attribute from the element | void |
setAttribute(<name>, <value>) | Applies an attribute with the specified name and value | void |
The four methods for working with attributes are easy to use and behave just as you might expect.
Using the Attribute Methods.
let results = document.getElementById("results");
let elem = document.getElementById("textblock");
results.innerHTML = "Element has lang attribute: "
+ elem.hasAttribute("lang") + "\n";
results.innerHTML += "Adding lang attribute\n";
elem.setAttribute("lang", "en-US");
results.innerHTML += "Attr value is : " + elem.getAttribute("lang") + "\n";
results.innerHTML += "Set new value for lang attribute\n";
elem.setAttribute("lang", "en-UK");
results.innerHTML += "Value is now: " + elem.getAttribute("lang") + "\n";
Open in separate window
View full source code
<html>
<head>
<style>
p {border: medium double black;}
</style>
</head>
<body>
<p id="textblock" class="yourdata numbers">
This is a test.
</p>
<pre id="results"></pre>
<script>
let results = document.getElementById("results");
let elem = document.getElementById("textblock");
results.innerHTML = "Element has lang attribute: "
+ elem.hasAttribute("lang") + "\n";
results.innerHTML += "Adding lang attribute\n";
elem.setAttribute("lang", "en-US");
results.innerHTML +=<!-- w w w . d em o 2 s . c o m-->
"Attr value is : " + elem.getAttribute("lang") + "\n";
results.innerHTML += "Set new value for lang attribute\n";
elem.setAttribute("lang", "en-UK");
results.innerHTML +=
"Value is now: " + elem.getAttribute("lang") + "\n";
</script>
</body>
</html>
In this example, we check for, add, and change the value of the lang attribute.
DOM Work with the data-* Attributes
HTML5 supports custom attributes that are prefixed with data-, such as
data-mycustomattribute.
You can work with these custom attributes in the DOM via the dataset
property, which returns an array of values, indexed by the custom part of the name.
Using the dataset Property.
let results = document.getElementById("results");
let elem = document.getElementById("textblock");
for (let attr in elem.dataset) {
results.innerHTML += attr + "\n";
}
results.innerHTML += "Value of data-yourdata attr: " +
elem.dataset["yourdata"];
Open in separate window
View full source code
<html>
<head>
<style>
p {border: medium double black;}
</style>
</head>
<body>
<p id="textblock" class="yourdata numbers"
data-yourdata="apple" data-sentiment="like">
This is a test.
</p>
<pre id="results"></pre>
<script>
let results = document.getElementById("results");
let elem = document.getElementById("textblock");
for (let attr in elem.dataset) {
results.innerHTML += attr + "\n";
}<!-- w w w . d e m o 2 s . c o m -->
results.innerHTML += "Value of data-yourdata attr: " +
elem.dataset["yourdata"];
</script>
</body>
</html>
The array of values that the dataset property returns isn't indexed
by position as in regular arrays.
If you want to enumerate the data-* attributes, you can do so using a for...in
statement.
Alternatively, you can request a value by name.
Note that you need to provide only the custom part of the attribute name.
For example, if you want the value of the data-yourData attribute, you request
the value dataset["yourData"].
DOM Work with All Attributes as Collection and Attr
You can obtain a collection containing all of the attributes for an element through the attributes
property, which returns an array of Attr objects.
The properties of the Attr object are described in the following table.
Properties | Description | Returns |
name | Returns the name of the attribute | string |
value | Gets or sets the value of the attribute | string |
The following code shows how to use the attributes property and the Attr object to read and modify an
element's attributes.
Working with the attributes Property.
let results = document.getElementById("results");
let elem = document.getElementById("textblock");
let attrs = elem.attributes;
for (let i = 0; i < attrs.length; i++) {
results.innerHTML += "Name: " + attrs[i].name + " Value: "
+ attrs[i].value + "\n";
}
attrs["data-yourdata"].value = "banana";
results.innerHTML += "Value of data-yourdata attr: "
+ attrs["data-yourdata"].value;
Open in separate window
View full source code
<html>
<head>
<style>
p {border: medium double black;}
</style>
</head>
<body>
<p id="textblock"
class="yourdata numbers"
data-yourdata="apple"
data-sentiment="like">
This is a test.
</p>
<pre id="results"></pre>
<script>
let results = document.getElementById("results");
let elem = document.getElementById("textblock");
let attrs = elem.attributes;
for (let i = 0; i < attrs.length; i++) {
results.innerHTML += "Name: " + attrs[i].name + " Value: "
+ attrs[i].value + "\n";
}<!-- w w w . d e m o 2 s . c o m -->
attrs["data-yourdata"].value = "banana";
results.innerHTML += "Value of data-yourdata attr: "
+ attrs["data-yourdata"].value;
</script>
</body>
</html>
As you can see from the listing, the attributes in the array of Attr objects are indexed by position and
name.
In this example, we enumerate the names and values of the attributes applied to an element, and
then modify the value of one of them.
DOM Working with Text inside HTMLElement
The text content of an element is represented by a Text object, which is presented
as a child of the element in the document model.
The following code shows an element with some text content.
...
<p>
test
</p>
...
When the browser represents the <p> element in the document model, there will be
an HTMLElement object for the element itself and a Text object for the content.
P element
|
+--text
If an element has children and they contain text, each will be handled in the same way.
The following code adds an element to the paragraph.
Adding an Element to the Paragraph.
...
<p>
test<b>500</b> test
</p>
...
The addition of the <b> element changes the hierarchy of nodes used to represent
the <p> element and its contents.
P
|
+--text
|
+--b
| |
| +-text
|
+--text
The first child of the <p> element is a <Text> object that represents the text from the start of the block to
the <b> element.
Then there is the <b> element, which has its own child Text object representing the text
contained between the start and end tags.
Finally, the last child of the <p> element is a Text object
representing the text that follows the b element through to the end of the block.
The following table describes the members supported by the Text object.
The following code shows some of the Text element methods and properties in use.
Dealing with Text.
let results = document.getElementById("results");
let elem = document.getElementById("textblock");
document.getElementById("pressme").onclick = function() {
let textElem = elem.firstChild;
results.innerHTML = "The element has " +
textElem.length + " chars\n";
};
Open in separate window
View full source code
<html>
<head>
<style>
p {border: medium double black;}
</style>
</head>
<body>
<p>
test <b>500</b>
test<!-- w w w . d e m o 2 s . c om -->
</p>
<button id="pressme">Press Me</button>
<pre id="results"></pre>
<script>
let results = document.getElementById("results");
let elem = document.getElementById("textblock");
document.getElementById("pressme").onclick = function() {
let textElem = elem.firstChild;
results.innerHTML = "The element has " +
textElem.length + " chars\n";
};
</script>
</body>
</html>
An important point to note when working with text is that whitespace is not collapsed.
This means that
any spaces or other whitespace characters that have been used to add structure to the HTML are counted as part
of the text.
DOM Modifying the Element Model
You can add, remove, duplicate, and copy elements.
The following table describes the properties and methods
that are available for altering the DOM hierarchy.
Member | Description | Returns |
appendChild(HTMLElement) | Appends the specified element as a child of the current element | HTMLElement |
cloneNode(boolean) | Copies an element | HTMLElement |
compareDocumentPosition(HTMLElement) | Determines the relative position of an element | number |
innerHTML | Gets or sets the element's contents | string |
insertAdjacentHTML(<pos>, <text>) | Inserts HTML relative to the element | void |
insertBefore(<new_Element>, <child_Element>) | Inserts the first element before the second (child) element | HTMLElement |
isEqualNode(<HTMLElement>) | Determines if the specified element is equal to the current element | boolean |
isSameNode(HTMLElement) | Determines if the specified element is the same as the current element | boolean |
outerHTML | Gets or sets an element's HTML and contents | string |
removeChild(HTMLElement) | Removes the specified child of the current element | HTMLElement |
replaceChild(HTMLElement, HTMLElement) | Replaces a child of the current element | HTMLElement |
These properties and methods are available on all element objects.
In addition, the document object defines two methods that allow you to create new elements.
This is essential when you want to add content to your document.
These creation methods are described in the following table.
Member | Description | Returns |
createElement(<tag>) | Creates a new HTMLElement object with the specific tag type | HTMLElement |
createTextNode(<text>) | Creates a new Text object with the specified content | Text |
You create new elements through the document object, and then insert them by finding an existing
HTMLElement and using one of the methods described previously.
Creating and Deleting Elements.
let tableBody = document.getElementById("fruitsBody");
document.getElementById("add").onclick = function() {
let row = tableBody.appendChild(document.createElement("tr"));
row.setAttribute("id", "newrow");
row.appendChild(document.createElement("td"))
.appendChild(document.createTextNode("new Data"));
row.appendChild(document.createElement("td"))
.appendChild(document.createTextNode("My Data"));
};
document.getElementById("remove").onclick = function() {
let row = document.getElementById("newrow");
row.parentNode.removeChild(row);
}
Open in separate window
View full source code
<html>
<head>
<style>
table{
border: solid thin black;
border-collapse: collapse;
margin: 10px;
}<!-- w w w . d em o 2 s .c o m-->
td { padding: 4px 5px; }
</style>
</head>
<body>
<table border="1">
<thead><th>Name</th><th>Color</th></thead>
<tbody id="fruitsBody">
<tr><td>Banana</td><td>Yellow</td></tr>
<tr><td>Apple</td><td>Red/Green</td></tr>
</tbody>
</table>
<button id="add">Add Element</button>
<button id="remove">Remove Element</button>
<script>
let tableBody = document.getElementById("fruitsBody");
document.getElementById("add").onclick = function() {
let row = tableBody.appendChild(document.createElement("tr"));
row.setAttribute("id", "newrow");
row.appendChild(document.createElement("td"))
.appendChild(document.createTextNode("new Data"));
row.appendChild(document.createElement("td"))
.appendChild(document.createTextNode("My Data"));
};
document.getElementById("remove").onclick = function() {
let row = document.getElementById("newrow");
row.parentNode.removeChild(row);
}
</script>
</body>
</html>
The script in this example uses the DOM to add and remove rows from an HTML table.
When adding the row, we start by creating a tr element, and then use it as the
parent for the td and Text objects.
You need to create the element,
associate it with its parent, and repeat the process for any child elements or text content.
To remove elements, you must find the element, navigate to the parent element, and then use the removeChild method.
DOM Duplicating Elements
You can use the cloneNode() method to duplicate existing elements.
This can be a convenient way to avoid
the process of creating the elements you want from scratch.
Duplicating Elements.
let tableBody = document.getElementById("fruitsBody");
document.getElementById("add").onclick = function() {
let count = tableBody.getElementsByTagName("tr").length + 1;
let newElem = tableBody.getElementsByTagName("tr")[0].cloneNode(true);
newElem.getElementsByClassName("sum")[0].firstChild.data = count
+ " + " + count;
newElem.getElementsByClassName("result")[0].firstChild.data =
count * count;
tableBody.appendChild(newElem);
};
Open in separate window
View full source code
<html>
<head>
<style>
table{
border: solid thin black;
border-collapse: collapse;
margin: 10px;
}<!-- w ww . d e mo 2 s . c o m-->
td { padding: 4px 5px; }
</style>
</head>
<body>
<table border="1">
<thead><tr><th>Multiply</th><th>Result</th></tr></thead>
<tbody id="fruitsBody">
<tr><td class="sum">1 x 1</td><td class="result">1</td></tr>
</tbody>
</table>
<button id="add">Add Row</button>
<script>
let tableBody = document.getElementById("fruitsBody");
document.getElementById("add").onclick = function() {
let count = tableBody.getElementsByTagName("tr").length + 1;
let newElem = tableBody
.getElementsByTagName("tr")[0].cloneNode(true);
newElem.getElementsByClassName("sum")[0].firstChild.data =
count
+ " + " + count;
newElem.getElementsByClassName("result")[0].firstChild.data =
count * count;
tableBody.appendChild(newElem);
};
</script>
</body>
</html>
In this example, we duplicate an existing row in a table to create more rows.
The Boolean argument to
the cloneNode() method specifies whether the child elements of the element should be duplicated as well.
In this case, we have specified true, because we want the td elements that are contained in the tr element to
form the structure of my new row.
DOM Moving Elements
When moving elements from one part of the document to another, you simply need to associate the
element you want to move with its new parent.
You don't need to dislocate the element from its starting position.
The following code provides a demonstration by moving a row from one table to another.
Moving Elements.
document.getElementById("move").onclick = function() {
let elem = document.getElementById("apple");
document.getElementById("fruitsBody").appendChild(elem);
};
Open in separate window
View full source code
<html>
<head>
<style>
table {
border: solid thin black;
border-collapse: collapse;
margin: 10px;
float: left;
}<!-- w w w .d e m o 2 s . c o m -->
td { padding: 4px 5px; }
p { clear:left; }
</style>
</head>
<body>
<table border="1">
<thead><tr><th>Fruit</th><th>Color</th></tr></thead>
<tbody>
<tr><td>Banana</td><td>Yellow</td></tr>
<tr id="apple"><td>Apple</td><td>Red/Green</td></tr>
</tbody>
</table>
<table border="1">
<thead><tr><th>Fruit</th><th>Color</th></tr></thead>
<tbody id="fruitsBody">
<tr><td>Plum</td><td>Purple</td></tr>
</tbody>
</table>
<p>
<button id="move">Move Row</button>
</p>
<script>
document.getElementById("move").onclick = function() {
let elem = document.getElementById("apple");
document.getElementById("fruitsBody").appendChild(elem);
};
</script>
</body>
</html>
When the <button> element is pressed, the script moves the <tr> element with the id of apple and calls
the appendChild() element on the <tbody> element with the id of fruitsBody.
This has the effect of moving the row from one table to another.
DOM Comparing Element Objects
You can compare element objects in two ways.
The first is simply to see if they represent the same
element, which you can do using the isSameNode() method.
This allows you to compare objects that you
have obtained from different queries, as shown in the following code.
Comparing Element Objects.
let elemByID = document.getElementById("plumrow");
let elemByPos
= document.getElementById("fruitsBody").getElementsByTagName("tr")[0];
if (elemByID.isSameNode(elemByPos)) {
document.getElementById("results").innerHTML = "Objects are the same";
}
Open in separate window
View full source code
<html>
<head>
<style>
table {
border: solid thin black;
border-collapse: collapse;
}<!-- w w w . d e m o 2 s. c o m -->
td { padding: 4px 5px; }
</style>
</head>
<body>
<table border="1">
<thead><tr><th>Fruit</th><th>Color</th></tr></thead>
<tbody id="fruitsBody">
<tr id="plumrow"><td>Plum</td><td>Purple</td></tr>
</tbody>
</table>
<pre id="results"></pre>
<script>
let elemByID = document.getElementById("plumrow");
let elemByPos
= document.getElementById("fruitsBody")
.getElementsByTagName("tr")[0];
if (elemByID.isSameNode(elemByPos)) {
document.getElementById("results")
.innerHTML = "Objects are the same";
}
</script>
</body>
</html>
The script in this example locates element objects using two different techniques: by searching for a
specific id and by searching by tag type from the parent element.
The isSameNode() method returns true
when these objects are compared because they represent the same element.
The alternative is to test to see if element objects are equal , which you can do by using the
isEqualNode() method.
Elements are equal if they are of the same type, have the same attribute values, and
each of their children is also equal and in the same order.
Working with Equal Elements.
let elems = document.getElementsByClassName("plumrow");
if (elems[0].isEqualNode(elems[1])) {
document.getElementById("results").innerHTML = "Elements are equal";
} else {
document.getElementById("results").innerHTML = "Elements are NOT equal";
}
Open in separate window
View full source code
<html>
<head>
<style>
table {
border: solid thin black;
border-collapse: collapse;
margin: 2px 0px;
}<!-- w w w .d e m o2 s . c o m -->
td { padding: 4px 5px; }
</style>
</head>
<body>
<table border="1">
<thead><tr><th>Fruit</th><th>Color</th></tr></thead>
<tbody>
<tr class="plumrow"><td>Plum</td><td>Purple</td></tr>
</tbody>
</table>
<table border="1">
<thead><tr><th>Fruit</th><th>Color</th></tr></thead>
<tbody>
<tr class="plumrow"><td>Plum</td><td>Purple</td></tr>
</tbody>
</table>
<pre id="results"></pre>
<script>
let elems = document.getElementsByClassName("plumrow");
if (elems[0].isEqualNode(elems[1])) {
document.getElementById("results").innerHTML =
"Elements are equal";
} else {
document.getElementById("results").innerHTML =
"Elements are NOT equal";
}
</script>
</body>
</html>
In this example, the two <tr> elements are equal, even though they are distinct elements in different
parts of the document.
If we changed any of the attributes or the content of the child td element, then the
elements would no longer be equal.
DOM Work with HTML Fragments via inner html and outer html
The innerHTML and outerHTML properties and the insertAdjacentHTML()
method are convenient syntax
shortcuts that allow you to work with fragments of HTML, thus avoiding the need to create elaborate
hierarchies of element and text objects.
The following code demonstrates using the innerHTML and outerHTML
properties to get the HTML from elements.
Using the innerHTML and outerHTML Properties.
let results = document.getElementById("results");
let row = document.getElementById("applerow");
document.getElementById("inner").onclick = function() {
results.innerHTML = row.innerHTML;
};
document.getElementById("outer").onclick = function() {
results.innerHTML = row.outerHTML;
}
Open in separate window
View full source code
<html>
<head>
<style>
table {
border: solid thin black;
border-collapse: collapse;
margin: 5px 2px;
float: left;
}<!-- w w w . d e m o 2 s . c o m -->
td { padding: 4px 5px; }
p {clear: left};
</style>
</head>
<body>
<table border="1">
<thead><tr><th>Fruit</th><th>Color</th></tr></thead>
<tbody>
<tr id="applerow"><td>Plum</td><td>Purple</td></tr>
</tbody>
</table>
<textarea rows="3" id="results"></textarea>
<p>
<button id="inner">Inner HTML</button>
<button id="outer">Outer HTML</button>
</p>
<script>
let results = document.getElementById("results");
let row = document.getElementById("applerow");
document.getElementById("inner").onclick = function() {
results.innerHTML = row.innerHTML;
};
document.getElementById("outer").onclick = function() {
results.innerHTML = row.outerHTML;
}
</script>
</body>
</html>
The outerHTML property returns a string containing the HTML defining the element and the HTML
of all of its children.
The innerHTML property returns just the HTML of the children.
In this example, we defined a pair of buttons that display the inner and outer HTML for a table row.
We displayed the content
in a textarea element, so that the browser treats the strings returned by these properties as text and not
HTML.
Changing the Document Structure
You can use the outerHTML and innerHTML properties to change the structure of the document as well.
We can use them to set text content without needing to create Text elements.
Modifying the Document Model.
document.getElementById("move").onclick = function() {
let source = document.getElementById("apple");
let target = document.getElementById("targetrow");
target.innerHTML = source.innerHTML;
source.outerHTML = '<tr id="targetrow"><td colspan="2">' +
'This is the placeholder</td>';
};
Open in separate window
View full source code
<html>
<head>
<style>
table {
border: solid thin black;
border-collapse: collapse;
margin: 10px;
float: left;
}<!-- w w w . d e m o 2 s . c o m-->
td { padding: 4px 5px; }
p { clear:left; }
</style>
</head>
<body>
<table border="1">
<thead><tr><th>Fruit</th><th>Color</th></tr></thead>
<tbody>
<tr><td>Banana</td><td>Yellow</td></tr>
<tr id="apple"><td>Apple</td><td>Red/Green</td></tr>
</tbody>
</table>
<table border="1">
<thead><tr><th>Fruit</th><th>Color</th></tr></thead>
<tbody id="fruitsBody">
<tr><td>Plum</td><td>Purple</td></tr>
<tr id="targetrow"><td colspan="2">
This is the placeholder</td></tr>
</tbody>
</table>
<p>
<button id="move">Move Row</button>
</p>
<script>
document.getElementById("move").onclick = function() {
let source = document.getElementById("apple");
let target = document.getElementById("targetrow");
target.innerHTML = source.innerHTML;
source.outerHTML = '<tr id="targetrow"><td colspan="2">' +
'This is the placeholder</td>';
};
</script>
</body>
</html>
In this example, we used the innerHTML property to set the child elements of a table row and the
outerHTML to replace an element inline.
These properties work on strings, meaning that you can obtain
HTML fragments by reading the property values or by creating strings from scratch.
DOM Inserting HTML Fragments
The innerHTML and outerHTML properties are useful for replacing existing elements, but if you want to use
an HTML fragment to insert new elements, you must use the insertAdjacentHTML method.
This method takes two arguments.
The first is a value from the following table indicating where the fragment should be
inserted relative to the current element, and the second is the fragment to insert.
Position Parameter Values for the insertAdjacentHTML() Method.
Value | Description |
afterbegin | Inserts the fragment as the first child of the current element |
afterend | Inserts the fragment immediately before the current element |
beforebegin | Inserts the fragment immediately before the current element |
beforeend | Inserts the fragment as the last child of the current element |
The following code shows the use of the insertAdjacentHTML() method to insert fragments of HTML in and
around a table row element.
let target = document.getElementById("targetrow");
let buttons = document.getElementsByTagName("button");
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e) {
if (e.target.id == "ab") {
target.insertAdjacentHTML("afterbegin", "<td>After Begin</td>");
} else if (e.target.id == "be") {
target.insertAdjacentHTML("beforeend", "<td>Before End</td>");
} else if (e.target.id == "bb") {
target.insertAdjacentHTML("beforebegin",
"<tr><td colspan='2'>Before Begin</td></tr>");
} else {
target.insertAdjacentHTML("afterend",
"<tr><td colspan='2'>After End</td></tr>");
}
}
Open in separate window
View full source code
<html>
<body>
<table border="1">
<thead><tr><th>Fruit</th><th>Color</th></tr></thead>
<tbody id="fruitsBody">
<tr id="targetrow"><td>Placeholder</td></tr>
</tbody>
</table>
<p>
<button id="ab">After Begin</button>
<button id="ae">After End</button>
<button id="bb">Before Begin</button>
<button id="be">Before End</button>
</p>
<script>
let target = document.getElementById("targetrow");
let buttons = document.getElementsByTagName("button");
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = handleButtonPress;
}<!-- w w w . d e m o2 s. c o m -->
function handleButtonPress(e) {
if (e.target.id == "ab") {
target.insertAdjacentHTML("afterbegin",
"<td>After Begin</td>");
} else if (e.target.id == "be") {
target.insertAdjacentHTML("beforeend",
"<td>Before End</td>");
} else if (e.target.id == "bb") {
target.insertAdjacentHTML("beforebegin",
"<tr><td colspan='2'>Before Begin</td></tr>");
} else {
target.insertAdjacentHTML("afterend",
"<tr><td colspan='2'>After End</td></tr>");
}
}
</script>
</body>
</html>
In this example, we use the different position values to demonstrate how to insert HTML fragments in
different locations.
DOM Inserting an Element into a Text Block
An important variation on modifying the model is to add an element to a text block, represented by a
Text object.
Inserting an Element into a Text Block.
document.getElementById("insert").onclick = function() {
let textBlock = document.getElementById("textblock");
textBlock.firstChild.splitText(10);
let newText = textBlock.childNodes[1].splitText(4).previousSibling;
textBlock.insertBefore(document.createElement("b"),
newText).appendChild(newText);
}
Open in separate window
View full source code
<html>
<body>
<p id="textblock">
test. test. test. test. test.
</p>
<p>
<button id="insert">Insert Element</button>
</p>
<script>
document.getElementById("insert").onclick = function() {
let textBlock = document.getElementById("textblock");
textBlock.firstChild.splitText(10);
let newText = textBlock.childNodes[1]
.splitText(4).previousSibling;
textBlock.insertBefore(document.createElement("b"),
newText).appendChild(newText);
}<!-- ww w . d e m o 2 s. co m -->
</script>
</body>
</html>
In this example, we take a word from the existing text and
making it a child of a new <b> element.
DOM Working with Stylesheets
You access the CSS stylesheets available in your document using the document.styleSheets property,
which returns a collection of objects representing the stylesheets associated with the document.
The returned type is CSSStyleSheet[].
Each stylesheet is represented by a CSSStyleSheet object, which provides the set of properties and
methods for manipulating the styles in the document.
The following table summarizes the CSSStyleSheet members.
Member | Description | Returns |
cssRules | Returns the set of rules in the stylesheet. | CSSRuleList |
deleteRule(<pos>) | Removes a rule from the stylesheet. | void |
disabled | Gets or sets the disabled state of the stylesheet. | boolean |
href | Returns the href for linked stylesheets. | string |
insertRule(<rule>, <pos>) | Inserts a new rule into the stylesheet. | number |
media | Returns the set of media constraints applied to the stylesheet. | MediaList |
ownerNode | Returns the element in which the style is defined. | HTMLElement |
title | Returns the value of the title attribute. | string |
type | Returns the value of the type attribute. | string |
Getting Basic Information About Stylesheets
We can get some basic information about the stylesheets defined in the document.
Getting Basic Information About the Stylesheets in a Document.
let placeholder = document.getElementById("placeholder");
let sheets = document.styleSheets;
for (let i = 0; i < sheets.length; i++) {
let newElem = document.createElement("table");
newElem.setAttribute("border", "1");
addRow(newElem, "Index", i);
addRow(newElem, "href", sheets[i].href);
addRow(newElem, "title", sheets[i].title);
addRow(newElem, "type", sheets[i].type);
addRow(newElem, "ownerNode", sheets[i].ownerNode.tagName);
placeholder.appendChild(newElem);
}
function addRow(elem, header, value) {
elem.innerHTML += "<tr><td>" + header + ":</td><td>"
+ value + "</td></tr>";
}
Open in separate window
View full source code
<html>
<head>
<style title="core styles">
p {<!-- w ww . d e m o 2 s. c o m -->
border: medium double black;
background-color: lightgray;
}
#block1 { color: white;}
table{border: thin solid black; border-collapse: collapse;
margin: 5px; float: left;}
td {padding: 2px;}
</style>
<link rel="stylesheet" type="text/css"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css"/>
<style media="screen AND (min-width:500px)" type="text/css">
#block2 {color:yellow; font-style:italic}
</style>
</head>
<body>
<p id="block1">test
</p>
<p id="block2">
This is a test. Test Test Test Test.
</p>
<div id="placeholder"/>
<script>
let placeholder = document.getElementById("placeholder");
let sheets = document.styleSheets;
for (let i = 0; i < sheets.length; i++) {
let newElem = document.createElement("table");
newElem.setAttribute("border", "1");
addRow(newElem, "Index", i);
addRow(newElem, "href", sheets[i].href);
addRow(newElem, "title", sheets[i].title);
addRow(newElem, "type", sheets[i].type);
addRow(newElem, "ownerNode", sheets[i].ownerNode.tagName);
placeholder.appendChild(newElem);
}
function addRow(elem, header, value) {
elem.innerHTML += "<tr><td>" + header + ":</td><td>"
+ value + "</td></tr>";
}
</script>
</body>
</html>
The script in this example enumerates the stylesheets defined in the document and creates a table
element containing the basic information available for each.
In this document, there are three stylesheets.
Two are defined using script elements and the other is contained in an external file called
styles.css and is imported into the document using the link element.
Note that not all properties have values.
As an example, the href property will only return a value if
the stylesheet has been loaded as an external file.
DOM Working with StyleSheet Media Constraints
You can use the media attribute when defining stylesheets to restrict the
circumstances under which the styles will be applied.
You can access those constraints through the CSSStyleSheet.media property, which returns a MediaList object.
The methods and properties of the MediaList object are described in the following table.
The Members of the MediaList Object.
Member | Description | Returns |
appendMedium(<medium>) | Adds a new medium to the list. | void |
deleteMedium(<medium>) | Removes a medium from the list. | void |
item(<pos>) | Returns the media at the specified index. | string |
length | Returns the number of media. | number |
mediaText | Returns the text value of the media attribute. | string |
The following code demonstrates the use of the MediaList object.
Using the MediaList Object.
<!DOCTYPE HTML>// w w w. de m o2 s . c o m
<html>
<head>
<style title="core styles">
p {
border: medium double black;
background-color: lightgray;
}
#block1 { color: white;}
table {border: thin solid black; border-collapse: collapse;
margin: 5px; float: left;}
td {padding: 2px;}
</style>
<style media="screen AND (min-width:500px), PRINT" type="text/css">
#block2 {color:yellow; font-style:italic}
</style>
</head>
<body>
<p id="block1">test
</p>
<p id="block2">
This is a test. Test Test Test Test.
</p>
<div id="placeholder"/>
<script>
let placeholder = document.getElementById("placeholder");
let sheets = document.styleSheets;
for (let i = 0; i < sheets.length; i++) {
if (sheets[i].media.length > 0) {
let newElem = document.createElement("table");
newElem.setAttribute("border", "1");
addRow(newElem, "Media Count", sheets[i].media.length);
addRow(newElem, "Media Text", sheets[i].media.mediaText);
for (let j =0; j < sheets[i].media.length; j++) {
addRow(newElem, "Media " + j, sheets[i].media.item(j));
}
placeholder.appendChild(newElem);
}
}
function addRow(elem, header, value) {
elem.innerHTML += "<tr><td>" + header + ":</td><td>"
+ value + "</td></tr>";
}
</script>
</body>
</html>
In this example, we create a table for any stylesheet that has a media attribute, enumerating the
individual media, the total number of media in the attribute value, and the overall media string.
DOM Disabling Stylesheets
The CSSStyleSheet.disabled property lets you enable and disable all of the styles in a stylesheet in a
single step.
The following code gives a demonstration of using this property to toggle a stylesheet on and off.
Enabling and Disabling a Stylesheet.
<!DOCTYPE HTML>/* w ww . d e m o 2 s . c o m*/
<html>
<head>
<style title="core styles">
p {
border: medium double black;
background-color: lightgray;
}
#block1 { color: white;
border: thick solid black;
background-color: gray;}
</style>
</head>
<body>
<p id="block1">test
</p>
<div><button id="pressme">Press Me </button></div>
<script>
document.getElementById("pressme").onclick = function() {
document.styleSheets[0].disabled =
!document.styleSheets[0].disabled;
}
</script>
</body>
</html>
In this example, clicking the button toggles the value of the disabled property on the stylesheet.
When a stylesheet is disabled, none of the styles within the stylesheet are applied to elements.
DOM Working with Individual Styles
The CSSStyleSheet.cssRules property returns a CSSRuleList object that provides access to the individual
styles in the stylesheet.
The members of this object are described in the following table.
The Members of the CSSRuleList Object.
Member | Description | Returns |
item(<pos>) | Returns the CSS style at the specified index. | CSSStyleRule |
length | Returns the number of styles in the stylesheet. | number |
Each CSS style in the stylesheet is represented by a CSSStyleRule object.
The members of the CSSStyleRule are shown in the following table.
Member | Description | Returns |
cssText | Gets or sets the text including the selector for the style. | string |
parentStyleSheet | Gets the stylesheet to which this style belongs. | CSSStyleSheet |
selectorText | Gets or sets the selector text for the style. | string |
style | Gets an object representing the styles. | CSSStyleDeclaration |
The following code shows the use of the CSSRuleList object and the basic properties of the CSSStyleRule
object.
The style property returns a CSSStyleDeclaration property, which allows you
to work with a style and which is the same object you use when applying styles to an individual
element.
Working with the CSSRuleList and CSSStyleRule Objects.
let placeholder = document.getElementById("placeholder");
processStyleSheet();/* ww w . d e m o 2 s . c o m */
document.getElementById("pressme").onclick = function() {
document.styleSheets[0].cssRules.item(1).selectorText = "#block2";
if (placeholder.hasChildNodes()) {
let childCount = placeholder.childNodes.length;
for (let i = 0; i < childCount; i++) {
placeholder.removeChild(placeholder.firstChild);
}
}
processStyleSheet();
}
function processStyleSheet() {
let rulesList = document.styleSheets[0].cssRules;
for (let i = 0; i < rulesList.length; i++) {
let rule = rulesList.item(i);
let newElem = document.createElement("table");
newElem.setAttribute("border", "1");
addRow(newElem, "parentStyleSheet", rule.parentStyleSheet.title);
addRow(newElem, "selectorText", rule.selectorText);
addRow(newElem, "cssText", rule.cssText);
placeholder.appendChild(newElem);
}
}
function addRow(elem, header, value) {
elem.innerHTML += "<tr><td>" + header + ":</td><td>"
+ value + "</td></tr>";
}
Open in separate window
View full source code
<html>
<head>
<style title="core styles">
p {<!-- w w w . d e m o 2 s .c o m -->
border: medium double black;
background-color: lightgray;
}
#block1 { color: white;
border: thick solid black;
background-color: gray;}
table {border: thin solid black; border-collapse: collapse;
margin: 5px; float: left;}
td {padding: 2px;}
</style>
</head>
<body>
<p id="block1">test
</p>
<p id="block2">
This is a test. Test Test Test Test.
</p>
<div><button id="pressme">Press Me </button></div>
<div id="placeholder"></div>
<script>
let placeholder = document.getElementById("placeholder");
processStyleSheet();
document.getElementById("pressme").onclick = function() {
document.styleSheets[0].cssRules.item(1).selectorText =
"#block2";
if (placeholder.hasChildNodes()) {
let childCount = placeholder.childNodes.length;
for (let i = 0; i < childCount; i++) {
placeholder.removeChild(placeholder.firstChild);
}
}
processStyleSheet();
}
function processStyleSheet() {
let rulesList = document.styleSheets[0].cssRules;
for (let i = 0; i < rulesList.length; i++) {
let rule = rulesList.item(i);
let newElem = document.createElement("table");
newElem.setAttribute("border", "1");
addRow(newElem, "parentStyleSheet",
rule.parentStyleSheet.title);
addRow(newElem, "selectorText", rule.selectorText);
addRow(newElem, "cssText", rule.cssText);
placeholder.appendChild(newElem);
}
}
function addRow(elem, header, value) {
elem.innerHTML += "<tr><td>" + header + ":</td><td>"
+ value + "</td></tr>";
}
</script>
</body>
</html>
We can get information about the defined styles, reporting on the parent stylesheet, the selector, and the individual declarations contained
in the style.
Some browser will display the shorthand properties if they have been used.
When the button is clicked, the
selector for one of the styles is changed from #block1 to #block2, which has the effect of changing which
of the p elements the style applies to.
DOM Working with Element Styles
To obtain the properties defined in an element's style attribute, you read the value of the style property
defined by HTMLElement objects.
The style property returns a CSSStyleDeclaration object, which is the same kind of object that you can obtain
through stylesheets.
To demonstrate the HTMLElement.style property, we have used the CSSStyleDeclaration.cssText property in following code to
display and modify the style properties that are applied to an element.
Obtaining a CSSStyleDeclaration Object from an HTMLElement.
let placeholder = document.getElementById("placeholder");
let targetElem = document.getElementById("block1");
displayStyle();/* w ww . d e m o2 s . c o m */
document.getElementById("pressme").onclick = function() {
targetElem.style.cssText = "color:black";
displayStyle();
}
function displayStyle() {
if (placeholder.hasChildNodes()) {
placeholder.removeChild(placeholder.firstChild);
}
let newElem = document.createElement("table");
addRow(newElem, "Element CSS", targetElem.style.cssText);
placeholder.appendChild(newElem);
}
function addRow(elem, header, value) {
elem.innerHTML += "<tr><td>" + header + ":</td><td>"
+ value + "</td></tr>";
}
Open in separate window
View full source code
<html>
<body>
<p id="block1"
style=
"color:white; border: thick solid black; background-color: gray">
test<!-- w w w . d e m o 2 s. c om -->
</p>
<div><button id="pressme">Press Me </button></div>
<div id="placeholder"></div>
<script>
let placeholder = document.getElementById("placeholder");
let targetElem = document.getElementById("block1");
displayStyle();
document.getElementById("pressme").onclick = function() {
targetElem.style.cssText = "color:black";
displayStyle();
}
function displayStyle() {
if (placeholder.hasChildNodes()) {
placeholder.removeChild(placeholder.firstChild);
}
let newElem = document.createElement("table");
addRow(newElem, "Element CSS", targetElem.style.cssText);
placeholder.appendChild(newElem);
}
function addRow(elem, header, value) {
elem.innerHTML += "<tr><td>" + header + ":</td><td>"
+ value + "</td></tr>";
}
</script>
</body>
</html>
This script displays the value of the style attribute for an element and, when the button is clicked,
changes that value to apply a different style.
Working with CSSStyleDeclaration Objects
To get complete control of CSS via the DOM, you have to use the CSSStyleDeclaration object.
The Members of the CSSStyleDeclaration Object.
Member | Description | Returns |
cssText | Gets or sets the text of the style. | string |
getPropertyCSSValue(<name>) | Gets the specified property. | CSSPrimitiveValue |
getPropertyPriority(<name>) | Gets the priority of the specified property. | string |
getPropertyValue(<name>) | Gets the specified value as a string. | string |
item(<pos>) | Gets the item at the specified position. | string |
length | Gets the number of items. | number |
parentRule | Gets the style rule if there is one. | CSSStyleRule |
removeProperty(<name>) | Removes the specified property. | string |
setProperty(<name>, <value>, <priority>) | Sets the value and priority for the specified property. | void |
<style> | Convenience property to get or set the specified CSS property. | string |
In addition to the item method, most browsers support array-style notation, so that item(4) and
item[4] are equivalent.
Working with the Convenience Properties
The easiest way to work with a CSSStyleDeclaration object is through the convenience properties, which
correspond to individual CSS properties.
You can determine the current value for a CSS property by
reading the corresponding object property, and change the CSS value by assigning a new value to the
object property.
You are effectively reading and
modifying the values defined in the HTML document, either in a stylesheet or applied directly to an element.
When the browser comes to display an element, it will generated a set of computed values, where the browser styles,
the stylesheets, and style attributes are allowed to cascade and inherit.
Working with CSSStyleDeclaration Object Convenience Properties.
let placeholder = document.getElementById("placeholder");
displayStyles();// ww w . d e m o 2s . c om
document.getElementById("pressme").onclick = function() {
document.styleSheets[0].cssRules.item(1).style.paddingTop = "10px";
document.styleSheets[0].cssRules.item(1).style.paddingRight = "12px";
document.styleSheets[0].cssRules.item(1).style.paddingLeft = "5px";
document.styleSheets[0].cssRules.item(1).style.paddingBottom = "5px";
displayStyles();
}
function displayStyles() {
if (placeholder.hasChildNodes()) {
let childCount = placeholder.childNodes.length;
for (let i = 0; i < childCount; i++) {
placeholder.removeChild(placeholder.firstChild);
}
}
displayStyleProperties(document.styleSheets[0].cssRules.item(1).style);
displayStyleProperties(document.getElementById("block2").style);
}
function displayStyleProperties(style) {
let newElem = document.createElement("table");
newElem.setAttribute("border", "1");
addRow(newElem, "border", style.border);
addRow(newElem, "color", style.color);
addRow(newElem, "padding", style.padding);
addRow(newElem, "paddingTop", style.paddingTop);
placeholder.appendChild(newElem);
}
function addRow(elem, header, value) {
elem.innerHTML += "<tr><td>" + header + ":</td><td>"
+ value + "</td></tr>";
}
Open in separate window
View full source code
<html>
<head>
<style title="core styles">
#block1 { color: white;
border: thick solid black;
background-color: gray;}
p {<!-- w w w . d e m o 2 s . co m -->
border: medium double black;
background-color: lightgray;
}
table{border: thin solid black;
border-collapse: collapse;
margin: 5px; float: left;}
td {padding: 2px;}
</style>
</head>
<body>
<p id="block1">test
</p>
<p id="block2"
style="border: medium dashed blue; color: red; padding: 2px">
This is a test. Test Test Test Test.
</p>
<div><button id="pressme">Press Me </button></div>
<div id="placeholder"></div>
<script>
let placeholder = document.getElementById("placeholder");
displayStyles();
document.getElementById("pressme").onclick = function() {
document.styleSheets[0].cssRules.item(1).style.paddingTop =
"10px";
document.styleSheets[0].cssRules.item(1).style.paddingRight =
"12px";
document.styleSheets[0].cssRules.item(1).style.paddingLeft =
"5px";
document.styleSheets[0].cssRules.item(1).style.paddingBottom =
"5px";
displayStyles();
}
function displayStyles() {
if (placeholder.hasChildNodes()) {
let childCount = placeholder.childNodes.length;
for (let i = 0; i < childCount; i++) {
placeholder.removeChild(placeholder.firstChild);
}
}
displayStyleProperties(
document.styleSheets[0].cssRules.item(1).style);
displayStyleProperties(document.getElementById("block2").style);
}
function displayStyleProperties(style) {
let newElem = document.createElement("table");
newElem.setAttribute("border", "1");
addRow(newElem, "border", style.border);
addRow(newElem, "color", style.color);
addRow(newElem, "padding", style.padding);
addRow(newElem, "paddingTop", style.paddingTop);
placeholder.appendChild(newElem);
}
function addRow(elem, header, value) {
elem.innerHTML += "<tr><td>" + header + ":</td><td>"
+ value + "</td></tr>";
}
</script>
</body>
</html>
The script in code displays the values of four CSSStyleDeclaration convenience properties.
These are read from objects obtained from a stylesheet and from an element's style attribute to
demonstrate the two different ways you can get these objects.
The border, color, and padding convenience properties correspond to the CSS properties with the
same name.
The paddingTop convenience property corresponds to the padding-top CSS property.
This is the general naming pattern for multiword CSS properties: remove the hyphens and capitalize the first
letter of the second and subsequent words.
As you can see, there are convenience properties for both
shorthand and individual CSS properties (padding and paddingTop, for example).
The convenience
properties return an empty string ("") when there is no value set for the corresponding CSS property.
When the button is clicked, the script modifies the value of the individual padding properties using
the paddingTop, paddingBottom, paddingLeft, and paddingRight convenience properties on the
CSSStyleDeclaration object obtained from the first stylesheet in the document.
DOM Element Active Element with Focus
HTML5 adds functionality to aid with focus management in the DOM.
The first is document.activeElement, which always contains a pointer
to the DOM element that currently has focus.
An element can receive focus automatically as the page is loading, via user
input, or programmatically using the focus() method.
For example:
let button = document.getElementById("myButton");
button.focus();
console.log(document.activeElement === button); // true
By default, document.activeElement is set to document.body
when the document is first loaded.
Before the document is fully loaded, document.activeElement is null.
The document.hasFocus() returns a Boolean value indicating if the document has focus:
let button = document.getElementById("myButton");
button.focus();
console.log(document.hasFocus()); // true
Determining if the document has focus allows you to determine if the user is interacting
with the page.
DOM Custom Data Attributes
HTML5 allows elements to have non standard attributes prefixed with data- in order
to provide information that isn't necessary to the rendering or semantic value of the element.
These attributes can be added as desired and named anything,
provided that the name begins with data-.
Here is an example:
<div id="myDiv" data-appId="12345" data-myname="CSS"></div>
When a custom data attribute is defined, it can be accessed via the dataset
property of the element.
The dataset property contains an instance of DOMStringMap that is a mapping
of name-value pairs.
Each attribute of the format data-name is represented by a property with a name
equivalent to the attribute but without the data- prefix.
For example, attribute data-myname is represented by a property called myname.
The following is an example of how to use custom data attributes:
let div = document.getElementById("myDiv");
// Get the values
let appId = div.dataset.appId;
let myName = div.dataset.myname;
// Set the value
div.dataset.appId = 1234;
div.dataset.myname = "CSS";
// Is there a "myname" value?
if (div.dataset.myname){
console.log('Hello, ${div.dataset.myname}');
}
Custom data attributes are useful when non visual data needs to be tied to an element.
DOM Element children Property
The children property is an HTMLCollection that contains only an element's
child nodes that are also elements.
Otherwise, the children
property is the same as childNodes and may contain the same items when an element has only
elements as children.
The children property is accessed as follows:
let childCount = element.children.length;
let firstChild = element.children[0];
All modern browsers support contains.
DOM Element classList Property
The className property is used to add, remove, and replace class names.
Because className contains a single string,
we have to deal with the class list as a while string.
For example, consider the following HTML code:
<div class="abc user disabled">...</div>
This <div> element has three classes assigned.
To remove one of these classes, you need to split the
class attribute into individual classes, remove the unwanted class, and then create a string containing the remaining classes.
HTML5 classList property provides a new way to work with class list.
The classList property is an instance of a new type of collection named DOMTokenList.
DOMTokenList has a length property to indicate how many items it contains,
and individual items may be retrieved via the item() method or using bracket notation.
It also has the following additional methods:
Method | Meaning |
add(value) | Adds the given string value to the list. If the value already exists, it will not be added. |
contains(value) | Indicates if the given value exists in the list (true if so; false if not). |
remove(value) | Removes the given string value from the list. |
toggle(value) | If the value already exists in the list, it is removed. If the value doesn't exist, then it's added. |
To remove one class among the class list string we can do:
div.classList.remove("user");
Using this code ensures that the rest of the class names will be unaffected by the change.
The other methods reduce the complexity of the basic operations,
as shown in these examples:
Remove the "disabled" class.
div.classList.remove("disabled");
Add the "current" class.
div.classList.add("current");
Toggle the "user" class.
div.classList.toggle("user");
Figure out what's on the element.
if (div.classList.contains("abc") && !div.classList.contains("disabled")){
// Do stuff
)
Iterate over the class names.
for (let class of div.classList){
doStuff(class);
}
The classList property is fully in all other major browsers.
DOM Get element Client Dimensions
The client dimensions of an element comprise the space occupied by the element's content and its padding.
There are only two properties related to client dimensions: clientWidth and
clientHeight.
The clientWidth property is the width of the content area plus the width of both the left
and the right padding.
The clientHeight property is the height of the content area plus the height of
both the top and the bottom padding.
The client dimensions are the amount of space inside of the element, so the space
taken up by scrollbars is not counted.
The most common use of these properties is to determine the browser viewport size.
This is done by using the clientWidth and clientHeight of document.documentElement.
These properties represent the dimensions of the viewport which is the <html> or <body> elements.
The client dimensions are read-only and are calculated each time they are accessed.
DOM Element contains() Method
We can use contains() method to determine if a given node is a descendant of another.
The contains() method is called on the ancestor node from
which the search should begin and accepts a single argument,
which is the target descendant node.
If the node exists as a descendant of the root node, the method returns true; otherwise it returns
false.
Here is an example:
console.log(document.documentElement.contains(document.body)); // true
This example tests to see if the <body> element is a descendant
of the <html> element, which returns
true in all well-formed HTML pages.
DOM Get Element Dimensions
Browsers offer a method called getBoundingClientRect() on each element, which
returns a DOMRect object that has six properties: left, top, right, bottom, height, and width.
These properties give the location of the element on the page relative to the viewport.
let myDiv = document.getElementById("myDiv");
let rect = myDiv.getBoundingClientRect();
console.log(rect);
DOM Element innerHTML Property
When used in read mode, innerHTML returns the HTML representing all of the child nodes, including
elements, comments, and text nodes.
When used in write mode, innerHTML completely replaces all of
the child nodes in the element with a new DOM subtree based on the specified value.
Consider the following HTML code:
<div id="content">
<p>This is a <strong>paragraph</strong> with a list following it.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
For the <div> element in this example, the innerHTML property returns the
following string:
<p>This is a <strong>paragraph</strong> with a list following it.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
The exact text returned from innerHTML differs from browser to browser.
You cannot depend on
the returned value of innerHTML being exactly the same from browser to browser.
When used in write mode, innerHTML parses the given string into a DOM subtree and replaces all of
the existing child nodes with it.
Because the string is considered to be HTML, all tags are converted
into elements in the standard way that the browser handles HTML.
Setting simple text without any HTML tags, as shown here, sets the plain text:
div.innerHTML = "Hello world!";
You can set innerHTML to a string containing HTML and the string will be parsed.
Consider the following example:
div.innerHTML = "Hello & hi, <b>\"hi\"!</b>";
The result of this operation is as follows:
<div id="content">Hello & hi, <b>"hi"!</b></div>
After setting innerHTML, you can access the newly created nodes as you would any other nodes in
the document.
Setting innerHTML causes the HTML string to be parsed by the browser
into an appropriate DOM tree.
Setting innerHTML and then
reading it back typically results in a different string being returned.
The returned string is the result of serializing the DOM subtree that was
created for the original HTML string.
DOM Element innerText Property
The innerText property works with all text content contained within an element, regardless of how
deep in the subtree the text exists.
When used to read the value, innerText concatenates the values
of all text nodes in the subtree in depth-first order.
When used to write the value, innerText removes
all children of the element and inserts a text node containing the given value.
Consider the following
HTML code:
<div id="content">
<p>This is a <strong>paragraph</strong> with a list following it.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
For the <div> element in this example, the innerText property returns the following string:
This is a paragraph with a list following it.
Item 1
Item 2
Item 3
Note that different browsers treat white space in different ways,
so the formatting may or may not
include the indentation in the original HTML code.
The following code uses the innerText property to set the contents of the <div> element:
div.innerText = "Hello world!";
After executing this line of code, the HTML of the page is effectively changed to the
following:
<div id="content">Hello world!</div>
Setting innerText removes all of the child nodes that existed before, completely changing the DOM
subtree.
Additionally, setting innerText encodes all HTML syntax characters such as
less-than, greater-than, quotation marks, and ampersands, that may appear in the text.
Here is an example:
div.innerText = "Hello & hi, <b>\"hi\"!</b>";
The result of this operation is as follows:
<div id="content">
Hello & hi, <b>"hi"!</b></div>
The innerText property is also useful for stripping out HTML tags.
By setting the innerText equal
to the innerText, as shown here, all HTML tags are removed:
div.innerText = div.innerText;
Executing this code replaces the contents of the container with just the text that exists already.
DOM Element insert Adjacent HTML()
The insertAdjacentHTML() method accepts two arguments:
the position in which to insert and
the HTML or text to insert.
The first argument must be one of the following values:
Value | Meaning |
"beforebegin" | Insert just before the element as a previous sibling. |
"afterbegin" | Insert just inside of the element as a new child or series of children before the first child. |
"beforeend" | Insert just inside of the element as a new child or series of children after the last child. |
"afterend" | Insert just after the element as a next sibling. |
Note that each of these values is case insensitive.
The second argument is parsed as an
HTML string or as a raw string and in the case of HTML,
will throw an error if the value cannot be properly
parsed.
Basic usage is as follows.
Insert as previous sibling.
element.insertAdjacentHTML("beforebegin", "<p>Hello world!</p>");
element.insertAdjacentText("beforebegin", "Hello world!");
Insert as first child.
element.insertAdjacentHTML("afterbegin", "<p>Hello world!</p>");
element.insertAdjacentText("afterbegin", "Hello world!");
Insert as last child.
element.insertAdjacentHTML("beforeend", "<p>Hello world!</p>");
element.insertAdjacentText("beforeend", "Hello world!");
Insert as next sibling.
element.insertAdjacentHTML("afterend", "<p>Hello world!</p>"); element.
insertAdjacentText("afterend", "Hello world!");
DOM insertAdjacentText() Methods
The insertAdjacentText() methods accept two arguments:
the position in which to insert and
the HTML or text to insert.
The first argument must be one of the following values:
Value | Meaning |
"beforebegin" | Insert just before the element as a previous sibling. |
"afterbegin" | Insert just inside of the element as a new child or series of children before the first child. |
"beforeend" | Insert just inside of the element as a new child or series of children after the last child. |
"afterend" | Insert just after the element as a next sibling. |
Note that each of these values is case insensitive.
The second argument is parsed as an
HTML string or as a raw string and in the case of HTML,
will throw an error if the value cannot be properly
parsed.
Basic usage is as follows.
Insert as previous sibling.
element.insertAdjacentHTML("beforebegin", "<p>Hello world!</p>");
element.insertAdjacentText("beforebegin", "Hello world!");
Insert as first child.
element.insertAdjacentHTML("afterbegin", "<p>Hello world!</p>");
element.insertAdjacentText("afterbegin", "Hello world!");
Insert as last child.
element.insertAdjacentHTML("beforeend", "<p>Hello world!</p>");
element.insertAdjacentText("beforeend", "Hello world!");
Insert as next sibling.
element.insertAdjacentHTML("afterend", "<p>Hello world!</p>"); element.
insertAdjacentText("afterend", "Hello world!");
DOM Get Element Offset Dimensions
The offset dimensions' properties incorporate all of the visual space that
an element takes up on the screen.
The following four properties are used to retrieve offset dimensions:
Property | Meaning |
offsetHeight | The amount of vertical space, in pixels, taken up by the element, including its height, the height of a horizontal scrollbar (if visible), the top border height, and the bottom border height. |
offsetLeft | The number of pixels between the element's outside left border and the containing element's inside left border. |
offsetTop | The number of pixels between the element's outside top border and the containing element's inside top border. |
offsetWidth | The amount of horizontal space taken up by the element, including its width, the width of a vertical scrollbar (if visible), the left border width, and the right border width. |
The offsetLeft and offsetTop properties are in relation to the containing element, which is stored in the offsetParent property.
The offsetParent may not necessarily be the same as the parentNode.
For example, the offsetParent of a <td> element is the <table> element that it's an
ancestor of, because the <table> is the first element in the hierarchy that provides dimensions.
The offset of an element on the page can roughly be determined by taking the offsetLeft and
offsetTop properties and adding them to the same properties of the offsetParent, continuing up the
hierarchy until you reach the root element.
Here is an example:
function getElementLeft(element) {
let actualLeft = element.offsetLeft;
let current = element.offsetParent;
while (current !== null) {
actualLeft += current.offsetLeft;
current = current.offsetParent;/* w w w . d e m o 2 s . c o m*/
}
return actualLeft;
}
function getElementTop(element) {
let actualTop = element.offsetTop;
let current = element.offsetParent;
while (current !== null) {
actualTop += current.offsetTop;
current = current.offsetParent;
}
return actualTop;
}
These two functions go through the DOM hierarchy using the offsetParent property, adding up the offset properties at each level.
For simple page layouts using CSS-based layouts, these functions are very accurate.
Generally, all elements that are contained solely within <div> elements have <body> as their offsetParent, so getElementLeft() and getElementTop() will return the same values as offsetLeft and
offsetTop.
All of the offset dimension properties are read-only and are calculated
each time they are accessed.
DOM Element outerText Property
The outerText property works in the same way as innerText except that
it includes the node on
which it's called.
For reading text values, outerText and innerText essentially behave in the exact
same way.
In writing mode, outerText behaves differently.
The outerText actually replaces the entire element, including its child nodes.
Consider the following:
div.outerText = "Hello world!";
This single line of code is equivalent to the following two lines:
let text = document.createTextNode("Hello world!");
div.parentNode.replaceChild(text, div);
Essentially, the new text node completely replaces the element on which
outerText was set.
After that point in time, the element is no longer in the document and cannot be accessed.
The outerText property is nonstandard.
It is supported in all modern browsers except for Firefox.
DOM Element outerHTML Property
When outerHTML is called in read mode,
it returns the HTML of the element on which it is called, as well as its child nodes.
When called in write mode, outerHTML replaces the node on which it is
called with the DOM subtree created from parsing the given HTML string.
Consider the following
HTML code:
<div id="content">
<p>This is a <strong>paragraph</strong> with a list following it.</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
When outerHTML is called on the <div> in this example,
the same code is returned, including the code for the <div>.
There may be differences based on how the browser parses and interprets the HTML code.
Use outerHTML to set a value in the following manner:
div.outerHTML = "<p>This is a paragraph.</p>";
This code performs the same operation as the following DOM code:
let p = document.createElement("p");
p.appendChild(document.createTextNode("This is a paragraph."));
div.parentNode.replaceChild(p, div);
The new <p> element replaces the original <div> element in the DOM tree.
DOM Get Element Node relationship
We can determine node relationships using the compareDocumentPosition() method.
This method determines the relationship between two nodes and returns a
bit mask indicating the relationship.
The values for the bit mask are as shown in the following table.
Mask | Relationship Between Nodes | Meaning |
0x1 | Disconnected | The passed-in node is not in the document. |
0x2 | Precedes | The passed-in node appears in the DOM tree prior to the reference node. |
0x4 | Follows | The passed-in node appears in the DOM tree after the reference node. |
0x8 | Contains | The passed-in node is an ancestor of the reference node. |
0x10 | Is contained by | The passed-in node is a descendant of the reference node. |
The result of compareDocumentPosition() can be bitwise ANDed to determine if the reference node contains the given node.
Here is an example:
let result = document.documentElement.compareDocumentPosition(document.body);
console.log(!!(result & 0x10));
When this code is executed, result becomes 20, or 0x14
(0x4 for "follows" plus 0x10 for "is contained by").
Applying a bitwise mask of 0x10 to the result returns a nonzero number, and the two
NOT operators convert that value into a Boolean.
All modern browsers support compareDocumentPosition.
DOM Get Element Scroll Dimensions
The scroll dimensions provide information about an element whose
content is scrolling.
The four scroll dimension properties are as follows:
Property | Meaning |
scrollHeight | The total height of the content if there were no scrollbars present. |
scrollLeft | The number of pixels that are hidden to the left of the content area. This property can be set to change the scroll position of the element. |
scrollTop | The number of pixels that are hidden in the top of the content area. This property can be set to change the scroll position of the element. |
scrollWidth | The total width of the content if there were no scrollbars present. |
The scrollWidth and scrollHeight properties are useful for determining the actual dimensions
of the content in a given element.
For example, the <html> element is considered the element that
scrolls the viewport in a web browser.
Therefore, the height of an entire page that has a vertical scrollbar is document.documentElement.scrollHeight.
The relationship between scrollWidth and scrollHeight to clientWidth and clientHeight is
not clear when it comes to documents that do not scroll.
Inspecting these properties on document.documentElement leads to inconsistent results across browsers.
When trying to determine the total height of a document, including the minimum height
based on the viewport, you must take the maximum value of scrollWidth/clientWidth and
scrollHeight/clientHeight to guarantee accurate results across browsers.
Here is an example:
let docHeight = Math.max(document.documentElement.scrollHeight,
document.documentElement.clientHeight);
let docWidth = Math.max(document.documentElement.scrollWidth,
document.documentElement.clientWidth);
The scrollLeft and scrollTop properties can be used either to determine the current scroll settings on an element or to set them.
When an element hasn't been scrolled, both properties are equal to 0.
If the element has been scrolled vertically, scrollTop is greater than 0, indicating the amount of content that is not visible at the top of the element.
If the element has been scrolled horizontally, scrollLeft is greater than 0, indicating the number of pixels that are not visible on the left.
Because each property can also be set, you can reset the element's scroll
position by setting both scrollLeft and scrollTop to 0.
The following function checks to see if the element is at the top, and if not, it scrolls
it back to the top:
function scrollToTop(element) {
if (element.scrollTop != 0) {
element.scrollTop = 0;
}
}
This function uses scrollTop both for retrieving the value and for setting it.
DOM Element Traversal
The Element Traversal API adds five new properties to DOM elements:
Method | Meaning |
childElementCount | Returns the number of child elements (excludes text nodes and comments). |
firstElementChild | Points to the first child that is an element. Element-only version of firstChild. |
lastElementChild | Points to the last child that is an element. Element-only version of lastChild. |
previousElementSibling | Points to the previous sibling that is an element. Element-only version of previousSibling. |
nextElementSibling | Points to the next sibling that is an element. Element-only version of nextSibling. |
The following code shows how to use the Element Traversal properties:
let parentElement = document.getElementById('parent');
let currentChildElement = parentElement.firstElementChild;
// For zero children, firstElementChild returns null and the loop is skipped
while (currentChildElement) {
// You already know this is an ELEMENT_NODE,
// do whatever work is needed here
processChild(currentChildElement);
if (currentChildElement === parentElement.lastElementChild) {
break;
}
currentChildElement = currentChildElement.nextElementSibling;
}
Element Traversal is implemented in Internet Explorer 9+ and all modern browsers.
DOM Get content Document from iframe
Iframe is represented by HTMLIFrameElement.
It has a contentDocument property that contains a pointer to the
document object representing the contents of the iframe.
This property can be used, as shown in the following example:
let iframe = document.getElementById("myIframe");
let iframeDoc = iframe.contentDocument;
The contentDocument property is an instance of Document and can
be used just like any other
HTML document, including all properties and methods.
There is a property called contentWindow that returns the window object for the frame, which has a document property.
The contentDocument and contentWindow properties are available in all modern browsers.
Access to the document object of an iframe is limited based on
cross domain security restrictions.
If you are trying to access the document object
of an iframe containing a page from a different domain or
sub domain, or with a different protocol, you get an error.
DOM Element namespace related Method
The Element has the following namespace related methods which are mostly
related to attributes.
Method | Meaning |
getAttributeNS(namespaceURI, localName) | Gets the attribute from the namespace represented by namespaceURI and with a name of localName. |
getAttributeNodeNS(namespaceURI, localName) | Gets the attribute node from the namespace represented by namespaceURI and with a name of localName. |
getElementsByTagNameNS(namespaceURI, tagName) | Returns a of descendant elements with the given tagName that are also a part of the namespace indicated by namespaceURI. |
hasAttributeNS(namespaceURI, localName) | Determines if the element has an attribute from the namespace represented by namespaceURI and with a name of localName. Note:DOM Level 2 Core also adds a hasAttribute() method for use without namespaces. |
removeAttributeNS(namespaceURI, localName) | Removes the attribute from the namespace represented by namespaceURI and with a name of localName. |
setAttributeNS(namespaceURI, qualifiedName, value) | Sets the attribute from the namespace represented by namespaceURI and with a name of qualifiedName equal to value. |
setAttributeNodeNS(attNode) | Sets the attribute node from the namespace represented by namespaceURI. |
DOM NamedNodeMap namespace method for Attribute
The NamedNodeMap type introduces the following methods for dealing with namespaces.
Because attributes are represented by a NamedNodeMap,
these methods mostly apply to attributes.
Method | Meaning |
getNamedItemNS(namespaceURI, localName) | Gets the item from the namespace represented by namespaceURI and with a name of localName. |
removeNamedItemNS(namespaceURI, localName) | Removes the item from the namespace represented by namespaceURI and with a name of localName. |
setNamedItemNS(node) | Adds node, which should have namespace information already applied. |
These methods are rarely used because attributes are typically accessed
directly from an element.
DOM Event Introduction: event flow, event bubble, event capture
JavaScript's interaction with HTML is handled through events.
Events can be subscribed to
using listeners that execute only when an event occurs.
Event Flow
When you click on a button, you're clicking on the button and on its
container and on the page as a whole.
Event flow describes the order in which events are received on the page.
Event Bubbling
The event flow is called event bubbling if an event is said to start at the most
specific element which is the deepest possible point in the document tree and then
flow upward toward the least specific node which is the document.
Consider the following HTML page:
<!DOCTYPE html>
<html>
<head>
<title>Event Bubbling Example</title>
</head>
<body>
<div id="myDiv">Click Me</div>
</body>
</html>
When you click the <div> element in the page, the click event occurs in the following order:
<div>
<body>
<html>
document
The click event is first fired on the <div>, which is the element that was clicked.
Then the click event goes up the DOM tree,
firing on each node along its way until it reaches the document
object.
All modern browsers support event bubbling, although there
are some variations on how it is implemented.
Modern browsers continue event bubbling up to the window object.
Event Capturing
The event flow is called event capturing if the least specific node should receive the event first and the most
specific node should receive the event last.
Event capturing was designed to intercept the event
before it reached the intended target.
If the previous example is used with event capturing, clicking
the <div> element fires the click event in the following order:
document
<html>
<body>
<div>
With event capturing, the click event is first received by the
document and then continues down the DOM tree to the actual target of
the event, the <div> element.
Event capturing is supported in all modern browsers.
All of them actually begin event capturing at the window-level event.
The general advice is to use event bubbling
freely while retaining event capturing for special circumstances.
Three Phases
The event flow specified by DOM Level 2 Events has three phases:
the event capturing phase,
at the target, and
the event bubbling phase.
Event capturing occurs first, providing the opportunity to
intercept events if necessary.
Next, the actual target receives the event.
The final phase is bubbling, which
allows a final response to the event.
In the DOM event flow, the actual target (the <div> element) does not receive the event during the
capturing phase.
The capturing phase moves from document to <html> to <body>
and stops.
The next phase is "at target," which fires on the <div> and is considered to be part of the
bubbling phase in terms of event handling.
Then, the bubbling phase occurs and the
event travels back up to the document.
Modern browsers all fire an event during the capturing phase on the event target.
There are two opportunities to work with the event on the target.
DOM HTML Event Handlers Attribute
Events are certain actions performed either by the user or by the browser itself.
These events have names like click, load, and mouseover.
A function that is called in response to an event is called an
event handler or an event listener.
Event handlers have names beginning with "on", so an event
handler for the click event is called onclick and an event handler for the load event is called onload.
Assigning event handlers can be accomplished in a number of different ways.
HTML Event Handlers
Each event supported by a particular element can be assigned using an HTML attribute with the
name of the event handler.
The value of the attribute should be some JavaScript code to execute.
For example, to execute some JavaScript when a button is clicked, you can use the following:
<input type="button" value="Click Me" onclick="console.log('Clicked')"/>
When this button is clicked, a message is logged.
This interaction is defined by specifying the
onclick attribute and assigning some JavaScript code as the value.
In this way we need to escape the JavaScript code used attribute value.
To use double quotes, you will change the code to the following:
<input type="button" value="Click Me"
onclick="console.log("Clicked")"/>
An event handler defined in HTML may contain the precise action to take or it can call a script
defined elsewhere on the page, as in this example:
<script>
function showMessage() {
console.log("Hello world!");
}
</script>
<input type="button" value="Click Me" onclick="showMessage()"/>
In this code, the button calls showMessage() when it is clicked.
The showMessage() function is
defined in a separate <script> element and could also be included in an external file.
Code executing as an event handler has access to everything in the global scope.
A function is created that wraps the attribute value.
That function has a special local variable called event, which is the event
object:
<!-- outputs "click" -->
<input type="button" value="Click Me" onclick="console.log(event.type)">
This gives you access to the event object without needing to define it yourself.
The this value inside of the function is equivalent to the event's target element, as shown in
this example:
<!-- outputs "Click Me" -->
<input type="button" value="Click Me" onclick="console.log(this.value)">
Within the function, members of both document and the element itself can be accessed as if they were
local variables.
The event handler code can access other members of the same form
without referencing the form element itself.
<form method="post">
<input type="text" name="username" value="">
<input type="button" value="Echo Username"
onclick="console.log(username.value)">
</form>
Most HTML event
handlers are enclosed in try-catch blocks so that they quietly fail, as in the following example:
<input type="button" value="Click Me" onclick="try{showMessage();}catch(ex) {}">
If this button is clicked before the showMessage() function is defined, no JavaScript error occurs
because the error is caught before the browser can handle it.
DOM Event Handler Property
The traditional way of assigning event handlers in JavaScript is to assign a function to an event
handler property.
This was the event handler assignment method introduced in the fourth generation of
web browsers, and it still remains in all modern browsers because of its simplicity and cross-browser
support.
To assign an event handler using JavaScript, you must first retrieve a reference to the object
to act on.
Each element as well as window and document has event handler properties that are typically all
lowercase, such as onclick.
An event handler is assigned by setting the property equal to a function,
as in this example:
let btn = document.getElementById("myBtn");
btn.onclick = function() {
console.log("Clicked");
};
Here, a button is retrieved from the document and an onclick event handler is assigned.
The event handler is run within the scope of element, meaning
that this is equivalent to the element.
The value of this is demonstrated in the following example:
let btn = document.getElementById("myBtn");
btn.onclick = function() {
console.log(this.id); // "myBtn"
};
This code displays the element's ID when the button is clicked.
The ID is retrieved using this.id.
It's possible to use this to access any of the element's properties or methods from within the event
handlers.
Event handlers added in this way are intended for the bubbling phase of the event flow.
You can remove an event handler by setting the value of the
event handler property to null, as in the following example:
btn.onclick = null; // remove event handler
Once the event handler is set to null, the button no longer has any action to take when it is clicked.
If you've assigned an event handler using HTML, the value on the
onclick property is a function containing the code specified in the HTML
attribute.
These event handlers can also be removed by setting the property to null.
DOM Event Listener
DOM Level 2 Events define two methods to deal with the assignment and removal of event handlers:
addEventListener() and removeEventListener().
These methods exist on all DOM nodes and
accept three arguments:
the event name to handle,
the event handler function, and
a Boolean value indicating whether to call the event handler during the capture phase (true) or during the bubble phase (false).
To add an event handler for the click event on a button, you can use the following code:
let btn = document.getElementById("myBtn");
btn.addEventListener("click", () => {
console.log(this.id);
}, false);
This code adds an onclick event handler to a button that will be fired in the bubbling phase since the last argument is false.
The event handler runs in the scope of the element on which it is attached.
We can add multiple event handlers by using addEventListener().
Consider the following example:
let btn = document.getElementById("myBtn");
btn.addEventListener("click", () => {
console.log(this.id);
}, false);
btn.addEventListener("click", () => {
console.log("Hello world!");
}, false);
Here, two event handlers are added to the button.
The event handlers fire in the order in which
they were added, so the first log displays the element's ID and the second displays the message
"Hello world!"
Event handlers added via addEventListener() can be removed only by using
removeEventListener() and passing in the same arguments as were used when the handler was added.
The anonymous functions added using addEventListener() cannot be removed, as shown in
this example:
let btn = document.getElementById("myBtn");
btn.addEventListener("click", () => {
console.log(this.id);
}, false);
// other code here
btn.removeEventListener("click", function() { // won't work!
console.log(this.id);
}, false);
In this example, an anonymous function is added as an event handler using addEventListener().
The call to removeEventListener() looks like it's using the same arguments, but in reality, the
second argument is a completely different function than the one used in addEventListener().
The
event handler function passed into removeEventListener() must be the same one that was used in
addEventListener(), as in this example:
let btn = document.getElementById("myBtn");
let handler = function() {
console.log(this.id);
};
btn.addEventListener("click", handler, false);
// other code here
btn.removeEventListener("click", handler, false); // works!
This rewritten example works as expected because the same function is used for both
addEventListener() and removeEventListener().
In most cases, event handlers are added to the bubbling phase of the event flow because this offers
the broadest possible cross-browser support.
Attaching an event handler in the capture phase is best
done if you need to intercept events before they reach their intended target.
If this is not necessary, it's advisable to avoid event capturing.
DOM Event Object Introduction
When a DOM event is fired, all of the relevant information is gathered and stored
on an object called event.
This object contains basic information such as
the element that caused the event,
the type of event that occurred, and
any other data that may be relevant to the particular event.
For example, an event caused by a mouse action generates information about the
mouse's position, whereas an event caused by a keyboard action generates information
about the keys that were pressed.
All browsers support the event object in various ways.
In DOM-compliant browsers, the event object is passed in as the only argument to an
event handler.
Here is an example which references the event object inside the handler both ways:
let btn = document.getElementById("myBtn");
btn.onclick = function(event) {
console.log(event.type); // "click"
};
btn.addEventListener("click", (event) => {
console.log(event.type); // "click"
}, false);
Both event handlers in this example log a message indicating the type of event being fired by
using the event.type property.
This property always contains the type of event that was fired,
such as "click".
When an event handler is assigned using HTML attributes, the event object is available as a variable
called event.
This example demonstrates how to use this variable:
<input type="button" value="Click Me" onclick="console.log(event.type)">
Providing the event object in this way allows HTML attribute event handlers to perform the same as
JavaScript functions.
DOM Event Object Property and Method
The event object contains properties and methods related to the specific event that caused its
creation.
The available properties and methods differ based on the type of event that was fired, but all
events have the members listed in the following table.
Property/Method | Type | Read/Write | Description |
bubbles | Boolean | Read only | Indicates if the event bubbles. |
cancelable | Boolean | Read only | Indicates if the default behavior of the event can be canceled. |
currentTarget | Element | Read only | The element whose event handler is currently handling the event. |
defaultPrevented | Boolean | Read only | When true, indicates that preventDefault() has been called. |
detail | Integer | Read only | Extra information related to the event. |
eventPhase
| Integer
| Read only
| The phase during which the event handler is being called: 1 for the capturing phase, 2 for "at target," and 3 for bubbling. |
preventDefault() | Function | Read only | Cancels the default behavior for the event. If cancelable is true, this method can be used. |
stopImmediatePropagation() | Function | Read only | Cancels any further event capturing or event bubbling and prevents any other event handlers from being called. |
stopPropagation() | Function | Read only | Cancels any further event capturing or event bubbling. If bubbles is true, this method can be used. |
target | Element | Read only | The target of the event. |
trusted | Boolean | Read only | When true, indicates if the event was generated by the browser. When false, indicates the event was created using JavaScript by the developer. |
type | String | Read only | The type of event that was fired. |
View | AbstractView | Read only | The abstract view associated with the event. This is equal to the window object in which the event occurred. |
DOM Event Object Target
Inside an event handler, the this object is always equal to the value of currentTarget,
whereas target contains only the actual target of the event.
If the event handler is assigned directly onto the
intended target, then this, currentTarget, and target all have the same value.
Here is an example
demonstrating where the two properties are equivalent to this:
let btn = document.getElementById("myBtn");
btn.onclick = function(event) {
console.log(event.currentTarget === this); // true
console.log(event.target === this); // true
};
This code examines the values of currentTarget and target relative to this.
Because the target
of the click event is the button, all three are equal.
If the event handler existed on a parent node of
the button, such as document.body, the values would be different.
Consider the following example, where a click handler is set on document.body:
document.body.onclick = function(event) {
console.log(event.currentTarget === document.body); // true
console.log(this === document.body); // true
console.log(event.target === document.getElementById("myBtn")); // true
};
When the button is clicked in this example, both this and currentTarget are
equal to document.body because that's where the event handler was registered.
The target property is equal to the
button element itself, because that's the true target of the click event.
Because the button itself doesn't have
an event handler assigned, the click event bubbles up to document.body, where the event is handled.
DOM Event Object Type
The type property is useful when you want to assign a single function to handle multiple events.
Here is an example which uses event.type:
let btn = document.getElementById("myBtn");
let handler = function(event) {
switch(event.type) {
case "click":
console.log("Clicked");
break;
case "mouseover":
event.target.style.backgroundColor = "red";
break;
case "mouseout":
event.target.style.backgroundColor = "";
break;
}
};
btn.onclick = handler;
btn.onmouseover = handler;
btn.onmouseout = handler;
In this example, a single function called handler is defined to handle three different events: click,
mouseover, and mouseout.
Using the event.type property, the function is able to determine which event occurred and then
react appropriately.
DOM Event Object preventDefault() method
The preventDefault() method is used to prevent the default action of a particular event.
The default behavior of a link, for example, is to navigate to the URL specified in its href attribute when
clicked.
If you want to prevent that navigation from occurring, an onclick event handler can cancel
that behavior, as in the following example:
let link = document.getElementById("myLink");
link.onclick = function(event) {
event.preventDefault();
};
Any event that can be canceled using preventDefault() will have its cancelable property
set to true.
DOM Event Object stopPropagation() method
The stopPropagation() method stops the flow of an event through the DOM structure
immediately, canceling any further event capturing or bubbling before it occurs.
For example, an event handler added directly to a button can call stopPropagation() to prevent an event handler on
document.body from being fired, as shown in the following example:
let btn = document.getElementById("myBtn");
btn.onclick = function(event) {
console.log("Clicked");
event.stopPropagation();
};
document.body.onclick = function(event) {
console.log("Body clicked");
};
Without the call to stopPropagation() in this example, two messages would be logged when the
button is clicked.
However, the click event never reaches document.body, so the onclick event
handler is never executed.
DOM Event Object eventPhase Property
The eventPhase property aids in determining what phase of event flow is currently active.
If the event handler is called during the capture phase, eventPhase is 1;
If the event handler is at the target, eventPhase is 2;
If the event handler is during the bubble phase, eventPhase is 3.
Note that even though "at target" occurs during the bubbling phase, eventPhase
is always 2.
Here is an example showing the various eventPhase values:
let btn = document.getElementById("myBtn");
btn.onclick = function(event) {
console.log(event.eventPhase); // 2
};
document.body.addEventListener("click", (event) => {
console.log(event.eventPhase); // 1
}, true);
document.body.onclick = (event) => {
console.log(event.eventPhase); // 3
};
When the button in this example is clicked, the first event handler to fire is the one on
document.body in the capturing phase, which logs a message that displays 1 as the eventPhase.
Next, the event handler on the button itself is fired, at which point the eventPhase is 2.
The last event handler to fire is during the bubbling phase on document.body when eventPhase is 3.
Whenever eventPhase is 2, this, target, and currentTarget are always equal.
The event object exists only while event handlers are still being executed;
once all event handlers have been executed, the event object is destroyed.
DOM Event Types
There are many categories of events that can occur in a web browser.
The type of event being fired determines the information that is available about the event.
DOM Level 3 Events specifies the following event groups:
User interface (UI) events are general browser events that may have some interaction with the BOM.
Focus events are fired when an element gains or loses focus.
Mouse events are fired when the mouse is used to perform an action on the page.
Wheel events are fired when a mouse wheel (or similar device) is used.
Text events are fired when text is input into the document.
Keyboard events are fired when the keyboard is used to perform an action on the page.
Composition events are fired when inputting characters for an Input Method Editor IME.
In addition to these categories, HTML5 defines another set of events, and browsers often
implement proprietary events both on the DOM and on the BOM.
These proprietary events are implemented differently across browsers.
All major browsers support DOM Level 2 and 3 Events.
DOM UI Event
UI events are those events that aren't necessarily related to user actions.
The UI events are as follows:
Event load
| Description Fires on a window when the page has been completely loaded, on a frameset when all frames have been completely loaded, on an <img> element when it has been completely loaded, or on an <object> element when it has been completely loaded. |
unload
| Fires on a window when the page has been completely unloaded, on a frameset when all frames have been completely unloaded, or on an <object> element when it has been completely unloaded. |
abort | Fires on an <object> element if it is not fully loaded before the user stops the download process. |
error
| Fires on a window when a JavaScript error occurs, on an <img> element if the image specified cannot be loaded, on an <object> element if it cannot be loaded, or on a frameset if one or more frames cannot be loaded.. |
select | Fires when the user selects one or more characters in a text box (either <input> or <textarea>). |
resize | Fires on a window or frame when it is resized. |
scroll | Fires on any element with a scrollbar when the user scrolls it. The <body> element contains the scrollbar for a loaded page. |
Most of the HTML events are related either to the window object or to form controls.
DOM UI Event Document Element load Event
The load event is perhaps the most often used event in JavaScript.
For the window object, the load
event fires when the entire page has been loaded, including all external resources such as images,
JavaScript files, and CSS files.
You can define an onload event handler in two ways.
The first is by
using JavaScript, as shown here:
window.addEventListener("load", (event) => {
console.log("Loaded!");
});
The event object is passed into the event handler.
The event object event.target set to document.
The second way to assign the onload event handler is to add an onload attribute to the <body>
element, as in the following example:
<!DOCTYPE html>
<html>
<head>
<title>Load Event Example</title>
</head>
<body onload="console.log('Loaded!')">
</body>
</html>
Generally speaking, any events that occur on the window can be assigned via attributes on the <body>
element because there is no access to the window element in HTML.
DOM UI Event Image Element load Event
The load event also fires on images, both those that are in the DOM and those that are not.
You can
assign an onload event handler directly using HTML on any images in the document, using code
such as this:
<img src="smile.gif" onload="console.log('Image loaded.')">
This example logs a message when the given image has been loaded.
This can also be done using
JavaScript, as follows:
let image = document.getElementById("myImage");
image.addEventListener("load", (event) => {
console.log(event.target.src);
});
Here, the onload event handler is assigned using JavaScript.
The event object is passed in, though it
doesn't have much useful information.
The target of the event is the <img> element, so its src property can be accessed and displayed.
When creating a new <img> element, an event handler can be assigned to indicate when the image has
been loaded.
In this case, it's important to assign the event before assigning the src property, as in the
following example:
window.addEventListener("load", () => {
let image = document.createElement("img");
image.addEventListener("load", (event) => {
console.log(event.target.src);
});
document.body.appendChild(image);
image.src = "smile.gif";
});
The first part of this example is to assign an onload event handler for the window.
A new image element is created and its onload event handler is set.
Then, the image is added to the page and its src is assigned.
Note that the element need not be added to the document for the image download to
begin; it begins as soon as the src property is set.
The Image object was used to preload images on the client.
It can be used the same way as an <img> element
with the exception that it cannot be added into the DOM tree.
Consider the following example which
instantiates a new Image object:
window.addEventListener("load", () => {
let image = new Image();
image.addEventListener("load", (event) => {
console.log("Image loaded!");
});
image.src = "smile.gif";
});
Here, the Image constructor is used to create a new image and the event handler is assigned.
Some browsers implement the Image object as an <img> element, but not all, so it's best to treat them
as separate.
DOM UI Event Script Element load Event
The <script> element fires a load event, allowing you to determine when dynamically loaded JavaScript files have
been completely loaded.
JavaScript files start downloading only after the src property
has been assigned and the element has been added into the document,
so the order in which the event
handler and the src property are assigned is insignificant.
The following illustrates how to assign an event handler for a <script> element:
window.addEventListener("load", () => {
let script = document.createElement("script");
script.addEventListener("load", (event) => {
console.log("Loaded");
});
script.src = "example.js";
document.body.appendChild(script);
});
DOM Document UI Event Element unload Event
The unload event fires when a document has completely unloaded.
The unload event typically fires when navigating from one page to another and is most often used to
clean up references to avoid memory leaks.
An onunload event handler can be assigned in two ways.
The first is by using JavaScript, as shown here:
window.addEventListener("unload", (event) => {
console.log("Unloaded!");
});
The event object is generated for this event and the target is set to document in DOM-compliant browsers.
The second way to assign the event handler is to add an attribute to the <body> element, as in this example:
<!DOCTYPE html>
<html>
<head>
<title>Unload Event Example</title>
</head>
<body onunload="console.log('Unloaded!')">
</body>
</html>
Be careful with the code that executes inside of an onunload
event handler.
Because the unload event fires after everything is unloaded, not all objects that were
available when the page was loaded are still available.
Trying to manipulate the location of a DOM
node or its appearance can result in errors.
DOM UI resize Event
When the browser window is resized to a new height or width, the resize event fires.
This event fires
on window, so an event handler can be assigned either via JavaScript or by using the onresize
attribute on the <body> element.
Prefer to use the JavaScript approach, as shown here:
window.addEventListener("resize", (event) => {
console.log("Resized");
});
The event object is created and its target is document
in DOM-compliant browsers.
We should avoid
computation-heavy code in the event handler for this event because it will be executed frequently and
cause a noticeable slowdown in the browser.
NOTE The resize event also fires when the browser window is minimized or
maximized.
DOM Document UI Element scroll Event
Even though the scroll event occurs on the window, it actually refers to changes in the appropriate
page-level element.
In quirks mode, the changes are observable using the scrollLeft and scrollTop of the
<body> element; in standards mode, the changes occur on the <html> element in all
browsers except Safari, which still tracks scroll position on <body>.
The following example shows how to properly handle this:
window.addEventListener("scroll", (event) => {
if (document.compatMode == "CSS1Compat") {
console.log(document.documentElement.scrollTop);
} else {
console.log(document.body.scrollTop);
}
});
This code assigns an event handler that outputs the vertical scroll position of the page, depending on
the rendering mode.
The scroll event occurs repeatedly as the document is being scrolled, so it's best
to keep the event handlers as simple as possible.
DOM UI Focus Events
Focus events are fired when elements of a page receive or lose focus.
These events work in concert
with the document.hasFocus() and document.activeElement properties to give insight as to how
the user is navigating the page.
There are six focus events:
Event | Meaning |
blur | Fires when an element has lost focus. This event does not bubble and is supported in all browsers. |
focus | Fires when an element has received focus. This event does not bubble and is supported in all browsers. |
focusin | Fires when an element has received focus. This is a bubbling version of the focus HTML event. |
focusout | Fires when an element has lost focus. This is a generic version of the blur HTML event. |
The two primary events of this group are focus and blur, both of which have been supported in
browsers since the early days of JavaScript.
The focus events don't bubble.
This led to the inclusion of focusin and focusout.
When focus is moved from one element to another on the page, the order of events is as follows:
focusout fires on the element losing focus.
focusin fires on the element receiving focus.
blur fires on the element losing focus.
focus fires on the element receiving focus.
DOM UI Mouse and Wheel Events
There are nine mouse events defined in DOM Level 3 Events.
They are as follows:
Event | Meaning |
click | Fires when the user clicks the primary mouse button (the left button) or when the user presses the Enter key. For accessibility purposes, because onclick event handlers can be executed using the keyboard and the mouse. |
dblclick | Fires when the user double-clicks the primary mouse button (the left button). |
mousedown | Fires when the user pushes any mouse button down. |
mouseenter | Fires when the mouse cursor is outside of an element and then the user first moves it inside of the boundaries of the element. This event does not bubble and does not fire when the cursor moves over descendant elements. |
mouseleave | Fires when the mouse cursor is over an element and then the user moves it outside of that element's boundaries. This event does not bubble and does not fire when the cursor moves over descendant elements. |
mousemove | Fires repeatedly as the cursor is being moved around an element. This event cannot be fired via the keyboard. |
mouseout | Fires when the mouse cursor is over an element and then the user moves it over another element. The element moved to may be outside of the bounds of the original element or a child of the original element. This event cannot be fired via the keyboard. |
mouseover | Fires when the mouse cursor is outside of an element and then the user first moves it inside of the boundaries of the element. This event cannot be fired via the keyboard. |
mouseup | Fires when the user releases a mouse button. This event cannot be fired via the keyboard. |
All elements on a page support mouse events.
All mouse events bubble except mouseenter and
mouseleave, and they can all be canceled, which affects the default behavior of the browser.
Canceling the default behavior of mouse events can affect other events as well because of the
relationship that exists amongst the events.
A click event can be fired only if a mousedown event is fired and followed by a mouseup event on
the same element; if either mousedown or mouseup is canceled, then the click event will not fire.
Similarly, it takes two click events to cause the dblclick event to fire.
If anything prevents these
two click events from firing by either canceling one of the click events or
canceling either mousedown or mouseup, the dblclick event will not fire.
These four mouse events always fire in the following order:
mousedown
mouseup
click
mousedown
mouseup
click
dblclick
Both click and dblclick rely on other events to fire before they can fire,
whereas mousedown and mouseup are not affected by other events.
The DOM Level 3 feature name is just
MouseEvent instead of MouseEvents.
There is also a sub group of mouse events called wheel events.
Wheel events are really just a single
event, mousewheel, which monitors interactions of a mouse wheel or a similar device such as the
Mac track pad.
DOM Mouse Event Client Coordinates
Client Coordinates
Mouse events all occur at a particular location within the browser viewport.
This information is
stored in the clientX and clientY properties of the event object.
These properties indicate the location of the mouse cursor within the viewport at
the time of the event and are supported in all browsers.
You can retrieve the client coordinates of a mouse event in the following way:
let div = document.getElementById("myDiv");
div.addEventListener("click", (event) => {
console.log(`Client coordinates: ${event.clientX}, ${event.clientY}`);
});
This example assigns an onclick event handler to a <div> element.
When the element is clicked, the
client coordinates of the event are displayed.
Keep in mind that these coordinates do not take into
account the scroll position of the page, so these numbers do not indicate the location of the cursor
on the page.
Page Coordinates
Where client coordinates give you information about where an event occurred in the viewport, page
coordinates tell you where on the page the event occurred via the pageX and pageY properties of the
event object.
These properties indicate the location of the mouse cursor on the page, so the
coordinates are from the left and top of the page itself rather than the viewport.
You can retrieve the page coordinates of a mouse event in the following way:
let div = document.getElementById("myDiv");
div.addEventListener("click", (event) => {
console.log(`Page coordinates: ${event.pageX}, ${event.pageY}`);
});
The values for pageX and pageY are the same as clientX and clientY when
the page is not scrolled.
You can calculate them using client coordinates and scrolling information.
You need to use the scrollLeft and
scrollTop properties on either document.body when in quirks mode or document.documentElement
in standards mode.
The calculation is done as follows:
let div = document.getElementById("myDiv");
div.addEventListener("click", (event) => {
let pageX = event.pageX,
pageY = event.pageY;
if (pageX === undefined) {
pageX = event.clientX + (document.body.scrollLeft ||
document.documentElement.scrollLeft);
}
if (pageY === undefined) {
pageY = event.clientY + (document.body.scrollTop ||
document.documentElement.scrollTop);
}
console.log(`Page coordinates: ${pageX}, ${pageY}`);
});
Screen Coordinates
Mouse events occur not only in relation to the browser window but also in relation to the entire
screen.
We can determine the location of the mouse in relation to the entire screen by
using the screenX and screenY properties.
You can retrieve the screen coordinates of a mouse event in the following way:
let div = document.getElementById("myDiv");
div.addEventListener("click", (event) => {
console.log(`Screen coordinates: ${event.screenX}, ${event.screenY}`);
});
This code assigns an onclick event handler to a <div> element.
When the element is clicked, the screen coordinates of the event are displayed.
DOM Mouse Modifier Keys
A mouse event can be linked with the state of certain keyboard keys to determine the action to take.
The modifier keys Shift, Ctrl, Alt, and
Meta are often used to alter the behavior of a mouse event.
The DOM specifies four properties to
indicate the state of these modifier keys: shiftKey, ctrlKey, altKey, and metaKey.
Each of these
properties contains a Boolean value that is set to true if the key is being held down or false if the
key is not pressed.
When a mouse event occurs, you can determine the state of the various keys by
inspecting these properties.
Consider the following example, which checks for modifier key state
when a click event is fired:
let div = document.getElementById("myDiv");
div.addEventListener("click", (event) => {
let keys = new Array();
if (event.shiftKey) {
keys.push("shift");
}/* ww w . d e m o 2 s . c o m*/
if (event.ctrlKey) {
keys.push("ctrl");
}
if (event.altKey) {
keys.push("alt");
}
if (event.metaKey) {
keys.push("meta");
}
console.log("Keys: " + keys.join(","));
});
In this example, an onclick event handler checks the state of the various modifier keys.
The keys
array contains the names of the modifier keys that are being held down.
For each property that is true, the name of the key is added to keys.
At the end of the event handler, the keys are displayed in a log message.
Modern browsers support all four keys.
DOM Mouse Event Related Elements
For the mouseover and mouseout events, there are other elements related to
the event.
Both of these
events involve moving the mouse cursor from within the boundaries of one element to within the
boundaries of another element.
For the mouseover event, the primary target of the event is the
element that is gaining the cursor, and the related element is the one that is
losing the cursor.
For mouseout, the primary target is the element that is losing the cursor, and the related element is the
one that is gaining the cursor.
Consider the following example:
<!DOCTYPE html>
<html>
<head>
<title>Related Elements Example</title>
</head>
<body>
<div id="myDiv"
style="background-color:red;height:100px;width:100px;"></div>
</body>
</html>
This page renders a single <div> on the page.
If the mouse cursor starts over the <div> and then
moves outside of it, a mouseout event fires on <div> and the related element is the <body> element.
The mouseover event fires on <body> and the related element is the <div>.
The DOM provides information about related elements via the relatedTarget property on the
event object.
This property contains a value only for the mouseover and mouseout events; it is null
for all other events.
A cross-browser method to get the related element:
var EventUtil = {
// more code here
getRelatedTarget: function(event) {
if (event.relatedTarget) {
return event.relatedTarget;
} else if (event.toElement) {
return event.toElement;
} else if (event.fromElement) {
return event.fromElement;
} else {
return null;
}
}
};
The code above uses feature detection to determine which value to return.
The EventUtil.getRelatedTarget() method can then be used as follows:
let div = document.getElementById("myDiv");
div.addEventListener("mouseout", (event) => {
let target = event.target;
let relatedTarget = EventUtil.getRelatedTarget(event);
console.log(
`Moused out of ${target.tagName} to ${relatedTarget.tagName}`);
});
This example registers an event handler for the mouseout event on the <div> element.
When the event fires, a message is logged indicating the place the mouse moved from and the place the
mouse moved to.
DOM Mouse Event Buttons
The click event is fired only when the primary mouse button is clicked on an element or when the
Enter key is pressed on the keyboard, so button information isn't necessary.
For the mousedown and
mouseup events, there is a button property on the event object that indicates the button that was
pressed or released.
The DOM button property has the following three possible values:
0 for the primary mouse button,
1 for the middle mouse button (the scroll wheel button), and
2 for the secondary mouse button.
In traditional setups, the primary mouse button is the left button and the
secondary button is the right one.
For mouse events, detail contains a number indicating
how many times a click has occurred at the given location.
Clicks are considered to be a mousedown
event followed by a mouseup event at the same pixel location.
The value of detail starts at 1 and is
incremented every time a click occurs.
If the mouse is moved between mousedown and mouseup, then
detail is set back to 0.
DOM mouse wheel Event
The mousewheel event fires when the user interacts
with the mouse wheel, rolling it vertically in either direction.
This event fires on each element and bubbles up to window on modern browsers.
The event object for the mousewheel event contains all standard
information about mouse events and an additional property
called wheelDelta.
When the mouse wheel is rolled toward
the front of the mouse, wheelDelta is a positive multiple of
120; when the mouse wheel is rolled toward the rear of the
mouse, wheelDelta is a negative multiple of 120.
An onmousewheel event handler can be assigned to any element on the page or to the document to
handle all mouse wheel interactions.
Here's an example:
document.addEventListener("mousewheel", (event) => {
console.log(event.wheelDelta);
});
This example simply displays the wheelDelta value when the event is fired.
In most cases, you need
only know which direction the mouse wheel was turned, which can easily be determined by the sign
of the wheelDelta value.
The mousewheel event was added to HTML5 and availabile in most browsers.
DOM Popup context menu Event
The contextmenu event bubbles, so a single event handler can be assigned to a document that
handles all such events for the page.
The target of the event is the element that was acted on.
This event can be canceled in all browsers, using event.preventDefault() in DOM-compliant browsers.
The contextmenu event is
considered a mouse event and so has all of the properties related to the cursor position.
Typically, a custom context menu is displayed using an oncontextmenu event handler and hidden again using the
onclick event handler.
Consider the following HTML page:
<!DOCTYPE html>
<html>
<head>
<title>ContextMenu Event Example</title>
</head>
<body>
<div id="myDiv">Right click or Ctrl+click me to get a custom context menu.
Click anywhere else to get the default context menu.</div>
<ul id="myMenu" style="position:absolute;visibility:hidden;background-color:
silver">
<li><a href="http://www.google.com">Search site</a></li>
<li><a href="http://www.demo2s.com">Demo site</a></li>
<li><a href="http://www.yahoo.com">Yahoo!</a></li>
</ul>
</body>
</html>
In this code, a <div> is created that has a custom context menu.
The <ul> element serves as the custom context menu and is initially hidden.
The JavaScript to make this example work is as follows:
window.addEventListener("load", (event) => {
let div = document.getElementById("myDiv");
div.addEventListener("contextmenu", (event) => {
event.preventDefault();
let menu = document.getElementById("myMenu");
menu.style.left = event.clientX + "px";
menu.style.top = event.clientY + "px";
menu.style.visibility = "visible";
});
document.addEventListener("click", (event) => {
document.getElementById("myMenu").style.visibility = "hidden";
});
});
Here, an oncontextmenu event handler is defined for the <div>.
The event handler begins by canceling the default behavior, ensuring that the browser's context menu won't be displayed.
Next, the <ul> element is placed into position based on the clientX and clientY properties of the event object.
The last step is to show the menu by setting its visibility to "visible".
An onclick event handler is then added to the document to hide the menu whenever a click occurs, which is the behavior of system context menus.
DOM beforeunload Event
The beforeunload event fires on the window and is intended to give developers a way to prevent the
page from being unloaded.
This event fires before the page starts to unload from the browser,
allowing continued use of the page should it ultimately not be unloaded.
You cannot cancel this event. The event gives you the ability to display a message to the user.
The message indicates that the page is about to
be unloaded, displays the message, and asks if the user would like to continue to close the page or
remain on the page.
In order to cause this dialog box to pop up, you must set event.returnValue equal to the string
you want displayed in the dialog for Internet Explorer and Firefox and also return it as the function
value for Safari and Chrome, as in this example:
window.addEventListener("beforeunload", (event) => {
let message = "Really?";
event.returnValue = message;
return message;
});
DOM Content Loaded Event
The window's load event fires when everything on the page has been completely loaded, which may
take some time for pages with lots of external resources.
The DOMContentLoaded event fires as soon
as the DOM tree is completely formed and without regard to images, JavaScript files, CSS files, or
other such resources.
DOMContentLoaded allows event handlers to be
attached earlier in the page download process, which means a faster time to interactivity for users.
To handle the DOMContentLoaded event, you can attach an event handler either on the document
or on the window.
Here's an example which listens for the event on document:
document.addEventListener("DOMContentLoaded", (event) => {
console.log("Content loaded");
});
The event object target for DOMContentLoaded is document.
The DOMContentLoaded event is typically used
to attach event handlers or perform other DOM
manipulations.
This event always fires before the load event.
For browsers that don't support DOMContentLoaded, a
timeout should be set during page loading with a millisecond delay of 0, as in this example:
setTimeout(() => {
// attach event handlers here
}, 0);
The code will run the function as soon as the current JavaScript process is complete.
There is a single JavaScript process running as the page is being downloaded and constructed, so the
timeout will fire after that.
To work properly, this
must be the first timeout set on the page, and even then, it is not guaranteed that the timeout will run
prior to the load event in all circumstances.
DOM URL Hash Changed Event
HTML5 introduced the hashchange event to notify developers when the URL hash changed.
The URL hash value is everything following a pound sign (#) in a URL.
The developers used the URL hash to store state information or navigational information in Ajax applications.
The onhashchange event handler must be attached to the window, and it is called whenever
the URL hash changes.
The event object should have two additional properties: oldURL and newURL.
These properties hold the complete URL including the hash before the change and after the change.
The contrasting URLs are tracked in the following example:
window.addEventListener("hashchange", (event) => {
console.log(`Old URL: ${event.oldURL}, New URL: ${event.newURL}`);
});
It's best to use the location object to determine the current hash:
window.addEventListener("hashchange", (event) => {
console.log(`Current hash: ${location.hash}`);
});
DOM Key Event
Keyboard events are fired when the user interacts with the keyboard.
There are three keyboard events, as described here:
Event | Meaning |
keydown | Fires when the user presses a key on the keyboard and fires repeatedly while the key is being held down. |
keypress | Fires when the user presses a key on the keyboard that results in a character and fires repeatedly while the key is being held down. This event also fires for the Esc key. DOM Level 3 Events deprecates the keypress event in favor of the textInput event. |
keyup | Fires when the user releases a key on the keyboard. |
These events are most easily seen as the user types in a text box, though all elements support them.
There is only one text event and it is called textInput.
This event is an augmentation of keypress
intended to make it easier to intercept text input before being displayed to the user.
The textInput
event fires just before text is inserted into a text box.
When the user presses a character key once on the keyboard, the keydown event is fired first, followed
by the keypress event, followed by the keyup event.
Both keydown and keypress are fired
before any change has been made to the text box, whereas the keyup event fires after changes have
been made to the text box.
If a character key is pressed and held down, keydown and keypress are
fired repeatedly and don't stop until the key is released.
For non character keys, a single key press on the keyboard results in the keydown event being fired
followed by the keyup event.
If a non character key is held down, the keydown event fires repeatedly
until the key is released, at which point the keyup event fires.
Keyboard events support the same set of modifier keys as mouse events.
The shiftKey, ctrlKey, altKey, and metaKey properties are all available for
keyboard events.
DOM Key Event Key Code
For keydown and keyup events, the event object's keyCode property is filled in with a code that
maps to a specific key on the keyboard.
For alphanumeric keys, the keyCode is the same as the ASCII value
So the 7 key has a keyCode of 55 and
the A key has a keyCode of 65, regardless of the state of the Shift key.
Here's an example shows the inspection of the keyCode property:
let textbox = document.getElementById("myText");
textbox.addEventListener("keyup", (event) => {
console.log(event.keyCode);
});
In this example, the keyCode is displayed every time a keyup event is fired.
The complete list of key codes to non character keys is listed in the following table.
Key | Key Code |
Backspace | 8 |
Tab | 9 |
Enter | 13 |
Shift | 16 |
Ctrl | 17 |
Alt | 18 |
Pause/Break | 19 |
Caps Lock | 20 |
Esc | 27 |
Page Up | 33 |
Page Down | 34 |
End | 35 |
Home | 36 |
Left Arrow | 37 |
Up Arrow | 38 |
Right Arrow | 39 |
Down Arrow | 40 |
Ins | 45 |
Del | 46 |
Left Windows Key | 91 |
Right Windows Key | 92 |
Context Menu Key | 93 |
Num pad 0 | 96 |
Num pad 1 | 97 |
Num pad 2 | 98 |
Num pad 3 | 99 |
Num pad 4 | 100 |
Num pad 5 | 101 |
Num pad 6 | 102 |
Num pad 7 | 103 |
Num pad 8 | 104 |
Num pad 9 | 105 |
Num pad + | 107 |
Minus (both Num pad and not) | 109 |
Num pad . | 110 |
Num pad / | 111 |
F1 | 112 |
F2 | 113 |
F3 | 114 |
F4 | 115 |
F5 | 116 |
F6 | 117 |
F7 | 118 |
F8 | 119 |
F9 | 120 |
F10 | 121 |
F11 | 122 |
F12 | 123 |
Num Lock | 144 |
Scroll Lock | 145 |
Semicolon (IE/Safari/Chrome) | 186 |
Semicolon (Opera/FF) | 59 |
Less than | 188 |
Greater than | 190 |
Forward slash | 191 |
Grave accent ( `) | 192 |
Equals | 61 |
Left Bracket | 219 |
Back slash (\) | 220 |
Right Bracket | 221 |
Single Quote | 222 |
DOM UI Key Character Codes
When a keypress event occurs, this means that the key affects the display of
text on the screen.
All browsers fire the keypress event for keys that insert or remove a character; other keys are
browser-dependent.
Browsers support a property on the event object called charCode, which is filled
in only for the
keypress event and contains the ASCII code for the character related to the key that was pressed.
In this case, the keyCode is typically equal to 0 or may also be equal to the key code for the key that was
pressed.
To retrieve the character code in a cross-browser way, you must therefore first check to see if
the charCode property is used and, if not, use keyCode instead, as shown in the following example:
var EventUtil = {
getCharCode: function(event) {
if (typeof event.charCode == "number") {
return event.charCode;
} else {
return event.keyCode;
}
}
};
This method checks to see if the charCode property is a number.
It will be undefined for browsers that don't support it and, if it is, returns the value.
Otherwise, the keyCode value is returned.
This method can be used as follows:
let textbox = document.getElementById("myText");
textbox.addEventListener("keypress", (event) => {
console.log(EventUtil.getCharCode(event));
});
Once you have the character code, it's possible to convert it to the actual character using the String.fromCharCode() method.
DOM Key text Input Event
The DOM textInput event fires when a character is input to an editable area.
The keypress fires on any element that can have
focus but textInput fires only on editable areas.
The textInput fires only for
keys that result in a new character being inserted, whereas keypress fires for
keys that affect text in any way including Backspace.
The textInput event provides a data property on the
event object that contains the character that was inserted.
The value of data
is always the exact character that was inserted, so if the S key is pressed
without Shift, data is "s",
but if the same key is pressed holding Shift down, then data is "S".
The textInput event can be used as follows:
let textbox = document.getElementById("myText");
textbox.addEventListener("textInput", (event) => {
console.log(event.data);
});
In this example, the character that was inserted into the text box is displayed in a log message.
DOM Key Event Input Method
The event object inputMethod property indicates how the text was
input into the control.
The possible values are:
Value | Indicate |
0 | the browser couldn't determine how the input was entered. |
1 | a keyboard was used. |
2 | the text was pasted in. |
3 | the text was dropped in as part of a drag operation. |
4 | the text was input using an IME. |
5 | the text was input by selecting an option in a form. |
6 | the text was input by handwriting (such as with a stylus). |
7 | the text was input by voice command. |
8 | the text was input by a combination of methods. |
9 | the text was input by script. |
Using this property, you can determine how text was input into a control in order to verify its
validity.
DOM Keyboard Input Composition Events
Composition events handle complex input sequences typically found on IMEs.
IME stands for input method editor.
IMEs allow users to input characters not found on the physical keyboard.
For example, those using a Latin keyboard can still enter Japanese characters into the computer.
IMEs often require multiple keys to be pressed at once while resulting in only a single character being entered.
Composition events help to detect and work with such input.
There are three composition events:
Event | Meaning |
compositionstart | Fires when the text composition system of the IME is opened, indicating that input is about to commence. |
compositionupdate | Fires when a new character has been inserted into the input field. |
compositionend | Fires when the text composition system is closed, indicating a return to normal keyboard input. |
Composition events are similar to text events in many ways.
When a composition event fires, the target is the input field receiving the text.
The only additional event property is data, which contains one of the following:
When accessed during compositionstart, contains the text being edited. For instance, if text has been selected and will now be replaced.
When accessed during compositionupdate, contains the new character being inserted.
When accessed during compositionend, contains all of the input entered during this composition session.
The composition events can be used to filter input where necessary.
These events can be used as follows:
let textbox = document.getElementById("myText");
textbox.addEventListener("compositionstart", (event) => {
console.log(event.data);
});
textbox.addEventListener("compositionupdate", (event) => {
console.log(event.data);
});
textbox.addEventListener("compositionend", (event) => {
console.log(event.data);
});
DOM orientation change Event
The orientationchange event can determine
when the user switched the device from landscape to portrait mode.
The window.orientation property on mobile contains one of three values:
0 for portrait mode,
90 for landscape mode when rotated to the left (the Home button on the right), and
-90 for landscape mode when rotated to the right (the Home button on the left).
Whenever the user changes from one mode to another, the orientationchange event fires.
Typical usage of this event is as follows:
window.addEventListener("load", (event) => {
let div = document.getElementById("myDiv");
div.innerHTML = "Current orientation is " + window.orientation;
window.addEventListener("orientationchange", (event) => {) {
div.innerHTML = "Current orientation is " + window.orientation;
});
});
In this example, the initial orientation is displayed when the load event fires.
Then, the event handler for orientationchange is assigned.
Whenever the event fires, the message on the page is updated to indicate the new orientation.
All iOS devices support both the orientationchange event and the window.orientation property.
Because orientationchange is considered a window event, you can also
assign an event handler by adding the onorientationchange attribute to the
<body> element.
DOM deviceorientation Event
The deviceorientation event is fired on window when accelerometer information is available and changes.
The deviceorientation inform you of how the device is
oriented in space.
A device is said to exist in three-dimensional space
along an x-axis, a y-axis, and a z-axis.
These all start at zero when the device is at rest on a horizontal surface.x
The x-axis goes from the left of the device to the right,
the y-axis goes from the bottom of the device to the
top, and the z-axis goes from the back of the device to
the front.
When deviceorientation fires, it returns information
about how the values of each axis have changed relative
to the device at rest.
The event object has five properties:
Property | Meaning |
alpha | The difference in y-axis degrees as you rotate around the z-axis (side-to-side tilt); a floating point number between 0 and 360. |
beta | The difference in z-axis degrees as you rotate around the x-axis (front-to-back tilt); a floating point number between -180 and 180. |
gamma | The difference in the z-axis degrees as you rotate around the y-axis (twisting tilt); a floating point number between -90 and 90. |
absolute | A Boolean value indicating if the device is returning absolute values or not. |
compassCalibrated | A Boolean value indicating if the device's compass is properly calibrated or not. |
Here's a simple example that outputs the values for alpha, beta, and gamma:
window.addEventListener("deviceorientation", (event) => {
let output = document.getElementById("output");
output.innerHTML =
`Alpha=${event.alpha}, Beta=${event.beta], Gamma=${event.gamma$}<br>`;
});
You can use this information to rearrange or otherwise alter elements on the screen in reaction to the
device changing its orientation.
For example, this code rotates an element in reaction to the device
orientation:
window.addEventListener("deviceorientation", (event) => {
let arrow = document.getElementById("arrow");
arrow.style.webkitTransform = `rotate(${Math.round(event.alpha)}deg)`;
});
The element "arrow" is rotated along with the value of event.alpha, giving it a compass-like feel.
DOM devicemotion Event
The devicemotion event can inform you when the device is actually moving,
not just when it has changed orientation.
For
instance, devicemotion is useful to determine that the device is falling or
is being held by someone who is walking.
When the devicemotion event fires, the event object contains the following additional properties:
Property | Meaning |
acceleration | An object containing x, y, and z properties that tells you the acceleration in each dimension without considering gravity. |
accelerationIncludingGravity | An object containing x, y, and z properties that tells you the acceleration in each dimension, including the natural acceleration of gravity in the z-axis. |
interval | The amount of time, in milliseconds, that will pass before another devicemotion event is fired. This value should be constant from event to event. |
rotationRate | An object containing the alpha, beta, and gamma properties that indicate device orientation. |
If acceleration, accelerationIncludingGravity, or rotationRate
cannot be provided, then the property value is null.
Because of that, you should always check that the value is not null before
using any of these properties.
For example:
window.addEventListener("devicemotion", (event) => {
let output = document.getElementById("output");
if (event.rotationRate !== null) {
output.innerHTML += `Alpha=${event.rotationRate.alpha}` +
`Beta=${event.rotationRate.beta}` +
`Gamma=${event.rotationRate.gamma}`;
}
});
DOM Touch Events
Touch events are fired when a finger is placed on the screen,
dragged across the screen, or removed from the screen.
The touch events are as follows:
Event | Meaning |
touchstart | Fires when a finger touches the screen even if another finger is already touching the screen. |
touchmove | Fires continuously as a finger is moved across the screen. Calling preventDefault() during this event prevents scrolling. |
touchend | Fires when a finger is removed from the screen. |
touchcancel | Fires when the system has stopped tracking the touch. It's unclear in the documentation as to when this can occur. |
Each of these events bubbles and can be canceled.
The event object for each touch
event provides properties that are common to mouse events:
bubbles,
cancelable,
view,
clientX,
clientY,
screenX,
screenY,
detail,
altKey,
shiftKey,
ctrlKey, and
metaKey.
In addition to these common DOM properties, touch events have the following three properties to
track touches:
Property | Meaning |
touches | An array of Touch objects that indicate the currently tracked touches. |
targetTouches | An array of Touch objects specific to the event's target. |
changedTouches | An array of Touch objects that have been changed in the last user action. Each Touch object, in turn, has the following properties: |
clientX | The x-coordinate of the touch target in the viewport. |
clientY | The y-coordinate of the touch target in the viewport. |
identifier | A unique ID for the touch. |
pageX | The x-coordinate of the touch target on the page. |
pageY | The y-coordinate of the touch target on the page. |
screenX | The x-coordinate of the touch target on the screen. |
screenY | The y-coordinate of the touch target on the screen. |
target | The DOM node target for the touch. |
These properties can be used to track the touch around the screen.
For example:
function handleTouchEvent(event) {
// only for one touch
if (event.touches.length == 1)
let output = document.getElementById("output");
switch(event.type) {
case "touchstart":
output.innerHTML += `<br>Touch started:` +
`(${event.touches[0].clientX}` +
` ${event.touches[0].clientY})`;
break;/* ww w . d e m o 2 s . c o m */
case "touchend":
output.innerHTML += `<br>Touch ended:` +
`(${event.changedTouches[0].clientX}` +
` ${event.changedTouches[0].clientY})`;
break;
case "touchmove":
event.preventDefault(); // prevent scrolling
output.innerHTML += `<br>Touch moved:` +
`(${event.changedTouches[0].clientX}` +
` ${event.changedTouches[0].clientY})`;
break;
}
}
}
document.addEventListener("touchstart", handleTouchEvent);
document.addEventListener("touchend", handleTouchEvent);
document.addEventListener("touchmove", handleTouchEvent);
This code tracks a single touch around the screen.
To keep things simple, it outputs information only
when there's a single active touch.
When the touchstart event occurs, it outputs the location of the
touch into a <div>.
When a touchmove event fires, its default behavior is canceled to prevent
scrolling and then it outputs information about the changed
touch.
The touchend event outputs the last information about the touch.
There is nothing in the touches collection during the touchend event,
because there is no longer an active touch; the changedTouches collection must be used instead.
These events fire on all elements of the document, so you can manipulate different parts of the page
individually.
The order of events (including mouse events) when you tap on an element are:
touchstart
mouseover
mousemove (once)
mousedown
mouseup
click
touchend
DOM Event Object
Event Object
All event objects in the DOM are based on the Event Object.
Therefore, all other event objects (like MouseEvent and KeyboardEvent) has access to the Event Object's properties and methods.
Event Property List
Event Method List
DOM KeyboardEvent
Events that occur when user presses a key on the keyboard,
belongs to the KeyboardEvent Object.
Property List
DOM MouseEvent
The MouseEvent Object
Events that occur when the mouse interacts with the HTML document
belongs to the MouseEvent Object.
Property List
Property | Description |
altKey | Check if alt Key pressed |
button | Get which button was clicked |
buttons | Get which buttons were clicked |
clientX | Get client X position |
clientY | Get client Y position |
ctrlKey | Check if ctrl control Key was pressed |
detail | Get detail information |
metaKey | Check if meta Key was pressed |
offsetX | Get X Position relative to element |
offsetY | Get Y Position relative to element |
pageX | Get X Position relative to page |
pageY | Get Y Position relative to element |
relatedTarget | Get related Target element |
screenX | Get X Position relative to screen |
screenY | Get Y Position relative to screen |
shiftKey | Check if shift Key was pressed |
which | Get which button was clicked |
Method List
DOM Mouse WheelEvent
The WheelEvent Object
Events that occur when the mouse wheel is scrolling,
belongs to the WheelEvent Object.
Property List
Property | Description |
deltaMode | WheelEvent deltaMode Property |
deltaX | WheelEvent deltaX Property |
deltaY | WheelEvent deltaY Property |
deltaZ | WheelEvent deltaZ Property |
onplaying Event
Example
Execute a JavaScript when a video is ready to start
after having been paused:
<video onplaying="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onplaying"
event to a video element.</p>
<p>Play, pause and then play the video again.</p>
<video controls onplaying="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support the video tag.
</video><!-- w w w. d e m o 2s .c o m -->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML =
"The video is now playing";
}
</script>
</body>
</html>
Description
The onplaying event occurs when the audio/video is playing
after having been paused or stopped for buffering.
Browser Compatibility
|  |  |  |  |  |  |
onplaying
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onplaying="myScript">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onplaying"
event to a video element.</p>
<p>Play, pause and then play the video again.</p>
<video controls onplaying="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2 s . c o m-->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML =
"The video is now playing";
}
</script>
</body>
</html>
In JavaScript:
object.onplaying = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "onplaying"
event to a video element.</p>
<p>Play, pause and then play the video again.</p>
<video controls id="myVideo">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2 s . c o m -->
<p id='demo'></p>
<script>
document.getElementById("myVideo").onplaying = function() {myFunction()};
function myFunction() {
document.getElementById('demo').innerHTML =
"The video is now playing";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("playing",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to
attach a "playing" event to a video element.</p>
<p>Play, pause and then play the video again.</p>
<video controls id="myVideo">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2 s . c o m -->
<p id='demo'></p>
<script>
document.getElementById("myVideo").addEventListener("playing", myFunction);
function myFunction() {
document.getElementById('demo').innerHTML =
"The video is now playing";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <audio> and <video> |
DOM Version: | Level 3 Events |
More Examples
Execute a JavaScript when an audio is ready to
start after having been paused:
<audio onplaying="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onplaying"
event to an audio element.</p>
<p>Play, pause and then play the audio again.</p>
<audio controls onplaying="myFunction()">
<source src="Bell.ogg" type="audio/ogg">
<source src="Bell.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio><!-- w w w . de m o2 s . c om -->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "The audio is now playing";
}
</script>
</body>
</html>
onprogress Event
Example
Execute a JavaScript when the video is downloading:
<video onprogress="myFunction()">
Open in separate window
View full source code
<html>
<body>
<video controls onprogress="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<script>
function myFunction() {
alert("Downloading video");
}
</script>
</body>
</html>
Description
The onprogress event occurs when the browser is downloading
the specified audio/video.
Browser Compatibility
|  |  |  |  |  |  |
onprogress
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onprogress="myScript">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onprogress" event
to a video element.</p>
<video controls onprogress="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2 s . c om -->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "Downloading video";
}
</script>
</body>
</html>
In JavaScript:
object.onprogress = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "onprogress"
event to a video element.</p>
<video controls id="myVideo">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2 s. c o m -->
<p id='demo'></p>
<script>
document.getElementById("myVideo").onprogress = function() {myFunction()};
function myFunction() {
document.getElementById('demo').innerHTML = "Downloading video";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("progress",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to attach
a "progress" event to a video element.</p>
<video controls id="myVideo">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2s . c om -->
<p id='demo'></p>
<script>
document.getElementById("myVideo").addEventListener("progress", myFunction);
function myFunction() {
document.getElementById('demo').innerHTML = "Downloading video";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <audio>, <video> |
DOM Version: | Level 3 Events |
More Examples
Execute a JavaScript when the audio is downloading:
<audio onprogress="myFunction()">
Open in separate window
View full source code
<html>
<body>
<audio controls onprogress="myFunction()">
<source src="Bell.ogg" type="audio/ogg">
<source src="Bell.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "Downloading audio";
}
</script>
</body>
</html>
onratechange Event
Example
Execute a JavaScript when the playing speed of the video is changed:
<video onratechange="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>In this example, we assign an "onratechange" event to a video element.
The playbackRate property is used to change the playing speed of
the video.</p>
<video id="myVideo" width="320" height="240"
autoplay controls onratechange="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support the video tag.
</video><br>
<button onclick="setPlaySpeed()" type="button">
Set video to be play in slow motion</button>
<p id='demo'></p>
<script>
let x = document.getElementById("myVideo");
function setPlaySpeed() {<!-- w w w .d e m o 2 s . c om -->
x.playbackRate = 0.3;
}
function myFunction() {
document.getElementById('demo').innerHTML =
"The playing speed of the video was changed";
}
</script>
</body>
</html>
Description
The onratechange event occurs when the playing speed of
the audio/video is changed.
This event is invoked by the playbackRate
property of the Audio/Video Object, which gets and sets
the current playback speed of an audio/video.
Browser Compatibility
|  |  |  |  |  |  |
onratechange
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onratechange="myScript">
Open in separate window
View full source code
<html>
<body>
<p>In this example, we assign an "onratechange" event
to a video element. The playbackRate property is used to
change the playing speed of the video.</p>
<video id="myVideo" width="320" height="240"
autoplay controls onratechange="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support the video tag.
</video><br>
<button onclick="setPlaySpeed()" type="button">
Set video to be play in slow motion</button>
<p id='demo'></p>
<script>
let x = document.getElementById("myVideo");
function setPlaySpeed() {<!-- w w w. d e m o 2 s . c o m -->
x.playbackRate = 0.3;
}
function myFunction() {
document.getElementById('demo').innerHTML =
"The playing speed of the video was changed";
}
</script>
</body>
</html>
In JavaScript:
object.onratechange = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>In this example, we use the HTML DOM to assign an "onratechange"
event to a video element. The playbackRate property is used to change
the playing speed of the video.</p>
<video id="myVideo" width="320" height="240" autoplay controls>
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support the video tag.
</video><br>
<button onclick="setPlaySpeed()" type="button">
Set video to be play in slow motion</button>
<p id='demo'></p>
<script>
let x = document.getElementById("myVideo");
function setPlaySpeed() {<!-- w w w . d e m o2 s . c o m -->
x.playbackRate = 0.3;
}
x.onratechange = function() {myFunction()};
function myFunction() {
document.getElementById('demo').innerHTML =
"The playing speed of the video was changed";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("ratechange",myScript);
Open in separate window
View full source code
<html>
<body>
<p>In this example, we use the addEventListener() method to
attach a "ratechange" event to a video element.
The playbackRate property is used to change the playing
speed of the video.</p>
<video id="myVideo" width="320" height="240" autoplay controls>
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support the video tag.
</video><br>
<button onclick="setPlaySpeed()" type="button">
Set video to be play in slow motion</button>
<p id='demo'></p>
<script>
let x = document.getElementById("myVideo");
function setPlaySpeed() {<!-- w w w . de m o 2 s . c o m-->
x.playbackRate = 0.3;
}
x.addEventListener("ratechange", myFunction);
function myFunction() {
document.getElementById('demo').innerHTML =
"The playing speed of the video was changed";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <audio> and <video> |
DOM Version: | Level 3 Events |
onreset Event
Example
Execute a JavaScript when a form is reset:
<form onreset="myFunction()">
Enter name: <input type="text">
<input type="reset">
</form>
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "The form was reset";
}
</script>
Open in separate window
View full source code
<html>
<body>
<p>When you reset the form, a function is triggered
which alerts some text.</p>
<form onreset="myFunction()">
Enter name: <input type="text">
<input type="reset">
</form>
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "The form was reset";
}
</script>
</body>
</html>
Description
The onreset event occurs when a form is reset.
Browser Compatibility
|  |  |  |  |  |  |
onreset
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onreset="myScript">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onreset"
event to a form element.</p>
<p>When you reset the form, a function is triggered
which outputs some text.</p>
<form onreset="myFunction()">
Enter name: <input type="text">
<input type="reset">
</form><!-- ww w . d e m o 2 s . c o m -->
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "The form was reset";
}
</script>
</body>
</html>
In JavaScript:
object.onreset = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "onreset"
event to a form element.</p>
<p>When you reset the form, a function is triggered
which outputs some text.</p>
<form id="myForm">
Enter name: <input type="text">
<input type="reset">
</form><!-- w w w . d e mo 2 s . co m-->
<p id="demo"></p>
<script>
document.getElementById("myForm").onreset = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "The form was reset";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("reset",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to
attach a "reset" event to a form element.</p>
<p>When you reset the form, a function is triggered
which outputs some text.</p>
<form id="myForm">
Enter name: <input type="text">
<input type="reset">
</form><!-- w w w . d e m o 2 s . co m -->
<p id="demo"></p>
<script>
document.getElementById("myForm").addEventListener("reset", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "The form was reset";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | Yes |
Cancelable: | Yes |
Event type: | Event |
Supported HTML tags: | <form> |
DOM Version: | Level 2 Events |
More Examples
Display the text that was inserted in a text field before it was reset:
let x = document.getElementById("myInput");
console.log("Before reset, the text was: " + x.value);
Open in separate window
View full source code
<html>
<body>
<p>Write something in the text field and press the Reset button.</p>
<form onreset="myFunction()">
<input type="text" id="myInput">
<input type="reset">
</form><!-- w w w .d e mo 2 s . co m-->
<p id='demo'></p>
<script>
function myFunction() {
let x = document.getElementById("myInput");
document.getElementById('demo').innerHTML =
"Before reset, the text was: " + x.value;
}
</script>
</body>
</html>
Example
Using the reset() method of the HTML DOM Form Object to
reset the form.
<form id="myForm" onreset="myAlertFunction()">
First name: <input type="text" name="fname">
<input type="button" onclick="myResetFunction()" value="Reset form">
</form>
<p id='demo'></p>
<script>
function myResetFunction() {
document.getElementById("myForm").reset();
}
// Alert some text when the form is reset
function myAlertFunction() {
document.getElementById('demo').innerHTML = "The form was reset";
}
</script>
Open in separate window
View full source code
<html>
<body>
<p>Enter some text in the field below, then press the "Reset form"
button to reset the form.</p>
<form id="myForm" onreset="myAlertFunction()">
First name: <input type="text" name="fname">
<input type="button" onclick="myResetFunction()" value="Reset form">
</form><!-- w w w . d e m o 2 s . c o m -->
<p id='demo'></p>
<script>
function myResetFunction() {
document.getElementById("myForm").reset();
}
// Alert some text when the form is reset
function myAlertFunction() {
document.getElementById('demo').innerHTML = "The form was reset";
}
</script>
</body>
</html>
onresize Event
Example
Execute a JavaScript when the browser window is resized:
<body onresize="myFunction()">
Open in separate window
View full source code
<html>
<body onresize="myFunction()">
<p>Try to resize the browser window to display the
windows height and width.</p>
<p id="demo"></p>
<script>
function myFunction() {
let w = window.outerWidth;
let h = window.outerHeight;
let txt = "Window size: width=" + w + ", height=" + h;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Description
The onresize event occurs when the browser window has been resized.
To get the size of an element, use the clientWidth, clientHeight,
innerWidth, innerHeight, outerWidth, outerHeight, offsetWidth and/or
offsetHeight properties.
Browser Compatibility
|  |  |  |  |  |  |
onresize
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onresize="myScript">
Open in separate window
View full source code
<html>
<body onresize="myFunction()">
<p>This example demonstrates how to assign an "onresize"
event to a body element.</p>
<p>Try to resize the browser window.</p>
<p>Window resized <span id="demo">0</span> times.</p>
<script>
let x = 0;<!-- w w w . de m o2 s . c o m -->
function myFunction() {
let txt = x += 1;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
In JavaScript:
object.onresize = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "onresize"
event to the body element.</p>
<p>Try to resize the browser window.</p>
<p>Window resized <span id="demo">0</span> times.</p>
<script>
document.getElementsByTagName("BODY")[0].onresize =
function() {myFunction()};
let x = 0;<!-- w w w . d e m o 2 s . c om -->
function myFunction() {
let txt = x += 1;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("resize",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to attach
a "resize" event on the window object.</p>
<p>Try to resize the browser window.</p>
<p>Window resized <span id="demo">0</span> times.</p>
<script>
window.addEventListener("resize", myFunction);
let x = 0;<!-- w w w. de m o2 s . c o m-->
function myFunction() {
let txt = x += 1;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | UiEvent if generated from a user interface, Event otherwise |
Supported HTML tags: | <body> |
DOM Version: | Level 2 Events |
More Examples
Using the addEventListener() method to attach the "resize" event
on the window object.
window.addEventListener("resize", myFunction);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to attach a "resize"
event on the window object.</p>
<p>Try to resize the browser window.</p>
<p>Window resized <span id="demo">0</span> times.</p>
<script>
window.addEventListener("resize", myFunction);
let x = 0;<!-- w w w .d e m o 2 s . c o m-->
function myFunction() {
let txt = x += 1;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
onscroll Event
Example
Execute a JavaScript when a <div> element is being scrolled:
<div onscroll="myFunction()">
Open in separate window
View full source code
<html>
<head>
<style>
div {<!-- w w w . d e m o 2 s . c o m -->
border: 1px solid black;
width: 200px;
height: 100px;
overflow: scroll;
}
</style>
</head>
<body>
<p>Try the scrollbar in div.</p>
<div onscroll="myFunction()">
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
</div>
<p>Scrolled <span id="demo">0</span> times.</p>
<script>
let x = 0;
function myFunction() {
document.getElementById("demo").innerHTML = x += 1;
}
</script>
</body>
</html>
Description
The onscroll event occurs when an element's scrollbar is being scrolled.
Use the CSS overflow style property to create a scrollbar for an element.
Browser Compatibility
|  |  |  |  |  |  |
onscroll
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onscroll="myScript">
Open in separate window
View full source code
<html>
<head>
<style>
div {<!-- w ww . d e m o 2 s . c om -->
border: 1px solid black;
width: 200px;
height: 100px;
overflow: scroll;
}
</style>
</head>
<body>
<p>Try the scrollbar in div.</p>
<div onscroll="myFunction()">
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
</div>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "You scrolled in div.";
}
</script>
</body>
</html>
In JavaScript:
object.onscroll = function(){myScript};
Open in separate window
View full source code
<html>
<head>
<style>
div {<!-- w w w . d e m o 2 s . c o m-->
border: 1px solid black;
width: 200px;
height: 100px;
overflow: scroll;
}
</style>
</head>
<body>
<p>This example uses the HTML DOM to assign an "onscroll"
event to a div element.</p>
<p>Try the scrollbar in the div</p>
<div id="myDIV">
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
</div>
<p id="demo"></p>
<script>
document.getElementById("myDIV").onscroll = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = "You scrolled in div.";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("scroll",myScript);
Open in separate window
View full source code
<html>
<head>
<style>
div {<!-- w w w . d e m o 2 s .c o m -->
border: 1px solid black;
width: 200px;
height: 100px;
overflow: scroll;
}
</style>
</head>
<body>
<p>This example uses the addEventListener() method to attach
a "scroll" event to a div element.</p>
<p>Try the scrollbar in the div</p>
<div id="myDIV">
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
test<br>
</div>
<p id="demo"></p>
<script>
document.getElementById("myDIV").addEventListener("scroll", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "You scrolled in div.";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | UiEvent if generated from a user interface, Event otherwise |
Supported HTML tags:
| <address>, <blockquote>, <body>, <caption>, <center>, <dd>, <dir>, <div>, <dl>, <dt>, <fieldset>, <form>, <h1> to <h6>, <html>, <li>, <menu>, <object>, <ol>, <p>, <pre>, <select>, <tbody>, <textarea>, <tfoot>, <thead>, <ul> |
DOM Version: | Level 2 Events |
More Examples
Toggle between class names on different scroll positions - When the
user scrolls down 50 pixels from the top of the page, the class name
"test" will be added to an element and removed when scrolled up again.
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 50 ||
document.documentElement.scrollTop > 50) {
document.getElementById("myP").className = "test";
} else {
document.getElementById("myP").className = "";
}
}
Open in separate window
View full source code
<html>
<head>
<style>
.test {<!-- ww w . d e m o 2 s . c o m -->
background-color: yellow;
}
</style>
</head>
<body style="height:1500px">
<p>Scroll down this page</p>
<p id="myP" style="position:fixed">
When you have scrolled 50 pixels from the top of this page, add the
class "test" to this paragraph.
Scroll up again to remove the class.
</p>
<script>
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 50 ||
document.documentElement.scrollTop > 50) {
document.getElementById("myP").className = "test";
} else {
document.getElementById("myP").className = "";
}
}
</script>
</body>
</html>
Example
Slide in an element when the user has scrolled down 350 pixels
from the top of the page:
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 350 ||
document.documentElement.scrollTop > 350) {
document.getElementById("myImg").className = "slideUp";
}
}
Open in separate window
View full source code
<html>
<head>
<style>
.slideUp {<!-- w w w. d e m o 2 s . c o m-->
animation-name: slideUp;
-webkit-animation-name: slideUp;
animation-duration: 1s;
-webkit-animation-duration: 1s;
visibility: visible;
}
@keyframes slideUp {
0% {
opacity: 0;
-webkit-transform: translateY(70%);
}
100% {
opacity: 1;
-webkit-transform: translateY(0%);
}
}
@-webkit-keyframes slideUp {
0% {
opacity: 0;
-webkit-transform: translateY(70%);
}
100% {
opacity: 1;
-webkit-transform: translateY(0%);
}
}
body {height:1500px;}
.col-1 {float:left}
.col-2 {float:left;padding-left:25px;}
img {width:180px;height:100px;visibility:hidden;}
hr {margin-top:400px;}
</style>
</head>
<body>
<p>Scroll down this page.</p>
<p>When you have scrolled 350px from the top,
an image will slide in.</p>
<hr>
<div class="col-1">
<img id="myImg" src="html.png" width="304" height="228">
</div>
<div class="col-2">
Just some text..
</div>
<script>
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 350 ||
document.documentElement.scrollTop > 350) {
document.getElementById("myImg").className = "slideUp";
}
}
</script>
</body>
</html>
onsearch Event
Example
Execute a JavaScript when submitting a search:
<input type="search" onsearch="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>Write something in the search field and press "ENTER".</p>
<input type="search" id="myInput" onsearch="myFunction()">
<p id="demo"></p>
<script>
function myFunction() {
let x = document.getElementById("myInput");
document.getElementById("demo").innerHTML =
"You are searching for: " + x.value;
}
</script>
</body>
</html>
Description
The onsearch event occurs when a user presses the "ENTER"
key or clicks the "x" button in an <input> element with type="search".
onsearch is Not supported by major browsers.
Syntax
In HTML:
<element onsearch="myScript">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onsearch"
event to an input element.</p>
<p>Write something in the search field and press "ENTER".</p>
<input type="search" id="myInput" onsearch="myFunction()">
<p id="demo"></p>
<script>
function myFunction() {<!-- ww w . d em o 2 s . co m -->
let x = document.getElementById("myInput");
document.getElementById("demo").innerHTML =
"You are searching for: " + x.value;
}
</script>
</body>
</html>
In JavaScript:
object.onsearch = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "onsearch" event to an input
element.</p>
<p>Write something in the search field and press "ENTER".</p>
<input type="search" id="myInput">
<p id="demo"></p>
<script>
document.getElementById("myInput").onsearch = function() {myFunction()};
function myFunction() {<!-- w w w .d em o 2 s . c o m -->
let x = document.getElementById("myInput");
document.getElementById("demo").innerHTML =
"You are searching for: " + x.value;
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("search",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to attach
a "search" event to an input element.</p>
<p>Write something in the search field and press "ENTER".</p>
<input type="search" id="myInput">
<p id="demo"></p>
<script>
document.getElementById("myInput").addEventListener("search", myFunction);
function myFunction() {<!-- w w w . d e mo 2 s .c o m -->
let x = document.getElementById("myInput");
document.getElementById("demo").innerHTML =
"You are searching for: " + x.value;
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <input type="search"> |
DOM Version: | Level 3 Events |
onseeked Event
Example
Execute a JavaScript when the user is finished moving/skipping
to a new position in the video:
<video onseeked="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onseeked" event
to a video element.</p>
<p>Move to a new position in the video.</p>
<video controls onseeked="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w. d e m o 2 s . c o m-->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "Seek operation completed!";
}
</script>
</body>
</html>
Description
The onseeked event occurs when the user is finished moving or skipping
to a new position in the audio/video
The onseeked event is the opposite of the onseeking event.
Use the currentTime property of the Audio/Video Object to get the
current playback position.
Browser Compatibility
|  |  |  |  |  |  |
onseeked
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onseeked="myScript">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onseeked" event to a
video element.</p>
<p>Move to a new position in the video.</p>
<video controls onseeked="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- ww w. d e m o 2 s. c o m-->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "Seek operation completed!";
}
</script>
</body>
</html>
In JavaScript:
object.onseeked = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "onseeked" event
to a video element.</p>
<p>Move to a new position in the video.</p>
<video controls id="myVideo">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e mo 2 s . c om -->
<p id='demo'></p>
<script>
document.getElementById("myVideo").onseeked = function() {myFunction()};
function myFunction() {
document.getElementById('demo').innerHTML =
"Seek operation completed!";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("seeked",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to attach
a "seeked" event to a video element.</p>
<p>Move to a new position in the video.</p>
<video controls id="myVideo">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w. d e m o 2 s . c o m -->
<p id='demo'></p>
<script>
document.getElementById("myVideo").addEventListener("seeked", myFunction);
function myFunction() {
document.getElementById('demo').innerHTML = "Seek operation completed!";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <audio> and <video> |
DOM Version: | Level 3 Events |
More Examples
This example demonstrates the difference between the onseeking event
and onseeked event:
<video onseeking="myFunction()" onseeked="mySecondFunction()">
This example shows the difference between the onseeking
event and onseeked event.
The onseeking event occurs everytime the user STARTS moving/skipping to
a new position in the audio/video.
The onseeked event occurs when the user is FINISHED moving/skipping
to a new position in the audio/video</p>
Open in separate window
View full source code
<html>
<body>
<p>Move to a new position in the video.
</p><!-- w w w. d e m o 2 s .c om -->
<video controls onseeking="myFunction()" onseeked="mySecondFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<p>seeking occurred: <span id="demo"></span> times.</p>
<p>seeked occurred: <span id="demo2"></span> times.</p>
<script>
x = 0;
function myFunction() {
document.getElementById("demo").innerHTML = x += 1;
}
y = 0;
function mySecondFunction() {
document.getElementById("demo2").innerHTML = y += 1;
}
</script>
</body>
</html>
Example
Using the currentTime property of the Video Object to display
the current playtime position when the user is finished moving/skipping to
a new position:
<script>
let x = document.getElementById("myVideo");
x.addEventListener("seeked", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = x.currentTime;
}
</script>
Open in separate window
View full source code
<html>
<body>
<p>In this example, we attach a "seeked" event to the video element.
The currentTime property returns the current position (in seconds) of
the video playback.</p>
<p>Move to a new position in the video.</p>
<video id="myVideo" controls>
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- ww w . d e m o 2 s . c o m-->
<p>Seeked to position: <span id="demo"></span></p>
<script>
let x = document.getElementById("myVideo");
x.addEventListener("seeked", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = x.currentTime;
}
</script>
</body>
</html>
Example
Execute a JavaScript when the user is finished moving/skipping to
a new position in the audio:
<audio onseeked="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onseeked" event to
an audio element.</p>
<p>Move to a new position in the video.</p>
<audio controls onseeked="myFunction()">
<source src="Bell.ogg" type="audio/ogg">
<source src="Bell.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio><!-- w w w . de mo 2 s .c o m -->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "Seek operation completed!";
}
</script>
</body>
</html>
onseeking Event
Example
Execute a JavaScript when the user starts moving/skipping to a new
position in the video:
<video onseeking="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onseeking" event
to a video element.</p>
<p>Move to a new position in the video.</p>
<video controls onseeking="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d em o2 s . c o m-->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "Seek operation began!";
}
</script>
</body>
</html>
Description
The onseeking event occurs when the user starts moving/skipping
to a new position in the audio/video.
The onseeking event is the opposite of the onseeked event.
Use the currentTime property of the Audio/Video Object to get
the current playback position.
Browser Compatibility
|  |  |  |  |  |  |
onseeking
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onseeking="myScript">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onseeking" event to
a video element.</p>
<p>Move to a new position in the video.</p>
<video controls onseeking="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2 s . co m-->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "Seek operation began!";
}
</script>
</body>
</html>
In JavaScript:
object.onseeking = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "onseeking" event
to a video element.</p>
<p>Move to a new position in the video.</p>
<video controls id="myVideo">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . de m o 2 s . c o m -->
<p id='demo'></p>
<script>
document.getElementById("myVideo").onseeking = function() {myFunction()};
function myFunction() {
document.getElementById('demo').innerHTML = "Seek operation began!";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("seeking",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to attach
a "seeking" event to a video element.</p>
<p>Move to a new position in the video.</p>
<video controls id="myVideo">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d em o 2 s . c o m -->
<p id='demo'></p>
<script>
document.getElementById("myVideo").addEventListener("seeking", myFunction);
function myFunction() {
document.getElementById('demo').innerHTML = "Seek operation began!";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <audio> and <video> |
DOM Version: | Level 3 Events |
More Examples
This example demonstrates the difference between the onseeking event
and onseeked event:
<video onseeking="myFunction()" onseeked="mySecondFunction()">
Open in separate window
View full source code
<html>
<body>
<p>This example shows the difference between the onseeking event
and onseeked event.</p>
<p>Move to a new position in the video.
</p><!-- w w w . d e mo 2 s . c om -->
<video controls onseeking="myFunction()" onseeked="mySecondFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<p>seeking occurred: <span id="demo"></span> times.</p>
<p>seeked occurred: <span id="demo2"></span> times.</p>
<script>
x = 0;
function myFunction() {
document.getElementById("demo").innerHTML = x += 1;
}
y = 0;
function mySecondFunction() {
document.getElementById("demo2").innerHTML = y += 1;
}
</script>
</body>
</html>
Example
Using the currentTime property of the Video Object to display
the current playtime position when the user starts to skip to a
new position:
<script>
let x = document.getElementById("myVideo");
x.addEventListener("seeking", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = x.currentTime;
}
</script>
Open in separate window
View full source code
<html>
<body>
<p>Move to a new position in the video.</p>
<video id="myVideo" controls>
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w. d em o 2 s . c o m -->
<p>Seeked to position: <span id="demo"></span></p>
<script>
let x = document.getElementById("myVideo");
x.addEventListener("seeking", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = x.currentTime;
}
</script>
</body>
</html>
Example
Execute a JavaScript when the user starts moving/skipping to a
new position in the audio:
<audio onseeking="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onseeking" event to
an audio element.</p>
<p>Move to a new position in the video.</p>
<audio controls onseeking="myFunction()">
<source src="Bell.ogg" type="audio/ogg">
<source src="Bell.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio><!-- w w w . d em o 2 s . c o m-->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "Seek operation began!";
}
</script>
</body>
</html>
onselect Event
Example
Execute a JavaScript when some text has been selected:
<input type="text" onselect="myFunction()">
Open in separate window
View full source code
<html>
<body>
Select some of the text:
<input type="text" value="Hello world!" onselect="myFunction()">
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "You selected some text!";
}
</script>
</body>
</html>
Description
The onselect event occurs after some text has been selected in an element.
The onselect event is mostly used on
<input type="text"> or <textarea> elements.
Browser Compatibility
|  |  |  |  |  |  |
onselect
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onselect="myScript">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onselect" event
to an input element.</p>
Select some text:
<input type="text" value="Hello world!" onselect="myFunction()">
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "You selected some text!";
}
</script>
</body>
</html>
In JavaScript:
object.onselect = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "onselect" event to
an input element.</p>
Select some text: <input type="text" value="Hello world!" id="myText">
<p id="demo"></p>
<script>
document.getElementById("myText").onselect = function() {myFunction()};
function myFunction() {<!-- w w w . d e m o 2 s . c o m-->
document.getElementById("demo").innerHTML = "You selected some text!";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("select",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to attach
a "select" event to an input element.</p>
Select some text:
<input type="text" value="Hello world!" id="myText">
<p id="demo"></p>
<script>
document.getElementById("myText").addEventListener("select", myFunction);
function myFunction() {<!-- w w w . d em o 2 s . c o m-->
document.getElementById("demo").innerHTML = "You selected some text!";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | UiEvent if generated from a user interface, Event otherwise |
Supported HTML tags:
| <input type="file">, <input type="password">, <input type="text">, and <textarea> |
DOM Version: | Level 2 Events |
More Examples
Using the select() method of the HTML DOM Input Text Object to
select some content of a text field.
<script>
function mySelectFunction() {
document.getElementById("myText").select();
}
function myAlertFunction() {
document.getElementById('demo').innerHTML = "You selected some text!";
}
</script>
Open in separate window
View full source code
<html>
<body>
<input type="text" id="myText" value="Some text.."
onselect="myAlertFunction()">
<p>Click the button to select the contents of the text field.</p>
<button type="button" onclick="mySelectFunction()">Select content</button>
<p id='demo'></p>
<script>
function mySelectFunction() {<!-- w w w . d e m o2 s . c o m -->
document.getElementById("myText").select();
}
function myAlertFunction() {
document.getElementById('demo').innerHTML = "You selected some text!";
}
</script>
</body>
</html>
onshow Event
Example
Execute a JavaScript when a <menu> element is shown as a context menu:
<menu type="context" id="mymenu" onshow="myFunction()">
<menuitem label="Refresh"
onclick="window.location.reload();"
icon="css.png"></menuitem>
<menu label="Share on...">
<menuitem label="Twitter"
icon="html.png"
onclick="window.open(window.location.href);"></menuitem>
<menuitem label="Facebook"
icon="javascript.png"
onclick="window.open(window.location.href);"></menuitem>
</menu>
<menuitem label="Email This Page"
onclick="window.location='mailto:?body='+window.location.href;">
</menuitem>
</menu>
Open in separate window
View full source code
<html>
<head>
<style>
div {<!-- w w w . d e m o 2 s . c o m -->
background: yellow;
border: 1px solid #cccccc;
padding: 10px;
}
</style>
</head>
<body>
<p>This example demonstrates how to assign an "onshow"
event to a menu element.</p>
<div contextmenu="mymenu">
<p>Right-click inside this box to see the context menu!
<menu type="context" id="mymenu" onshow="myFunction()">
<menuitem label="Refresh"
onclick="window.location.reload();"
icon="css.png"></menuitem>
<menu label="Share on...">
<menuitem label="Twitter"
icon="html.png"
onclick="window.open(window.location.href);"></menuitem>
<menuitem label="Facebook"
icon="javascript.png"
onclick="window.open(window.location.href);"></menuitem>
</menu>
<menuitem label="Email This Page"
onclick="window.location='mailto:?body='+window.location.href;">
</menuitem>
</menu>
</div>
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML =
"The context menu is about to be shown";
}
</script>
</body>
</html>
Description
The onshow event occurs when a <menu> element is shown as a context menu.
The onshow event is currently only supported in Firefox.
Syntax
In HTML:
<element onshow="myScript">
Open in separate window
View full source code
<html>
<head>
<style>
div {<!-- w w w . d e m o 2 s . c o m-->
background: yellow;
border: 1px solid #cccccc;
padding: 10px;
}
</style>
</head>
<body>
<p>This example demonstrates how to assign an "onshow"
event to a menu element.</p>
<div contextmenu="mymenu">
<p>Right-click inside this box to see the context menu!
<menu type="context" id="mymenu" onshow="myFunction()">
<menuitem label="Refresh"
onclick="window.location.reload();"
icon="css.png"></menuitem>
<menu label="Share on...">
<menuitem label="Twitter"
icon="html.png"
onclick="window.open(window.location.href);"></menuitem>
<menuitem label="Facebook"
icon="javascript.png"
onclick="window.open(window.location.href);"></menuitem>
</menu>
<menuitem label="Email This Page"
onclick="window.location='mailto:?body='+window.location.href;">
</menuitem>
</menu>
</div>
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML =
"The context menu is about to be shown";
}
</script>
</body>
</html>
In JavaScript:
object.onshow = function(){myScript};
Open in separate window
View full source code
<html>
<head>
<style>
div {<!-- w w w. d e m o 2 s . c o m -->
background: yellow;
border: 1px solid #cccccc;
padding: 10px;
}
</style>
</head>
<body>
<p>This example uses the HTML DOM to assign an "onshow"
event to a menu element.</p>
<div contextmenu="mymenu">
<p>Right-click inside this box to see the context menu!
<menu type="context" id="mymenu" onshow="myFunction()">
<menuitem label="Refresh"
onclick="window.location.reload();"
icon="css.png"></menuitem>
<menu label="Share on...">
<menuitem label="Twitter"
icon="html.png"
onclick="window.open(window.location.href);"></menuitem>
<menuitem label="Facebook"
icon="javascript.png"
onclick="window.open(window.location.href);"></menuitem>
</menu>
<menuitem label="Email This Page"
onclick="window.location='mailto:?body='+window.location.href;">
</menuitem>
</menu>
</div>
<p id='demo'></p>
<script>
document.getElementById("mymenu").onshow = function() {myFunction()};
function myFunction() {
document.getElementById('demo').innerHTML =
"The context menu is about to be shown";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("show",
myScript);
Open in separate window
View full source code
<html>
<head>
<style>
div {<!-- w w w .d e mo 2 s . c o m -->
background: yellow;
border: 1px solid #cccccc;
padding: 10px;
}
</style>
</head>
<body>
<p>This example uses the addEventListener() method to attach a "show"
event to a menu element.</p>
<div contextmenu="mymenu">
<p>Right-click inside this box to see the context menu!
<menu type="context" id="mymenu" onshow="myFunction()">
<menuitem label="Refresh"
onclick="window.location.reload();"
icon="css.png"></menuitem>
<menu label="Share on...">
<menuitem label="Twitter"
icon="html.png"
onclick="window.open(window.location.href);"></menuitem>
<menuitem label="Facebook"
icon="javascript.png"
onclick="window.open(window.location.href);"></menuitem>
</menu>
<menuitem label="Email This Page"
onclick="window.location='mailto:?body='+window.location.href;">
</menuitem>
</menu>
</div>
<p id='demo'></p>
<script>
document.getElementById("mymenu").addEventListener("show", myFunction);
function myFunction() {
document.getElementById('demo').innerHTML =
"The context menu is about to be shown";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <menu> |
DOM Version: | Level 3 Events |
onstalled Event
Example
Execute a JavaScript when the browser is trying to get media data,
but data is not available:
<video onstalled="myFunction()">
Description
The onstalled event occurs when the browser is trying to get media data,
but data is not available.
Browser Compatibility
|  |  |  |  |  |  |
onstalled
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onstalled="myScript">
In JavaScript:
object.onstalled = function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("stalled",myScript);
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <audio> and <video> |
DOM Version: | Level 3 Events |
onsubmit Event
Example
Execute a JavaScript when a form is submitted:
<form action="/action_page.php" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Open in separate window
View full source code
<html>
<body>
<p>When you submit the form, a function is
triggered which alerts some text.</p>
<form action="/action_page.php" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "The form was submitted";
}
</script>
</body>
</html>
Description
The onsubmit event occurs when a form is submitted.
Browser Compatibility
|  |  |  |  |  |  |
onsubmit
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onsubmit="myScript">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onsubmit" event
to a form element.</p>
<p>When you submit the form, a function is triggered
which alerts some text.</p>
<form action="/action_page.php" onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form><!-- ww w . d e m o 2s . c o m -->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "The form was submitted";
}
</script>
</body>
</html>
In JavaScript:
object.onsubmit = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "onsubmit"
event to a form element.</p>
<p>When you submit the form, a function is triggered
which alerts some text.</p>
<form id="myForm" action="/action_page.php">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form><!-- w w w . d e m o 2 s . c o m -->
<p id='demo'></p>
<script>
document.getElementById("myForm").onsubmit = function() {myFunction()};
function myFunction() {
document.getElementById('demo').innerHTML = "The form was submitted";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("submit",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to
attach a "submit" event to a form element.</p>
<p>When you submit the form, a function is triggered
which alerts some text.</p>
<form id="myForm" action="/action_page.php">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form><!-- w w w . d e m o 2s . co m-->
<p id='demo'></p>
<script>
document.getElementById("myForm").addEventListener("submit", myFunction);
function myFunction() {
document.getElementById('demo').innerHTML = "The form was submitted";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | Yes |
Cancelable: | Yes |
Event type: | Event |
Supported HTML tags: | <form> |
DOM Version: | Level 2 Events |
onsuspend Event
Example
Execute a JavaScript when the browser is intentionally not
getting media data:
<video onsuspend="myFunction()">
Description
The onsuspend event occurs when the browser is
intentionally not getting media data.
This event occurs when the loading of the media is suspended.
This can happen when the download has completed,
or because it has been paused for some reason.
Browser Compatibility
|  |  |  |  |  |  |
onsuspend
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onsuspend="myScript">
In JavaScript:
object.onsuspend = function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("suspend",myScript);
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <audio> and <video> |
DOM Version: | Level 3 Events |
ontimeupdate Event
Example
Execute a JavaScript when the current playback position has changed:
<video ontimeupdate="myFunction()">
Open in separate window
View full source code
<html>
<body>
<video controls ontimeupdate="myFunction(this)">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<p>Playback position: <span id="demo"></span></p>
<script>
function myFunction(event) {
document.getElementById("demo").innerHTML = event.currentTime;
}
</script>
</body>
</html>
Description
The ontimeupdate event occurs when the playing position of an
audio/video has changed.
This event is invoked by:
Playing the audio/video
Moving the playback position
The ontimeupdate event is often used together with the currentTime
property of the Audio/Video Object, which returns the current position of
the audio/video playback, in seconds.
Browser Compatibility
|  |  |  |  |  |  |
ontimeupdate
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element ontimeupdate="myScript">
Open in separate window
View full source code
<html>
<body>
<video controls ontimeupdate="myFunction(this)">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2 s . c om -->
<p>Playback position: <span id="demo"></span></p>
<script>
function myFunction(event) {
document.getElementById("demo").innerHTML = event.currentTime;
}
</script>
</body>
</html>
In JavaScript:
object.ontimeupdate = function(){
myScript};
Open in separate window
View full source code
<html>
<body>
<video id="myVideo" controls>
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- ww w . d e mo 2 s . c o m-->
<p>Playback position: <span id="demo"></span></p>
<script>
let x = document.getElementById("myVideo");
x.ontimeupdate = function() {myFunction()};
function myFunction() {
document.getElementById("demo").innerHTML = x.currentTime;
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("timeupdate",myScript);
Open in separate window
View full source code
<html>
<body>
<video id="myVideo" controls>
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2 s . co m -->
<p>Playback position: <span id="demo"></span></p>
<script>
let x = document.getElementById("myVideo");
x.addEventListener("timeupdate", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = x.currentTime;
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <audio> and <video> |
DOM Version: | Level 3 Events |
More Examples
Execute a JavaScript when the current playback position of
an audio has changed:
<audio ontimeupdate="myFunction()">
Open in separate window
View full source code
<html>
<body>
<audio controls ontimeupdate="myFunction(this)">
<source src="Bell.ogg" type="audio/ogg">
<source src="Bell.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<p>Playback position: <span id="demo"></span></p>
<script>
function myFunction(event) {
document.getElementById("demo").innerHTML = event.currentTime;
}
</script>
</body>
</html>
Example
Using the currentTime property to set the current playback position
to 5 seconds:
document.getElementById("myVideo").currentTime = 5;
Open in separate window
View full source code
<html>
<body>
<video id="myVideo" width="320" height="240" controls>
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support the video tag.
</video><br>
<button onclick="setCurTime()" type="button">Set time position
to 5 seconds</button>
<p id="demo"></p>
<script>
let x = document.getElementById("myVideo");
x.addEventListener("timeupdate", getCurTime);
function getCurTime() {<!-- w w w . d em o 2 s . c om -->
document.getElementById("demo").innerHTML =
"The current playback position is " + x.currentTime + " seconds.";
}
function setCurTime() {
x.currentTime = 5;
}
</script>
</body>
</html>
ontoggle Event
Example
Execute a JavaScript when a <details> element is opened or closed:
<details ontoggle="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>Open the details.</p>
<details ontoggle="myFunction()">
<summary>CSS</summary>
<p> test test.</p>
<p>test test test</p>
</details>
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "The ontoggle event occurred";
}
</script>
</body>
</html>
Description
The ontoggle event occurs when the user opens or
closes the <details> element.
The <details> element specifies additional details that the
user can view or hide on demand.
Browser Compatibility
|  |  |  |  |  |  |
ontoggle
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element ontoggle="myScript">
Open in separate window
View full source code
<html>
<body>
<p>Open the details.</p>
<details ontoggle="myFunction()">
<summary>CSS</summary>
<p> test test</p>
<p>test test</p>
</details>
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "The ontoggle event occurred";
}
</script>
</body>
</html>
In JavaScript:
object.ontoggle = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "ontoggle" event to
a details element.</p>
<p>Open the details.</p>
<details id="myDetails">
<summary>CSS</summary>
<p> test test test</p>
<p>test test test</p>
</details><!-- w w w . de m o 2 s . c o m -->
<p id='demo'></p>
<script>
document.getElementById("myDetails").ontoggle = function() {myFunction()};
function myFunction() {
document.getElementById('demo').innerHTML = "The ontoggle event occurred";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("toggle",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to
attach a "toggle" event to a details element.</p>
<p>Open the details.</p>
<details id="myDetails">
<summary>CSS</summary>
<p> test test test</p>
<p>test test test</p>
</details><!-- w w w . d e m o 2 s . c o m-->
<p id='demo'></p>
<script>
document.getElementById("myDetails").addEventListener("toggle", myFunction);
function myFunction() {
document.getElementById('demo').innerHTML = "The ontoggle event occurred.";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <details> |
DOM Version: | Level 3 Events |
onunload Event
Example
Execute a JavaScript when a user unloads the document:
<body onunload="myFunction()">
Open in separate window
View full source code
<html>
<body onunload="myFunction()">
<h1>Welcome to my Home Page</h1>
<p>Close this window or press F5 to reload the page.</p>
<script>
function myFunction() {
console.log("Thank you for visiting Demo2s.com!");
}
</script>
</body>
</html>
Description
The onunload event occurs once a page has unloaded or the browser
window has been closed.
onunload occurs when the user navigates away from the page
by clicking on a link, submitting a form, closing the browser window, etc.
The onunload event is also triggered when a user reloads the
page and the onload event.
Browser Compatibility
|  |  |  |  |  |  |
onunload
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onunload="myScript">
In JavaScript:
object.onunload = function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("unload",myScript);
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | UiEvent if generated from a user interface, Event otherwise. |
Supported HTML tags: | <body> |
DOM Version: | Level 2 Events |
onvolumechange Event
Example
Execute a JavaScript when the volume of a video has been changed:
<video onvolumechange="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onvolumechange"
event to a video element.</p>
<p>Try to change the volume in the bottom right corner.</p>
<video controls onvolumechange="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w ww . d e m o2 s . c o m -->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML =
"The volume has been changed!";
}
</script>
</body>
</html>
Description
The onvolumechange event occurs each time the volume of a
video/audio has been changed.
This event is invoked by:
Increasing or decreasing the volume
Muting or unmuting the media player
Use the volume property of the Audio/Video Object to set or return
the audio volume of an audio/video.
Browser Compatibility
|  |  |  |  |  |  |
onvolumechange
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
In HTML:
<element onvolumechange="myScript">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign an "onvolumechange"
event to a video element.</p>
<p>Try to change the volume in the bottom right corner.</p>
<video controls onvolumechange="myFunction()">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2 s . c o m -->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML =
"The volume has been changed!";
}
</script>
</body>
</html>
In JavaScript:
object.onvolumechange = function(){myScript};
Open in separate window
View full source code
<html>
<body>
<p>This example uses the HTML DOM to assign an "onvolumechange"
event to a video element.</p>
<p>Try to change the volume in the bottom right corner.</p>
<video controls id="myVideo">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w . d e m o 2 s .c o m -->
<p id='demo'></p>
<script>
document.getElementById("myVideo").onvolumechange =
function() {myFunction()};
function myFunction() {
document.getElementById('demo').innerHTML = "The volume has been changed!";
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
object.addEventListener("volumechange",myScript);
Open in separate window
View full source code
<html>
<body>
<p>This example uses the addEventListener() method to attach
a "volumechange" event to a video element.</p>
<p>Try to change the volume in the bottom right corner.</p>
<video controls id="myVideo">
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video><!-- w w w. d em o 2s . c o m-->
<p id='demo'></p>
<script>
document.getElementById("myVideo")
.addEventListener("volumechange", myFunction);
function myFunction() {
document.getElementById('demo').innerHTML = "The volume has been changed!";
}
</script>
</body>
</html>
Technical Details
Item | Value |
Bubbles: | No |
Cancelable: | No |
Event type: | Event |
Supported HTML tags: | <audio> and <video> |
DOM Version: | Level 3 Events |
More Examples
Execute a JavaScript when the volume of an audio has been changed:
<audio onvolumechange="myFunction()">
Open in separate window
View full source code
<html>
<body>
<p>This example demonstrates how to assign
an "onvolumechange" event to an audio element.</p>
<p>Try to change the volume in the bottom right corner.</p>
<audio controls onvolumechange="myFunction()">
<source src="Bell.ogg" type="audio/ogg">
<source src="Bell.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio><!-- w w w . d em o 2 s . c o m -->
<p id='demo'></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "The volume has been changed!";
}
</script>
</body>
</html>
Example
Using the volume property to set the volume:
document.getElementById("myVideo").volume = 0.2;
Open in separate window
View full source code
<html>
<body>
<video id="myVideo" width="320" height="240" controls>
<source src="radian.mp4" type="video/mp4">
<source src="radian.ogg" type="video/ogg">
Your browser does not support the video tag.
</video><!-- w w w . d e mo 2 s .c o m-->
<p>Change the volume by either clicking the buttons
or by adjusting the volume in the bottom right corner.</p>
<button onclick="setHalfVolume()" type="button">Set volume to 0.2</button>
<button onclick="setFullVolume()" type="button">Set volume to 1.0</button>
<p id="demo"></p>
<script>
let x = document.getElementById("myVideo");
x.addEventListener("volumechange", getVolume);
function getVolume() {
document.getElementById("demo").innerHTML =
"The audio volume is: " + x.volume;
}
function setHalfVolume() {
x.volume = 0.2;
}
function setFullVolume() {
x.volume = 1.0;
}
</script>
</body>
</html>