Window Object

 

The window object represents an open window in a browser.

If a document contain frames (<iframe> tags), the browser creates one window object for the HTML document, and one additional window object for each frame.

Properties

name

The name property sets or returns the name of the window.

A windows does not need to have a name.

indow.name = "myWindowName";

location

The location object contains information about the current URL.

The location object is a property of the window object.

let origin = window.location;

let origin = location;

Output: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_loc_origin1

document

When an HTML document is loaded into a web browser, it becomes a document object.

The document object is the root node of the HTML document.

The document object is a property of the window object.

console

Returns the Console Object for the window.

screen

Returns the Screen object for the window

history

The history object contains the URLs visited by the user (in the browser window).

The history object is a property of the window object.

frameElement

The frameElement property returns the frame where the window runs.

The frameElement property returns null if the window does not run in a frame.

The frameElement property is read only.

A frame can be any embedding element:

<frame>, <iframe>, <embed>, <object>, etc.

if (window.frameElement) {

let answer = "YES";

}

frames

The frames property returns an array with all window objects in the window.

The frames property is read-only.

The windows can be accessed by index numbers. The first index is 0.

window.frames[0].location = "https://www.w3schools.com/jsref/";

length

The length property returns the number of (framed) windows in the window.

The length property is read-only.

The windows can be accessed by index numbers. The first index is 0.

let length = window.length;

Output: 3

opener

The opener property returns a reference to the window that created the window. Window object

If window xxx opens window yyy:

yyy.opener

returns xxx.

yyy.opener.close()

closes xxx.

parent

The parent property returns the parent window (of the current window). Window object

The parent property is read-only.

The parent property is not the same as the top property.

window.parent returns the immediate parent of a window.

window.top returns the topmost window in the hierarchy of windows.

top

The top property returns the topmost window in the current browser window. Window object

The top property is read-only.

self

The self property returns the current window. Window object

The self property is read-only.

The self property is often used in comparisons

if (window.top != window.self) {

text = "This window is NOT the topmost window!";

} else {

text = "This window is the topmost window!";

}

closed

The closed property returns true if the window is closed.

The closed property is read-only.

innerHeight

The innerHeight property returns the height of a window's content area.

The innerHeight property is read only.

innerWidth

The innerWidth property returns the width of a window's content area.

The innerWidth property is read-only.

outerHeight

TheouterHeight property returns the outer height of the browser window, including all interface elements (like toolbars/scrollbars).

TheouterHeight property is read only.

outerWidth

The outerWidth property returns the outer width of the browser window, including all interface elements (like toolbars/scrollbars).

TheouterWidth property is read only.

screenLeft

The screenLeft property returns the x (horizontal) position of a window, relative to the screen.

screenTop

The screenTop property returns the y (vertical) position of the window relative to the screen.

screenX

The screenX property returns the x (horizontal) coordinate of a window, relative to the screen.

screenY

The screenY property returns the y (vertical) coordinate of a window, relative to the screen.

pageXOffset

The pageXOffset property returns the pixels a document has scrolled from the upper left corner of the window.

The pageXOffset property is equal to the scrollX property.

The pageXOffset property is read-only.

pageYOffset

The pageXOffset property returns the pixels a document has scrolled from the upper left corner of the window.

The pageXOffset property is equal to the scrollX property.

pageXOffset property is read-only.

localStorage

The localStorage object allows you to save key/value pairs in the browser. Storage Object

The localStorage object stores data with no expiration date.

The data is not deleted when the browser is closed, and are available for future sessions.

sessionStorage

The sessionStorage object let you store key/value pairs in the browser. Storage Object

The sessionStorage object stores data for only one session.

The data is deleted when the browser is closed.

Storage Object

The Storage object of the Web Storage API provides access to the session storage or local storage for a particular domain. This allows you to read, add, modify, and delete stored data items.

length

Returns the number of data items stored in the Storage object

 

setItem()

Adds a key to the storage, or updates a key's value if it already exists

localStorage.setItem(keyname, value)

localStorage.setItem("mytime", Date.now());

 

getItem()

Returns the value of the specified key name

localStorage.getItem(keyname)

var x = localStorage.getItem("mytime");

 

removeItem()

Removes a key from the storage

localStorage.removeItem(keyname)

localStorage.removeItem("mytime");

 

key()

Returns the name of the nth key in the storage

sessionStorage.key(index)

var x = localStorage.key(0);

 

clear()

Empty all key out of the storage

Methods

open()

The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter values.

Syntax

window.open(URL, name, specs, replace)

 

Example

window.open("", "", "left=700,top=350,width=200,height=100");

 

URL

Optional.

The URL of the page to open.

If no URL is specified, a new blank window/tab is opened

 

name

Optional.

TThe target attribute or the name of the window.

The following values are supported:

_blankURL is loaded into a new window, or tab. This is the default
_parentURL is loaded into the parent frame
_selfURL replaces the current page
_topURL replaces any framesets that may be loaded
nameThe name of the window (does not specify the title of the window)

 

specs

Optional.

A comma-separated list of items, no whitespaces.

The following values are supported:

fullscreen=yes|no|1|0Whether or not to display the browser in full-screen mode. Default is no. A window in full-screen mode must also be in theater mode. IE only
height=pixelsThe height of the window. Min. value is 100
left=pixelsThe left position of the window. Negative values not allowed
location=yes|no|1|0Whether or not to display the address field. Opera only
menubar=yes|no|1|0Whether or not to display the menu bar
resizable=yes|no|1|0Whether or not the window is resizable. IE only
scrollbars=yes|no|1|0Whether or not to display scroll bars. IE, Firefox & Opera only
status=yes|no|1|0Whether or not to add a status bar
titlebar=yes|no|1|0Whether or not to display the title bar. Ignored unless the calling application is an HTML Application or a trusted dialog box
toolbar=yes|no|1|0Whether or not to display the browser toolbar. IE and Firefox only
top=pixelsThe top position of the window. Negative values not allowed
width=pixelsThe width of the window. Min. value is 100
close()

The close() method closes a window.

stop()

The stop() method stops window loading.

The stop() method is the same as clicking stop in the browser.

The stop() method can be used to stop loading an image if it takes too long.

print()

The print() method prints the contents of the current window.

The print() method opens the Print Dialog Box, which lets the user to select preferred printing options.

prompt()

The prompt() method displays a dialog box that prompts the user for input.

The prompt() method returns the input value if the user clicks "OK", otherwise it returns null.

Note: A prompt box is used if you want the user to input a value. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed.Do not overuse this method. It prevents the user from accessing other parts of the page until the box is closed.

Syntax

prompt(text, defaultText)

 

Example

prompt("Please enter your name", "Harry Potter")

 

Parameters

textRequired.
The text to display in the dialog box.
defaultTextOptional.
The default input text.

Return Value

A stringIf the user clicks "OK", the input value is returned.
Otherwise null is returned.
confirm()

The confirm() method displays a dialog box with a message, an OK button, and a Cancel button.

The confirm() method returns true if the user clicked "OK", otherwise false.

A confirm box is often used if you want the user to verify or accept something.

A confirm box takes the focus away from the current window, and forces the user to read the message.

Note: Do not overuse this method. It prevents the user from accessing other parts of the page until the box is closed.

confirm("Press a button!");

alert()

The alert() method displays an alert box with a message and an OK button.

The alert() method is used when you want information to come through to the user.

alert("Hello! I am an alert box!!");

focus()

The focus() method sets focus to a window.

The focus() method makes a request to bring a window to the front.

It may not work as you expect, due to different user settings.

blur()

The blur() method removes focus from a window.

The blur() method makes a request to bring a window to the background.

It may not work as you expect, due to different user settings.

moveBy()

The moveBy() method moves a window a number of pixels relative to its current coordinates.

Syntax

window.moveBy(x, y)

 

Example

myWindow.moveBy(250, 250);

moveTo()

The moveTo() method moves a window to the specified coordinates.

Syntax

window.moveTo(x, y)

 

Example

myWindow.moveTo(500, 100);

resizeBy()

The resizeBy() method resizes a window by a specified amount.

Syntax

resizeBy(width, height)

 

Example

myWindow.resizeBy(250, 250);

resizeTo()

The resizeTo() method resizes a window to a new width and height.

Syntax

window.resizeTo(width, height)

 

Example

myWindow.resizeBy(250, 250);

scrollBy()

The scrollBy() method scrolls the document by the specified number of pixels.

For the scrollBy() method to work, the document must be larger than the screen, and the scrollbar must be visible.

Syntax

window.scrollBy(x, y)

 

Example

window.scrollBy(0, 100);

scrollTo()

The scrollTo() method scrolls the document to specified coordinates.

Syntax

window.scrollBy(x, y)

 

Example

window.scrollBy(0, 100);

getComputedStyle()

The getComputedStyle() method gets the computed CSS properties and values of an HTML element.

The getComputedStyle() method returns a CSSStyleDeclaration object.

The computed style is the style used on the element after all styling sources have been applied.

const element = document.getElementById("test");

const cssObj = window.getComputedStyle(element, null);

getSelection()

Returns a Selection object representing the range of text selected by the user

matchMedia()

The matchMedia() method returns a MediaQueryList Object with the results from the query.

The media queries of the matchMedia() method can be any of the media features of the CSS @media rule, like min-height, min-width, orientation, etc.

Syntax

window.matchMedia(mediaQuery)

Example

matchMedia("(max-height: 480px)")

 

// Create a match function

function myFunction(x) {

if (x.matches) {

document.body.style.backgroundColor = "yellow";

} else {

document.body.style.backgroundColor = "pink";

}

}

 

// Create a MediaQueryList object

const mmObj = window.matchMedia("(max-width: 700px)")

 

// Call the match function at run time:

myFunction(mmObj);

 

// Add the match function as a listener for state changes:

mmObj.addListener(myFunction);

 

MediaQueryList Properties & Methods

ValueDescription
matchesA boolean.
true if the document matches the query, otherwise false.
mediaA string.
A media query (list).
removeListener()Removes a previously added listener function from the media query list. Does nothing if the specified listener is not already in the list
requestAnimationFrame()

Requests the browser to call a function to update an animation before the next repaint

setInterval()

The setInterval() method calls a function at specified intervals (in milliseconds).

setInterval(function () {element.innerHTML += "Hello"}, 1000);

clearInterval()

The clearInterval() method clears a timer set with the setInterval() method.

To clear an interval, use the id returned from setInterval():

myInterval = setInterval(function, milliseconds);

 

Then you can to stop the execution by calling clearInterval():

clearInterval(myInterval);

setTimeout()

The setTimeout() method calls a function after a number of milliseconds.

const myTimeout = setTimeout(myGreeting, 5000);

clearTimeout()

The clearTimeout() method clears a timer set with the setTimeout() method.

To clear a timeout, use the id returned from setTimeout():

myTimeout = setTimeout(function, milliseconds);

 

Then you can to stop the execution by calling clearTimeout():

clearTimeout(myTimeout);

btoa()

The btoa() method encodes a string in base-64.

The btoa() method uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode the string.

let text = "Hello World!";

let encoded = window.btoa(text);

atob()

The atob() method decodes a base-64 encoded string.

let text = "Hello World!";

let encoded = window.btoa(text);

let decoded = window.atob(encoded);

History Object

 

The history object contains the URLs visited by the user (in the browser window).

The history object is a property of the window object.

The history object is accessed with window.history or just history:

let length = window.history.length;

let length = history.length;

length

The length property returns the number of URLs in the history list of the current browser window.

The property returns at least 1, because the list includes the current page.

This property is useful to find out how many pages the user has visited in the current browsing session.

go()

The history.go() method loads a URL (page) from the history list.

The history.go() method only works if the page exist in the history list.

history.go(0) reloads the page.

history.go(-1) is the same as history.back().

history.go(1) is the same as history.forward().

back()

The history.back() method loads the previous URL (page) in the history list.

history.back() method only works if a previous page exists.

history.back() is the same as history.go(-1).

history.back() is the same as clicking "Back" your browser.

forward()

The history.forward() method loads the next URL (page) in the history list.

The history.forward() method only works if a next page exists.

story.forward() is the same as history.go(1).

history.forward() is the same as clicking "Forward" in your browser.

Location Object

 

The location object contains information about the current URL.

The location object is a property of the window object.

The location object is accessed with window.location or just location

let origin = window.location.origin;

let origin = location.origin;

Properties

href

The location.href property sets or returns the entire URL of the current page.

location.href = https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_loc_href

pathname

The pathname property sets or returns the pathname of a URL (page).

location.pathname = /jsref/tryit.asp

port

The port property sets or returns the port number of a URL.

If the port number is not specified in the URL, or if it is a default port (80 for http) or (443 for https), most browsers will return an empty string.

location.port = 55

origin

The origin property returns the protocol, hostname and port number of a URL.

The origin property is read-only.

location.origin = https://www.w3schools.com:55

host

The location.host property returns the host (IP adress or domain) and port of a URL.

The location.host property can also be set, to navigate to the same URL with a new host and port.

location.host = www.w3schools.com:55

hostname

The location.hostname property returns the host (IP adress or domain) of a URL.

location.hostname property can also be set, to navigate to the same URL with a new hostname.

location.hostname = www.w3schools.com

protocol

The protocol property sets or returns the protocol of the current URL, including the colon (:).

The protocol is a standard that specifies how data are transmitted between computers.

location.protocol = https:

hash

The location.hash property sets or returns the anchor part of a URL, including the hash sign (#).

When location.hash is used to set the anchor part, do not include the hash sign (#).

location.hash = #mark_array_from

Methods

assign()

The assign() method loads a new document.

location.assign("https://www.w3schools.com");

replace()

The replace() method replaces the current document with a new one.

replace() removes the current URL from the document history.

With replace() it is not possible to use "back" to navigate back to the original document.

location.replace("https://www.w3schools.com");

reload()

The reload() method reloads the current document.

The reload() method does the same as the reload button in your browser.

Screen Object

The screen object contains information about the visitor's screen.

height

The height property returns the total height of the user's screen.

The height property returns the height in pixels.

The height property is read only.

let height = screen.height;

width

The width property returns the total width of the user's screen.

The width property returns width in pixels.

The width property is read-only.

let width = screen.width;

availHeight

The availHeight property returns the height of the user's screen.

The availHeight property returns the height in pixels.

The availHeight property returns the height minus interface features like the Windows Taskbar.

availWidth

The availWidth property returns the width of the user's screen.

The availWidth property returns the width in pixels.

The availWidth property returns the width minus interface features like the Windows Taskbar.

The availWidth property is read-only.

pixelDepth

The pixelDepth property returns the screen's color depth.

The pixelDepth property returns the color depth in bits per pixel.

The pixelDepth property is read-only.

let depth = screen.pixelDepth;

colorDepth

The colorDepth property returns the screen's color depth.

The colorDepth property returns the depth in bits per pixel.

The colorDepth property is read-only.

let depth = screen.colorDepth;

Fullscreen API

The Fullscreen API has methods and properties to handle HTML elements in full-screen.

fullscreenElement

Returns the element that is in full-screen mode,

requestFullscreen()

Opens an element in fullscreen mode

exitFullscreen()

Cancels the element in fullscreen mode

fullscreenEnabled()

Returns true if the document can be viewed in fullscreen mode

Console Object

The console object provides access to the browser's debugging console.

The console object is a property of the window object.

window.console.error("You made a mistake");

console.error("You made a mistake");

log()

The log() method writes (logs) a message to the console.

The log() method is useful for testing purposes.

When testing console methods, be sure to have the console view visible.

Press F12 to open the console veiw.

Syntax

console.log(message)

 

Example

console.log("Hello world!");

group()

The group() method starts a message group.

All new messages will be written inside this group.

Syntax

console.group(label)

 

Example

console.group("Logs");

groupCollapsed()

The groupCollapsed() method starts a collapsed message group.

In the Console, click the expand button to open the new message group.

All new messages will now be written inside this group.

Syntax

console.groupCollapsed(label)

 

Example

console.groupCollapsed("Logs");

groupEnd()

The groupEnd() ends a message group.

Syntax

console.groupEnd()

info()

Syntax

The info() method writes a message to the console.

 

Example

console.info("Hello world!");

warn()

The warn() method writes a warning to the console.

Syntax

console.warn(message)

 

Example

console.warn("This is a warning!");

error()

The error() method writes an error message to the console.

The console is useful for testing purposes.

Syntax

console.error(message)

 

Example

console.error("You made a mistake");

assert()

The assert() method writes a message to the console if an expression evaluates to false.

Syntax

console.assert(expression, message)

 

Example

console.assert(x + y == 11, "Expression returned false");

clear()

The clear() method clears the console.

The clear() method also write "Console was cleared" in the console.

Syntax

console.clear();

count()

The count() method counts the number of times console.count() is called.

The count() method this number to the console.

You can add a label that will be included in the console view.

As a default value the label "Default" is used.

Syntax

console.count(label)

 

Example

console.count("myLabel");

table()

The table() method writes a table to the console.

console.table(tabledata, tablecolumns)

 

Write an array as a table in the console:

console.table(["Audi", "Volvo", "Ford"]);

 

Write an object as a table in the console:

console.table({firstname:"John", lastname:"Doe"});

 

trace()

The trace() method displays a trace that show how the code ended up at a certain point.

Syntax

console.trace(label)

 

Example

console.trace("Traces");

time()

The time() method starts a timer in the console view.

The time() method allows you to time code for testing purposes.

You can run many timers at the same time.

Use the label parameter to name different timers.

Syntax

console.time(label)

 

Example

console.time("error time");

timeEnd()

The timeEnd() method ends a timer, and writes the result to the console.

Syntax

console.timeEnd(label)

 

Example

console.timeEnd("error time");

Document Object

When an HTML document is loaded into a web browser, it becomes a document object.

The document object is the root node of the HTML document.

The document object is a property of the window object.

The document object is accessed with window.document or just document

let url = window.document.URL;

let url = document.URL;

Properties

documentElement

The documentElement property returns a document's element (as an Element object).

The documentElement is read-only.

For HTML documents the returned object is the <html> element.

doctype

The doctype property returns a document's doctype (as a DocumentType object).

The doctype property returns null if the document has no doctype.

The doctype property is read-only.

The doctype.name property returns the name of the doctype.

URL

The URL property returns the full URL of the document.

referrer

The referrer property returns the URL of the document that loaded the current document.

The referrer property is read-only.

documentURI

The documentURI property sets or returns a document's location.

The documentURI property returns null if the document was created in memory.

The documentURI property can be used on any document types.

The document.URL property can only be used on HTML documents.

baseURI

The baseURI property returns the base URI of the document.

The baseURI property is read-only.

domain

The domain property returns the domain name of the server (the document was loaded from).

The domain property returns null if the document was created in memory.

implementation

The implementation property returns the DOMimplementation object that handles the document.

readyState

The readyState property returns the (loading) status of the current document.

The readyState property is read-only.

designMode

The designMode property sets or returns if the document is editable.

lastModified

The lastModified property returns the date and time the document was last modified.

The lastModified property is read-only.

defaultView

The defaultView property returns the document's window object.

characterSet

The characterSet property returns the character encoding for a document.

document.characterSet

title

The title property sets or returns the title of the document.

document.title

document.title = newTitle

scripts

Returns a collection of <script> elements in the document

body

Sets or returns the document's body (the <body> element)

forms

Returns a collection of all <form> elements in the document

images

Returns a collection of all <img> elements in the document

embeds

Returns a collection of all <embed> elements the document

activeElement

The activeElement property returns the HTML element that have focus.

The activeElement property is read-only.

Methods

getElementById()

The getElementById() method returns an element with a specified value.

The getElementById() method returns null if the element does not exist.

The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.

Any id should be unique, but if two or more elements with the same id exist, getElementById() returns the first.

Syntax

document.getElementById(elementID)

 

Example

document.getElementById("demo");

getElementsByClassName()

The getElementsByClassName() method returns a collection of elements with a specified class name(s).

The getElementsByClassName() method returns an HTMLCollection.

The getElementsByClassName() property is read-only.

Syntax

document.getElementsByClassName(classname)

 

Example

document.getElementsByClassName("example");

getElementsByName()

The getElementsByName() method returns a collection of elements with a specified name.

The getElementsByName() method returns a live NodeList.

Syntax

document.getElementsByName(name)

 

Example

document.getElementsByName("animal")

getElementsByTagName()

The getElementsByTagName() method returns a collection of all elements with a specified tag name.

The getElementsByTagName() method returns an HTMLCollection.

The getElementsByTagName() property is read-only.

getElementsByTagName("*") returns all elements in the document.

Syntax

document.getElementsByTagName(tagname)

 

Example

document.getElementsByTagName("li");

createElement()

The createElement() method creates an element node.

Syntax

document.createElement(type)

 

Example

document.createElement("p");

createAttribute()

The createAttribute() method creates an attribute and returns the attribute as an Attr object.

Syntax

document.createAttribute(name)

 

Example

const att = document.createAttribute("style");

att.value = "color:red";

createTextNode()

The createTextNode() method creates a text node.

Syntax

document.createTextNode(text)

 

Example

const textNode = document.createTextNode("Hello World");

createDocumentFragment()

The createDocumentFragment() method creates an offscreen node.

The offscreen node can be used to build a new document fragment that can be insert into any document.

The createDocumentFragment() method can also be used to extract parts of a document, change, add, or delete some of the content, and insert it back to the document.

Note

You can always edit HTML elements directly. But a better way is to construct an (offscreen) document fragment, and attach this fragment to the real (live) DOM when it is ready. Because you insert the fragment when it is ready, there will be only one reflow and one single render.

If you want to append HTML elements items in a loops, using document fragments also improves performance.

Warning!

Document nodes appended to the document fragment, are removed from the original document.

Syntax

document.createDocumentFragment()

 

Example

const dFrag = document.createDocumentFragment();

dFrag.appendChild(li);

createComment()

The createComment() method creates a comment and returns the comment node.

Syntax

document.createComment(text)

 

Example

document.createComment("My comments");

createEvent()

The createEvent() method creates an event object.

The event must be of a legal event type, and must be initialized (dipatched) before use.

Syntax

document.createEvent(type)

 

Example

const ev = document.createEvent("MouseEvent");

ev.initMouseEvent("mouseover", true, true,

window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

 

document.getElementById("myDiv").dispatchEvent(ev);

importNode()

The importNode() method imports a node from another document.

Whith the second parameter set to true, child nodes will also be imported.

The imported node is not removed from the original document.

The imported node is a copy of the original.

Syntax

document.importNode(node, deep)

 

Example

document.importNode(h1, true);

 

nodeRequired.
A node from another document.
Can be type of node.
deepRequired.
false: only the node itself is imported.
true: child nodes (descendants) are also imported.
adoptNode()

The adoptNode() method adopts a node from another document.

The adopted node can be of all types.

Any child nodes (descendants) of the adopted node, are also adopted.

The original node (with child nodes) is removed from the other document.

Syntax

document.adoptNode(node)

 

Example

document.adoptNode(h1);

querySelector()

The querySelector() method returns the first element that matches a CSS selector.

To return all matches (not only the first), use the querySelectorAll() instead.

Both querySelector() and querySelectorAll() throw a SYNTAX_ERR exception if the selector(s) is invalid.

Syntax

document.querySelector(CSS selectors)

 

Get the first <p> element:

document.querySelector("p");

 

Get the first element with class="example":

document.querySelector(".example");

querySelectorAll()

The querySelectorAll() method returns all elements that matches a CSS selector(s).

The querySelectorAll() method returns a NodeList.

The querySelectorAll() method throws a SYNTAX_ERR exception if the selector(s) is invalid

Syntax

document.querySelectorAll(CSS selectors)

 

Example

document.querySelectorAll(".example");

open()

The open() method opens a document for writing.

Warning: All existing document content will be cleared.

Note: Do not confuse this method with the window.open() method, which opens a new browser window.

close()

The close() method closes a window previously opened with the open() method.

write()

The write() method writes directly to an open (HTML) document stream.

Warning

The write() method deletes all existing HTML when used on a loaded document.

The write() method cannot be used in XHTML or XML.

Note

write() method is most often used to write to output streams opened by the the open() method.

document.write("<h2>Hello World!</h2><p>Have a nice day!</p>");

writeln()

The writeln() method writes directly to an open (HTML) document stream.

The writeln() method is identical to the write() method, with the addition of writing a newline character after each statement.

Warning

The writeln() method deletes all existing HTML when used on a loaded document.

The writeln() method cannot be used in XHTML or XML.

Note

It makes no sense to use writeln() in HTML.

If you want new lines in HTML, you must use paragraphs or <br> tags.

Syntax

document.writeln(exp1, exp2, exp3, ...)

 

Example

document.writeln("Hello World!");

document.writeln("Have a nice day!");

Hello World!

Have a nice day!

normalize()

The normalize() method removes empty text nodes, and joins adjacent text nodes.

hasFocus()

The hasFocus() method returns a true if the document (or any element in the document) has focus.

Otherwise it returns false.

addEventListener()

The addEventListener() method attaches an event handler to a document

Syntax

document.addEventListener(event, function, Capture)

 

Example

document.addEventListener("click", myFunction);

 

eventRequired.
The event name.
Do not use the "on" prefix.
Use "click" instead of "onclick".
functionRequired.
The function to run when the event occurs.
When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event. For example, the "click" event belongs to the MouseEvent object.
captureOptional (default = false).
true - The handler is executed in the capturing phase.
false - The handler is executed in the bubbling phase.
removeEventListener()

The removeEventListener() method removes an event handler from a document.

Syntax

document.removeEventListener(event, function, capture)

 

Example

document.removeEventListener("mousemove", myFunction);

Element Object

In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element.

Properties

attributes

The attributes property returns a collection of attributes in an element.

The attributes property returns a NamedNodeMap.

const nodeMap = document.getElementById("myImg").attributes;

let text = "";

or (let i = 0; i < nodeMap.length; i++) {

text += nodeMap[i].name + " = " + nodeMap[i].value + "<br>";

}

 

document.getElementById("demo").innerHTML = text;

id = myImg;alt = Flower;src = klematis.jpg;width = 150;height = 113

Attr Object

In the HTML DOM, an Attr object represents an HTML attribute.

An HTML attribute always belongs to an HTML element.

name

The name property returns the name of an attribute.

The name property is read-only.

 

value

The value property sets or returns the value of an attribute.

 

specified

The specified property returns true if an attribute is specified.

Warning: This property returns an error if the attribute is not specified. This might crash your program.

NamedNodeMap Object

A NamedNodeMap is an array-like unordered collection of an element's attributes.

In other words: a NamedNodeMap is a list of Attr objects.

A NamedNodeMap has a length property that returns the number of nodes.

The nodes can be accessed by name or index numbes. The index starts at 0.

getNamedItem()

The getNamedItem() method returns an attribute node from a NamedNodeMap object.

It is easier to use the element.getAttribute() method.

namednodemap.getNamedItem(nodename)

 

const nodeMap = document.getElementById("myButton");

let value = nodeMap.getNamedItem("onclick").value;

 

item()

The item() method returns an attribute (by index) from a NamedNodeMap.

namednodemap.item(index)

namednodemap[index]

 

const nodeMap = document.getElementById("myDiv").attributes;

let name1 = nodeMap.item(0).name;

let name2 = nodeMap.item(1).name;

 

const nodeMap = document.getElementById("myDiv").attributes;

let name1 = nodeMap[0].name;

let name2 = nodeMap[1].name;

 

length

The length property returns the number of nodes in a NamedNodeMap.

The length property is read-only.

namednodemap.length

 

document.getElementById("myButton").attributes.length;

 

removeNamedItem()

The removeNamedItem() method removes a node (by name) in a NamedNodeMap.

Note: When removing the type attribute of an input element, the element will be of type text, which is the default value.

namednodemap.removeNamedItem(nodename)

 

const nodeMap = document.getElementById("myInput").attributes;

nodeMap.removeNamedItem("type");

 

setNamedItem()

The setNamedItem() method adds an attribute node to a NamedNodeMap.

If the attribute node already exists, it will be replaced, and the replaced attribute node is returned, otherwise the return value is null.

namednodemap.setNamedItem(node)

 

const element = document.getElementsByTagName("H1")[0];

element.setAttribute("class", "democlass");

accessKey

The accessKey property sets or returns the accesskey attribute of an element.

The accessKey property specifies a shortcut key to activate or focus an element.

Warning: Using accesskeys is difficult because they may conflict with other key standards in the browser. To avoid this problem, most browsers will use accesskeys only if pressed together with the Alt key.

Conserns: Adapting accesskeys to all internatinal languages is difficult. The accesskey value may not be present on all keyboards. Because of these conserns, it is advised not to use accesskeys.

classList

The classList property returns the CSS classnames of an element.

The classList property returns a DOMTokenList.

className

The className property sets or returns an element's class attribute.

Syntax

HTMLElementObject.className = class

 

Example

element.className = "myStyle";

contentEditable

The contentEditable property sets or returns if the content of an element is editable.

Syntax

element.contentEditable = value

 

Example

document.getElementById("myP").contentEditable = "true";

isContentEditable

The isContentEditable property returns true if the content of an element is editable.

isContentEditable property is read-only.

dir

The dir property sets or returns an elements's dir attribute.

The dir attribute specifies the text-direction.

Syntax

element.dir = "ltr|rtl|auto"

 

Example

document.body.dir = "rtl";

id

The id property sets or returns the value of an element's id attribute.

Syntax

element.id = id

 

Example

document.getElementById("demo").id = "newid";

lang

The lang property sets or returns the value of an element's lang attribute.

The lang attribute specifies the element's language code, like "en" for English, "es" for Spanish, or "fr" for French.

Syntax

element.lang = lang_code

style

The style property returns the values of an element's style attribute.

The style property returns a CSSStyleDeclaration object.

The CSSStyleDeclaration object contains all inline styles properties for the element. It does not contain any style properties set in the <head> section or in any external style sheets.

Syntax

element.style.property = value

 

Example

document.getElementById("myH1").style.color = "red";

tabIndex

The tabIndex property sets or returns the value of the tabindex attribute of an element.

The tabindex attribute specifies the tab order of an element, when the "tab" button is used for navigating.

Syntax

element.tabIndex = number

title

The title property sets or returns the value of an element's title attribute.

The title attribute specifies extra information about an element. It can be shown as a tooltip text when the mouse moves over the element.

Syntax

element.title = text

 

Example

element.title = "The World's Largest Web Development Site";

tagName

The tagName property returns the tag name of an element. h1, h2, body, p, button

The tagName property returns the tag name in UPPERCASE.

The tagName property is read-only.

Difference Between tagName and nodeName

The nodeName property also returns the tag name of an element.

The nodeName can also return the tag name of attribute nodes, text nodes, and comment nodes.

ownerDocument

The ownerDocument property returns the owner document of a node, as a Document object.

In HTML, the HTML document itself is always the ownerDocument of an element.

namespaceURI

The namespaceURI property returns the URI of an elements namespace.

The namespaceURI property is read-only.

The namespaceURI property has no practical use in HTML.

The default namespace URI is the same for HTML and XHTML documents.

innerHTML

The innerHTML property sets or returns the HTML content (inner HTML) of an element.

Syntax

element.innerHTML = text

 

Example

Change the HTML content of an element with id="demo":

document.getElementById("demo").innerHTML = "I have changed!";

innerText

The innerText property sets or returns the text content of an element.

When you set the innerText property, all child nodes are removed and replaced by only one new text node.

Syntax

element.innerText = text

node.innerText = text

textContent

e textContent property sets or returns the text content of the specified node, and all its descendants.

When you set the textContent property, all child nodes are removed and replaced by only one new text node.

Syntax

element.textContent = text

node.textContent = text

 

The Differences Between innerHTML, innerText and textContent

The innerHTML property returns the text content of the element, including all spacing and inner HTML tags.

This element has extra spacing and contains <span>a span element</span>.

 

The innerText property returns just the text content of the element and all its children, without CSS hidden text spacing and tags, except <script> and <style> elements.

This element has extra spacing and contains a span element.

 

The textContent property returns the text content of the element and all descendaces, with spacing and CSS hidden text, but without tags.

This element has extra spacing and contains a span element.

outerHTML

The outerHTML property sets or returns the HTML element, including attributes, start tag, and end tag.

Syntax

element.outerHTML = text

 

Example

let html = document.getElementsByTagName("ul")[0].outerHTML;

 

e.outerHTML

<ul id="myList">

<li>Coffee</li>

<li>Tea</li>

</ul>

 

e.innerHTML

<li>Coffee</li>

<li>Tea</li>

outerText

The outerText property sets or returns the text content of the specified node.

This property is similar to the inner innerText property, in fact getting the outerText returns the same result as getting the innerText property.

There are an important difference when setting an element's outerText, because the element itself is removed (same as outerHTML).

Syntax

node.outerText = text

 

Example

document.getElementById("myH1").outerText = "Changed content!";

clientHeight

Returns the height of an element, including padding

clientWidth

Returns the width of an element, including padding

clientTop

Returns the width of the top border of an element

clientLeft

Returns the width of the left border of an element

scrollHeight

Returns the entire height of an element, including padding

scrollWidth

Returns the entire width of an element, including padding

scrollTop

Sets or returns the number of pixels an element's content is scrolled vertically

scrollLeft

Sets or returns the number of pixels an element's content is scrolled horizontally

offsetHeight

Returns the height of an element, including padding, border and scrollbar

offsetWidth

Returns the width of an element, including padding, border and scrollbar

offsetTop

Returns the vertical offset position of an element

offsetLeft

Returns the horizontal offset position of an element

offsetParent

Returns the offset container of an element

children

The children property returns a collection of an element's child elements.

The children property returns an HTMLCollection object.

childElementCount

The childElementCount property returns the number of child elements of an element.

The childElementCount property returns the same as children.length.

The childElementCount is read only.

firstElementChild

Returns the first child element of an element

lastElementChild

Returns the last child element of an element

nextElementSibling

Returns the next element at the same node tree level

previousElementSibling

Returns the previous element at the same node tree level

parentElement

Returns the parent element node of an element

nodeName

The nodeName property returns the name of a node:

The nodeName property is read-only.

nodeType

The nodeType property returns the node type, as a number, of the specified node.

This property is read-only.

nodeValue

Sets or returns the value of a node

childNodes

Returns a NodeList of an element's child nodes

firstChild

Returns the first child node of an element

lastChild

Returns the last child node of an element

nextSibling

Returns the next node at the same node tree level

previousSibling

Returns the previous node at the same node tree level

parentNode

Returns the parent node of an element

Methods

getAttribute()

The getAttribute() method returns the value of an element's attribute.

Syntax

element.getAttribute(name)

 

Example

let text = element.getAttribute("class");

let text = myAnchor.getAttribute("target");

getAttributeNode()

The getAttributeNode() method returns an element's attribute.

The getAttributeNode() method returns an Attribute object.

Syntax

element.getAttributeNode(name)

 

Example

element.getAttributeNode("class").value;

 

The Difference Between getAttribute() and getAttributeNode()

The getAttribute() method returns the value of an attribute.

The getAttributeNode() method returns an Attr object, and you must use the Attr value property to get the value.

The result will be the same.

hasAttribute()

The hasAttribute() method returns true if the attribute exists, otherwise false.

Syntax

element.hasAttribute(name)

 

Example

myButton.hasAttribute("onclick")

hasAttributes()

The hasAttributes() method returns true if a node has attributes, otherwise false.

The hasAttributes() method always returns false if the node is not an element node.

Syntax

element.hasAttributes()

node.hasAttributes()

removeAttribute()

The removeAttribute() method removes an attribute from an element.

Syntax

element.removeAttribute(name)

 

Example

document.getElementById("myAnchor").removeAttribute("href");

removeAttributeNode()

The removeAttributeNode() method removes an attribute from an element.

The removeAttributeNode() method returns an Attribute object.

Syntax

element.removeAttributeNode(node)

 

Example

element.removeAttributeNode("class");

 

The Difference Between removeAttribute() and removeAttributeNode()

The removeAttribute() method removes an attribute, and does not have a return value.

The removeAttributeNode() method removes an Attr object, and returns the removed object.

The result will be the same.

setAttribute()

The setAttribute() method sets a new value to an attribute.

If the attribute does not exist, it is created first.

Syntax

element.setAttribute(name, value)

 

Example

element.setAttribute("class", "democlass");

setAttributeNode()

The setAttributeNode() method adds an attribute node to an element.

The setAttributeNode() method replaces existing attribute nodes.

The setAttributeNode() method returns an Attribute object.

Syntax

element.setAttributeNode(node)

 

Example

h1.setAttributeNode("class")

 

The Difference Between setAttribute() and setAttributeNode()

The setAttribute() method replaces attribute values.

The setAttributeNode() method replaces Attribute objects.

You must create an Attr object and set the Attr value before adding the attribute to an element.

The result will be the same.

getElementsByClassName()

The getElementsByClassName() method returns a collection of child elements with a given class name.

The getElementsByClassName() method returns a NodeList object.

Syntax

element.getElementsByClassName(classname)

 

Example

element.getElementsByClassName("child");

getElementsByTagName()

The getElementsByTagName() method returns a collection of child elements with a given tag name.

getElementsByTagName() method returns a NodeList object.

The tag name "*" returns all child elements.

Syntax

element.getElementsByTagName("p");

getBoundingClientRect()

The getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

The getBoundingClientRect() method returns a DOMRect object with eight properties: left, top, right, bottom, x, y, width, height.

The scrolling that has been done is taken into account. This means that the rectangle's edges (top, left, bottom, and right) change their values every time the scrolling position changes.

Syntax

element.getBoundingClientRect()

insertAdjacentElement()

The insertAdjacentElement() method inserts a an element into a specified position.

Syntax

element.insertAdjacentElement(position, element)

node.insertAdjacentElement(position, element)

 

Example

h2.insertAdjacentElement("afterend", span);

 

afterbeginAfter the beginning of the element (first child)
afterendAfter the element
beforebeginBefore the element
beforeendBefore the end of the element (last child)
insertAdjacentHTML()

The insertAdjacentHTML() method inserts HTML code into a specified position.

Syntax

element.insertAdjacentHTML(position, html)

node.insertAdjacentHTML(position, html)

 

Example

let html = "<p>My new paragraph.</p>";

h2.insertAdjacentHTML("afterend", html);

insertAdjacentText()

The insertAdjacentText() method inserts a a text into a specified position.

Syntax

element.insertAdjacentText(position, text)

node.insertAdjacentText(position, text)

click()

The click() method simulates a mouse-click on an element.

This method can be used to execute a click on an element as if the user manually clicked on it.

blur()

Removes focus from an element

focus()

Gives focus to an element

closest()

The closest() method searches up the DOM tree for elements which matches a specified CSS selector.

The closest() method starts at the element itself, then the anchestors (parent, grandparent, ...) until a match is found.

The closest() method returns null() if no match is found.

Syntax

element.closest(selectors)

 

Example

const element = document.getElementById(".container, .wrapper");

const closest = element.closest(".container");

matches()

The matches() method returns true if an element matches a specific CSS selector(s).

The matches() method returns false if not.

Syntax

element.matches(selectors)

 

Example

const element = document.getElementById("demo");

let answer = element.matches(".container");

normalize()

The normalize() method removes empty text nodes, and joins adjacent text nodes.

remove()

The remove() method removes an element (or node) from the document.

cloneNode()

The cloneNode() method creates a copy of a node, and returns the clone.

cloneNode() method clones all attributes and their values.

Set the deep parameter to true if you also want to clone descendants (children).

Syntax

node.cloneNode(deep)

 

Example

const clone = node.cloneNode(true);

 

deepOptional.
false - Default. Clone only the node and its attributes.
true - Clone the node, its attributes, and its descendants.
isEqualNode()

The isEqualNode() returns true if two elements (or nodes) are equal.

Two nodes are equal if all of the following conditions are true:

  • They have the same nodeType

  • They have the same nodeName

  • They have the same nodeValue

  • They have the same nameSpaceURI

  • They have the same childNodes with all the descendants

  • They have the same attributes and attribute values

  • They have the same localName and prefix

Syntax

element.isEqualNode(node)

node.isEqualNode(node)

 

Example

var item1 = document.getElementById("myList1").firstChild;

var item2 = document.getElementById("myList2").firstChild;

var x = item1.isEqualNode(item2);

isSameNode()

The isSameNode() method checks if two nodes are the same node.

The isSameNode() method returns true if the two nodes are the same node, otherwise false.

Syntax

node.isSameNode(node)

 

Example

var item1 = document.getElementById("myList1");

var item2 = document.getElementsByTagName("UL")[0];

var x = item1.isSameNode(item2);

scrollIntoView()

The scrollIntoView() method scrolls an element into the visible area of the browser window.

Syntax

element.scrollIntoView(align)

 

Example

const element = document.getElementById("content");

element.scrollIntoView();

 

ValueDescription
alignOptional.
A boolean that indicates the type of the align:

true - the top of the element will be aligned to the top of the visible area of the scrollable ancestor

false - the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor.

If omitted, it will scroll to the top of the element.

Note: Depending on the layout of other elements, some elements may not be scrolled completely to the top or to the bottom.
compareDocumentPosition()

The compareDocumentPosition() method compares two nodes, and returns an integer describing where they are positioned in the document:

Syntax

node.compareDocumentPosition(node)

 

Example

const p1 = document.getElementById("p1");

const p2 = document.getElementById("p2");

let position = p1.compareDocumentPosition(p2);

 

1The nodes do not belong to the same document
2The first node is positioned after the second
4The first node is positioned before the second
8The first node is positioned inside the second
16The second node is positioned inside the first
32The nodes are attributes on the same element
hasChildNodes()

The hasChildNodes() method returns true if the specified node has any child nodes, otherwise false.

The hasChildNodes() method is read-only.

appendChild()

The appendChild() method appends a node (element) as the last child of an element.

Syntax

element.appendChild(node)

 

Example

const node = document.getElementById("myList2").lastElementChild;

document.getElementById("myList1").appendChild(node);

insertBefore()

The insertBefore() method inserts a child node before an existing child.

Syntax

element.insertBefore(new, existing) * If null, it will be inserted at the end.

node.insertBefore(new, existing)

 

Example

const node = document.getElementById("myList2").lastElementChild;

const list = document.getElementById("myList1");

list.insertBefore(node, null);

removeChild()

The removeChild() method removes an element's child.

The child is removed from the Document Object Model (the DOM).

However, the returned node can be modified and inserted back into the DOM (See "More Examples").

Syntax

element.removeChild(node)

node.removeChild(node)

 

Example

const list = document.getElementById("myList");

list.removeChild(list.firstChild);

replaceChild()

The replaceChild() method replaces a child node with a new node.

Syntax

node.replaceChild(newnode, oldnode)

 

Example

const newNode = document.createTextNode("Water");

const element = document.getElementById("myList").children[0];

element.replaceChild(newNode, element.childNodes[0]);

contains()

The contains() method returns true if a node is a descendant of a node.

The contains() method returns false if not.

A descendant can be a child, grandchild, great-grandchild, ...

Syntax

node.contains(node)

 

Example

const span = document.getElementById("mySPAN");

let answer = document.getElementById("myDIV").contains(span);

querySelector()

The querySelector() method returns the first child element that matches a specified CSS selector(s) of an element.

Note: The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method instead.

Syntax

element.querySelector(CSS selectors)

 

Example

element.querySelector(".example").innerHTML = "Hello World!";

querySelectorAll()

The querySelectorAll() method returns a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object.

Syntax

element.querySelectorAll(CSS selectors)

 

Example

// Get the element with id="myDIV" (a div), then get all elements inside div with class="example"

var x = document.getElementById("myDIV").querySelectorAll(".example");

 

// Set the background color of the first element with class="example" (index 0) in div

x[0].style.backgroundColor = "red";

isDefaultNamespace()

The isDefaultNamespace() method returns true if the elements's namespace is default.

Syntax

element.isDefaultNamespace(namespaceURI)

node.isDefaultNamespace(namespaceURI)

 

Example

let answer = element.isDefaultNamespace("http://www.w3.org/1999/xhtml");

addEventListener()

The addEventListener() method attaches an event handler to an element.

Syntax

element.addEventListener(event, function, useCapture)

 

Example

element.addEventListener("click", myFunction);

 

useCaptureOptional (default = false).
false - The handler is executed in the bubbling phase.
true - The handler is executed in the capturing phase.
removeEventListener()

The removeEventListener() method removes an event handler from an element.

Syntax

element.removeEventListener(event, function, capture)

 

Example

myDIV.removeEventListener("mousemove", myFunction);

HTML DOM Events

HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document.

Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button).

In HTML:

<element onclick="myScript">

 

In JavaScript:

object.onclick = function(){myScript};

 

In JavaScript, using the addEventListener() method:

object.addEventListener("click", myScript);

 

Event Property & Method Syntax:

event.which

event.getModifierState()

 

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.

open

The onopen event occurs when a connection with an event source is opened.

show

The onshow event occurs when a <menu> element is shown as a context menu.

toggle

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

message

The onmessage event occurs when a message is received through an event source.

load

The onload event occurs when an object has been loaded.

onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

The onload event can also be used to deal with cookies (see "More Examples" below).

unload

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.).

Note: The onunload event is also triggered when a user reloads the page (and the onload event).

beforeunload

The onbeforeunload event occurs when the document is about to be unloaded.

This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page.

The default message that appears in the confirmation box, is different in different browsers. However, the standard message is something like "Are you sure you want to leave this page?". This message cannot be removed.

However, you can write a custom message together with the default message. See the first example on this page.Note: This only works in Internet Explorer.

Note: If the onbeforeunload event is not assigned to the <body> element, you must assign/attach the event on the window object, and use the returnValue property to create a custom message (see syntax examples below).

error

The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).

offline

The onoffline event occurs when the browser starts to work offline.

online

The ononline event occurs when the browser starts to work online.

resize

The onresize event occurs when the browser window has been resized.

scroll

The event occurs when an element's scrollbar is being scrolled

fullscreenchange

The fullscreenchange event occurs when an element is viewed in fullscreen mode.

Note: This event requires specific prefixes to work in different browsers (see Browser Support below).

fullscreenerror

The fullscreenerror event occurs when an element can not be viewed in fullscreen mode, even if it has been requested.

Note: This event requires specific prefixes to work in different browsers (see Browser Support below).

afterprint

The onafterprint event occurs when a page has started printing, or if the print dialogue box has been closed.

beforeprint

The onbeforeprint event occurs when a page is about to be printed (before the print dialogue box appears).

invalid

The oninvalid event occurs when a submittable <input> element is invalid.

input

The onbeforeprint event occurs when a page is about to be printed (before the print dialogue box appears).

select

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.

change

The onchange event occurs when the value of an element has been changed.

For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.

Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed. The other difference is that the onchange event also works on <select> elements.

submit

The event occurs when a form is submitted

reset

The event occurs when a form is reset

play

The event occurs when the media has been started or is no longer paused

playing

The event occurs when the media is playing after having been paused or stopped for buffering

pause

The event occurs when the media is paused either by the user or programmatically

ended

The event occurs when the media has reach the end (useful for messages like "thanks for listening")

seeking

The event occurs when the user starts moving/skipping to a new position in the media

seeked

The event occurs when the user is finished moving/skipping to a new position in the media

volumechange

The event occurs when the volume of the media has changed (includes setting the volume to "mute")

timeupdate

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 (like when the user fast forwards to a different point in the audio/video)

Tip: 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.

ratechange

The onratechange event occurs when the playing speed of the audio/video is changed (like when a user switches to a slow motion or fast forward mode).

This event is invoked by the playbackRate property of the Audio/Video Object, which sets or returns the current playback speed of an audio/video.

durationchange

The ondurationchange event occurs when the duration of the audio/video is changed.

Note: When the audio/video is loaded, the duration will change from "NaN" to the actual duration of the audio/video.

canplay

The event occurs when the browser can start playing the media (when it has buffered enough to begin)

canplaythrough

The event occurs when the browser can play through the media without stopping for buffering

loadeddata

The event occurs when media data is loaded

loadedmetadata

The onloadedmetadata event occurs when meta data for the specified audio/video has been loaded.

Meta data for audio/video consists of: duration, dimensions (video only) and text tracks.

progress

The event occurs when the browser is in the process of getting the media data (downloading the media)

waiting

The onwaiting event occurs when the video stops because it needs to buffer the next frame.

This event can also be used on <audio> elements, but it is mostly used for videos.

stalled

The event occurs when the browser is trying to get media data, but data is not available

suspend

The onsuspend event occurs when the browser is intentionally not getting media data.

This event occurs when the loading of the media is suspended (prevented from continuing). This can happen when the download has completed, or because it has been paused for some reason.

abort

The onabort event occurs when the loading of an audio/video is aborted.

This event occurs when the media data download has been aborted, and not because of an error.

Properties and Methods

type

The type event property returns the type of the triggered event.

target

The target event property returns the element that triggered the event.

The target property gets the element on which the event originally occurred, opposed to the currentTarget property, which always refers to the element whose event listener triggered the event.

currentTarget

The currentTarget event property returns the element whose event listeners triggered the event.

This is particularly useful during capturing and bubbling.

The currentTarget property always refers to the element whose event listener triggered the event, opposed to the targetproperty, which returns the element that triggered the event.

timeStamp

The timeStamp event property returns the number of milliseconds from the document was finished loading until the specific event was created.

Not all systems provide this information, therefore, timeStamp may be not available for all systems/events.

isTrusted

The isTrusted event property returns a Boolean value indicating whether the event is trusted or not.

Note: In Chrome, Firefox and Opera, the event is trusted if it is invoked by the user, and not trusted if it is invoked by a script. In IE, all events are trusted except those that are created with the createEvent() method.

composed

Returns whether the event is composed or not

cancelable

The cancelable event property returns a Boolean value indicating whether or not an event is a cancelable event.

The event is cancelable if it is possible to prevent the events default action.

To cancel an event, use the preventDefault() method.

bubbles

The bubbles event property returns a Boolean value that indicates whether or not an event is a bubbling event.

Event bubbling directs an event to its intended target, it works like this:

  • A button is clicked and the event is directed to the button

  • If an event handler is set for that object, the event is triggered

  • If no event handler is set for that object, the event bubbles up (like a bubble in water) to the objects parent

eventPhase

The eventPhase event property returns a number that indicates which phase of the event flow is currently being evaluated.

The number is represented by 4 constants:

  • 0. NONE

  • 1. CAPTURING_PHASE - The event flow is in capturing phase

  • 2. AT_TARGET - The event flow is in target phase, i.e. it is being evaluated at the event target

  • 3. BUBBLING_PHASE - The event flow is in bubbling phase

defaultPrevented

The defaultPrevented event property checks whether the preventDefault() method was called for the event.

onemptied

The event occurs when something bad happens and the media file is suddenly unavailable (like unexpectedly disconnects)

preventDefault()

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when:

  • Clicking on a "Submit" button, prevent it from submitting a form

  • Clicking on a link, prevent the link from following the URL

Note: Not all events are cancelable. Use the cancelable property to find out if an event is cancelable.

Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.

stopPropagation()

The stopPropagation() method prevents propagation of the same event from being called.

Propagation means bubbling up to parent elements or capturing down to child elements.

stopImmediatePropagation()

The stopImmediatePropagation() method prevents other listeners of the same event from being called.

Mouse Events

Events that occur when the mouse interacts with the HTML document, belongs to the MouseEvent Object.

onclick

The event occurs when the user clicks on an element

ondblclick

The event occurs when the user double-clicks on an element

onmousedown

The event occurs when the user presses a mouse button over an element

onmouseup

The event occurs when a user releases a mouse button over an element

onmouseenter

The event occurs when the pointer is moved onto an element

onmouseover

The event occurs when the pointer is moved onto an element, or onto one of its children

onmousemove

The event occurs when the pointer is moving while it is over an element

onmouseleave

The event occurs when the pointer is moved out of an element

onmouseout

The event occurs when a user moves the mouse pointer out of an element, or out of one of its children

oncontextmenu

The event occurs when the user right-clicks on an element to open a context menu

Properties and Methods

which

The which property returns a number that indicates which mouse button was pressed when a mouse event was triggered.

This property is mostly used together with the onmousedown event.

Note: The values returned by this property are the same as those returned by the button property plus one.

Note: This property is read-only.

button

The button property returns a number that indicates which mouse button was pressed when a mouse event was triggered.

This property is mostly used together with the onmousedown event.

Note: This property is read-only.

Possible values:

  • 0 : Left mouse button

  • 1 : Wheel button or middle button (if present)

  • 2 : Right mouse button

buttons

The buttons property returns a number that indicates which mouse button or mouse buttons were pressed when a mouse event was triggered.

This property is mostly used together with the onmousedown event.

Tip: Due to lack of browser support, you may want to look at the button property instead.

Note: This property is read-only.

Possible values:

  • 1 : Left mouse button

  • 2 : Right mouse button

  • 4 : Wheel button or middle button

  • 8 : Fourth mouse button (typically the "Browser Back" button)

  • 16 : Fifth mouse button (typically the "Browser Forward" button)

ctrlKey

The ctrlKey property returns a Boolean value that indicates whether or not the "CTRL" key was pressed when a mouse event was triggered.

Note: This property is read-only.

altKey

The altKey property returns a Boolean value that indicates whether or not the "ALT" key was pressed when a mouse event was triggered.

Note: On some Mac keyboards, the "ALT" key is displayed as "Option" or "Opt".

Note: This property is read-only.

shiftKey

The shiftKey property returns a Boolean value that indicates whether or not the "SHIFT" key was pressed when a mouse event was triggered.

Note: This property is read-only.

metaKey

The metaKey property returns a Boolean value that indicates whether or not the "META" key was pressed when a mouse event was triggered.

Not all keyboards have the meta key. It is common for Sun microsystem keyboards, and MIT and LISP machine keyboards. The meta key is either labeled "META" or marked with a solid diamond "◆" symbol.

On Mac keyboards, the META key is represented by the the "Command/Cmd" ("⌘") key.

Note: This property is read-only.

relatedTarget

The relatedTarget property returns the element related to the element that triggered the mouse event.

The relatedTargert property can be used with the mouseover event to indicate the element the cursor just exited, or with the mouseout event to indicate the element the cursor just entered.

Note: This property is read-only.

screenX

The screenX property returns the horizontal coordinate (according to the users computer screen) of the mouse pointer when an event was triggered.

Note: This property is read-only.

screenY

The screenY property returns the vertical coordinate (according to the users computer screen) of the mouse pointer when an event was triggered.

Note: This property is read-only.

pageX

The pageX property returns the horizontal coordinate (according to the document) of the mouse pointer when a mouse event was triggered.

The document is the web page.

Note: This property is read-only.

Note: This property is non-standard, but works in most major browsers.

pageY

The pageX property returns the horizontal coordinate (according to the document) of the mouse pointer when a mouse event was triggered.

The document is the web page.

Note: This property is read-only.

Note: This property is non-standard, but works in most major browsers.

MovementX

Returns the horizontal coordinate of the mouse pointer relative to the position of the last mousemove event

MovementY

Returns the vertical coordinate of the mouse pointer relative to the position of the last mousemove event

offsetX

The offsetX property returns the x-coordinate of the mouse pointer, relative to the target element.

Note: This property is read-only.

offsetY

The offsetY property returns the y-coordinate of the mouse pointer, relative to the target element.

Note: This property is read-only.

clientX

The clientX property returns the horizontal coordinate (according to the client area) of the mouse pointer when a mouse event was triggered.

The client area is the current window.

Note: This property is read-only.

clientY

The clientY property returns the vertical coordinate (according to the client area) of the mouse pointer when a mouse event was triggered.

The client area is the current window.

Note: This property is read-only.

getModifierState()

The getModifierState() method returns true if the specified modifier key was pressed, or activated.

Modifier keys that are activated only when they are being pressed down:

  • Alt

  • AltGraph

  • Control

  • Meta

  • Shift

Modifier keys that are activated when they are clicked, and deactivated when they are clicked again:

  • CapsLock

  • NumLock

  • ScrollLock

event.getModifierState(modifierKey)

var x = event.getModifierState("CapsLock");

Inherited Properties and Methods

The MouseEvent inherits all the properties and methods from:

  • The UiEvent

Wheel Events

Events that occur when the mouse wheel is scrolling, belongs to the WheelEvent Object.

wheel

The onwheel event occurs when the mouse wheel is rolled up or down over an element.

The onwheel event also occurs when the user scrolls or zooms in or out of an element by using a touchpad (like the "mouse" of a laptop).

Properties and Methods

deltaMode

The deltaMode property returns a number representing the length unit of the scrolling values (deltaX, deltaY, and deltaZ).

  • 0 = pixels

  • 1 = lines

  • 2 = pages

Note: This property is read-only.

deltaX

The deltaX property returns a positive value when scrolling to the right, and a negative value when scrolling to the left, otherwise 0.

Note: Most mouse devices do not have the ability to scroll left and right, and will always return 0.

Note: This property is read-only.

deltaY

The deltaY property returns a positive value when scrolling down, and a negative value when scrolling up, otherwise 0.

Note: This property is read-only.

deltaZ

The deltaZ property returns a positive value when scrolling in, and a negative value when scrolling out, otherwise 0.

Note: Most mouse devices do not have the ability to scroll along the z-axis, and will always return 0.

Note: This property is read-only.

Inherited Properties and Methods

The WheelEvent inherits all the properties and methods from:

  • The MouseEvent

  • The UiEvent

Drag Events

Events that occur when elements are dragged and/or dropped, belongs to the DragEvent Object.

ondrag

The ondrag event occurs when an element or text selection is being dragged.

Drag and drop is a very common feature in HTML5. It is when you "grab" an object and drag it to a different location. For

Note: To make an element draggable, use the global HTML5 draggable attribute.

Tip: Links and images are draggable by default, and do not need the draggable attribute.

ondragstart

The ondragstart event occurs when the user starts to drag an element or text selection.

ondragend

The ondragend event occurs when the user has finished dragging an element or text selection.

ondragenter

The ondragenter event occurs when a draggable element or text selection enters a valid drop target.

ondragover

The ondragover event occurs when a draggable element or text selection is being dragged over a valid drop target.

ondragleave

The ondragleave event occurs when a draggable element or text selection leaves a valid drop target.

ondrop

The ondrop event occurs when a draggable element or text selection is dropped on a valid drop target.

Properties and Methods

dataTransfer

Returns an object containing the data being dragged/dropped, or inserted/deleted

Inherited Properties and Methods

The DragEvent inherits all the properties and methods from:

  • The MouseEvent

Keyboard Events

Events that occur when user presses a key on the keyboard, belongs to the KeyboardEvent Object.

onkeypress

The onkeypress event occurs when the user presses a key (on the keyboard).

Note: The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the onkeydown event instead, because it works for all keys.

onkeydown

The onkeydown event occurs when the user is pressing a key (on the keyboard).

onkeyup

The onkeyup event occurs when the user releases a key (on the keyboard).

Properties and Methods

key

The key property returns the identifier of the key that was pressed when a key event occured.

Key identifiers are strings that identify keyboard buttons. The return value of this property can be a string of:

  • A single character (like "a", "W", "4", "+" or "$")

  • A multicharacter (like "F1", "Enter", "HOME" or "CAPS LOCK")

Note: This property is read-only.

Tip: If you want to find out whether the "ALT", "CTRL", "META" or "SHIFT" key was pressed when a key event occured, use the altKey, ctrlKey, metaKey or shiftKey property.

code

The code property returns the key that triggered the event.

Note: This property returns different values for different keyboard layouts.

Tip: To make sure you return the correct character, use event.key instead

which

The which property returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event.

The difference between the two code types:

  • Character codes - A number which represents an ASCII character ("W" = the number "87")

  • Key codes - A number which represents an actual key on the keyboard

These types do not always mean the same thing; for example, a lower case "w" and an upper case "W" have the same keyboard code, because the key that is pressed on the keyboard is the same (just "W" = the number "87"), but a different character code because the resulting character is different (either "w" or "W", which is "119" or "87")

Tip: To find out if the user is pressing a printable key (e.g. "a" or "5"), it is recommended to use this property on the onkeypress event. To find out if the user is pressing a function key (e.g. "F1", "CAPS LOCK" or "Home") use the onkeydown or onkeyup event.

Tip: For a list of all Unicode characters, please study our Complete Unicode Reference.

Tip: If you want to convert the returned Unicode value into a character, use the fromCharCode() method.

Note: This property is read-only.

Note: The latest version of the DOM Events Specification recommend using the key property instead (if available).

Tip: If you want to find out whether the "ALT", "CTRL", "META" or "SHIFT" key was pressed when a key event occured, use the altKey, ctrlKey, metaKey or shiftKey property.

charCode

The charCode property returns the Unicode character code of the key that triggered the onkeypress event.

The Unicode character code is the number of a character (e.g. the number "97" represents the letter "a").

Tip: For a list of all Unicode characters, please study our Complete Unicode Reference.

Tip: If you want to convert the Unicode value into a character, use the fromCharCode() method.

Note: If this property is used on onkeydown or onkeyup events, the returned value is always "0".

Note: This property is read-only.

location

The location property returns a number that indicates the location of a key on the keyboard or device.

The number is represented by 4 constants:

0. DOM_KEY_LOCATION_STANDARD:

The key is not pressed on the right or left side of the keyboard, and was not pressed on the numeric keypad (this value represents almost every key on the keyboard, e.g. "A", "U", "SPACE" or "5")

1. DOM_KEY_LOCATION_LEFT:

A left key was pressed (e.g. the left "CTRL" key or left "ALT" key on a standard 101 key US keyboard)

2. DOM_KEY_LOCATION_RIGHT:

A right key was pressed (e.g. the right "CTRL" key or right "CTRL" key on a standard 101 key US keyboard)

3. DOM_KEY_LOCATION_NUMPAD:

The key was pressed on the numeric keypad (e.g. the "2" key on the right side on a standard keyboard)

Note: The location property can only be used on the onkeydown and onkeyup event, not onkeypress.

Note: This property is read-only.

repeat

Returns whether a key is being hold down repeatedly, or not

ctrlKey

The ctrlKey property returns a Boolean value that indicates whether or not the "CTRL" key was pressed when a key event was triggered.

Note: This property is read-only.

altKey

The altKey property returns a Boolean value that indicates whether or not the "ALT" key was pressed when a key event was triggered.

Note: On some Mac keyboards, the "ALT" key is displayed as "Option" or "Opt".

Note: This property is read-only.

shiftKey

The shiftKey property returns a Boolean value that indicates whether or not the "SHIFT" key was pressed when a key event was triggered.

Note: This property is read-only.

metaKey

The metaKey property returns a Boolean value that indicates whether or not the "META" key was pressed when a key event was triggered.

Not all keyboards have the meta key. It is common for Sun microsystem keyboards, and MIT and LISP machine keyboards. The meta key is either labeled "META" or marked with a solid diamond "◆" symbol.

On Mac keyboards, the META key is represented by the the "Command/Cmd" ("⌘") key.

Note: This property is read-only.

isComposing

Returns whether the state of the event is composing or not

getModifierState()

The getModifierState() method returns true if the specified modifier key was pressed, or activated.

Modifier keys that are activated only when they are being pressed down:

  • Alt

  • AltGraph

  • Control

  • Meta

  • Shift

Modifier keys that are activated when they are clicked, and deactivated when they are clicked again:

  • CapsLock

  • NumLock

  • ScrollLock

event.getModifierState(modifierKey)

Inherited Properties and Methods

The KeyboardEvent inherits all the properties and methods from:

  • The UiEvent

Touch Events

Events that occur when user touches a touch-based device, belongs to the TouchEvent Object.

ontouchstart

The touchstart event occurs when the user touches an element.

Note: The touchstart event will only work on devices with a touch screen.

ontouchmove

The touchmove event occurs when the user moves the finger across the screen.

The touchmove event will be triggered once for each movement, and will continue to be triggered until the finger is released.

ontouchend

The touchend event occurs when the user removes the finger from an element.

ontouchcancel

The touchcancel event occurs when the touch event gets interrupted.

Different devices will interrupt a touch event at different actions, and it is considered good practice to include this event to clean up code if this "error" should occur.

Properties and Methods

touches

The touches property returns an array of Touch objects, one for each finger that is currently touching the surface.

Note: This property is read-only.

targetTouches

The targetTouches property returns an array of Touch objects, one for each finger that is touching the current target element.

Note: This property is read-only.

changeTouches

Returns a list of all the touch objects whose state changed between the previous touch and this touch

ctrlKey

Returns whether the "CTRL" key was pressed when the key event was triggered

altKey

Returns whether the "ALT" key was pressed when the key event was triggered

shiftKey

Returns whether the "SHIFT" key was pressed when the key event was triggered

metaKey

Returns whether the "meta" key was pressed when the key event was triggered

Inherited Properties and Methods

The TouchEvent inherits all the properties and methods from:

  • The UiEvent

Animation Events

Events that occur when a CSS animation runs, belongs to the AnimationEvent Object.

animationstart

The event occurs when a CSS animation has started

animationend

The event occurs when a CSS animation has completed

animationiteration

The animationiteration event occurs when a CSS animation is repeated.

If the CSS animation-iteration-count property is set to "1", meaning that the animation will only be played one time, the animationiteration event does not occur. The animation needs to run more than once for this event to fire.

Properties and Methods

animationName

The animationName property returns the name of the animation, when an animation event occurs.

The name of the animation is the value of the animation-name CSS property.

This property is read-only.

propertyName

The propertyName property returns the name of the CSS property associated with the transition, when a transitioneventoccurs.

This property is read-only.

pseudoElement

Returns the name of the pseudo-element of the animation or transition

elapsedTime

The elapsedTime property returns the number of seconds an animation has been running, when an animation event occurs.

Note: The return value is not affected if the animation is paused (by using the animation-delay CSS property).

Note: For the animationstart event, this property always returns "0".

This property is read-only.

Transition Events

Events that occur when a CSS transition runs, belongs to the TransitionEvent Object.

transitionend

The transitionend event occurs when a CSS transition has completed.

Note: If the transition is removed before completion, e.g. if the CSS transition-property property is removed, the transitionend event will not fire.

Properties and Methods

propertyName

The propertyName property returns the name of the CSS property associated with the transition, when a transitioneventoccurs.

This property is read-only.

elapsedTime

The elapsedTime property returns the number of seconds a transition has been running, when a transitionend event occurs.

Note: The return value is not affected if the transition is paused (by using the transition-delay CSS property).

This property is read-only.

Input Events

Events that occur when an form element's content changes, belongs to the InputEvent Object.

oninput

The event occurs when an element gets user input

Properties and Methods

inputType

The oninput event occurs when an element gets user input.

This event occurs when the value of an <input> or <textarea> element is changed.

Tip: This event is similar to the onchange event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed. The other difference is that the onchange event also works on <select> elements.

data

The data property returns the character that was inserted with the event.

Nope: This property is read-only.

dataTransfer

Returns an object containing the data being dragged/dropped, or inserted/deleted

isComposing

Returns whether the state of the event is composing or not

getTargetRanges()

Returns an array containing target ranges that will be affected by the insertion/deletion

Inherited Properties and Methods

The InputEvent inherits all the properties and methods from:

  • The UiEvent

UI Events

Events that are triggered from the user interface belongs to the UiEvent Object.

select

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.

resize

The onresize event occurs when the browser window has been resized.

scroll

The onscroll event occurs when an element's scrollbar is being scrolled.

load

The onload event occurs when an object has been loaded.

onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

The onload event can also be used to deal with cookies (see "More Examples" below).

unload

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.).

Nope: The onunload event is also triggered when a user reloads the page (and the onload event).

beforeunload

The onbeforeunload event occurs when the document is about to be unloaded.

This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page.

The default message that appears in the confirmation box, is different in different browsers. However, the standard message is something like "Are you sure you want to leave this page?". This message cannot be removed.

However, you can write a custom message together with the default message. See the first example on this page. Note: This only works in Internet Explorer.

Nope: If the onbeforeunload event is not assigned to the <body> element, you must assign/attach the event on the window object, and use the returnValue property to create a custom message (see syntax examples below).

abort

The onabort event occurs when the loading of an audio/video is aborted.

This event occurs when the media data download has been aborted, and not because of an error.

error

The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).

Properties and Methods

detail

The detail property returns a number with details about the event.

When used on onclick and ondblclick, the number indicates the current click count.

When used on onmousedown and onmouseup,the number indicates the current click count plus 1.

Nope: This property is read-only.

view

The view event property returns a reference to the Window object where the event occured.

Page Transition Events

Events that occur when user navigates to, and away from, a webpage.

pagehide

The onpagehide event occurs when the user is navigating away from a webpage.

There are several ways to navigate away from a page. E.g. by clicking on a link, refreshing the page, submitting a form, closing the browser window, etc.

The onpagehide event is sometimes used instead of the onunload event, as the onunload event causes the page to not be cached.

To find out if a page is loaded directly from the server or if the page is cached, you can use the persisted property of the PageTransitionEvent object. This property returns true if the page is cached by the browser, and false otherwise.

pageshow

The onpageshow event occurs when a user navigates to a webpage.

The onpageshow event is similar to the onload event, except that it occurs after the onload event when the page first loads. Also, the onpageshow event occurs every time the page is loaded, whereas the onload event does not occur when the page is loaded from the cache.

Properties and Methods

persisted

The persisted property returns a Boolean value that indicates if the webpage is loaded directly from the server, or if the page is cached, when an onpageshow or onpagehide event occurs.

  • true - The page is cached by the browser

  • false - The page is NOT cached by the browser

Progress Events

Events that occur when loading external resources, belongs to the ProgressEvent Object.

onerror

The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).

onloadstart

The onloadstart event occurs when the browser starts looking for the specified audio/video. This is when the loading process starts.

Properties and Methods

total

Returns the total amount of work that will be loaded

lengthComputable

Returns whether the length of the progress can be computable or not

loaded

Returns how much work has been loaded

Storage Events

Events that occur when there is changes in the window's storage area.

Storage

The event occurs when a Web Storage area is updated

Properties and Methods

storageArea

The storageArea property returns the Storage Object of the changed storage item.

Nope: The storage event is only triggered when a window other than itself makes the changes.

key

The key property returns the name of the changed storage item.

newValue

The newValue property returns the new value of the changed storage item.

oldValue

The oldValue property returns the old value of the changed storage item.

url

Returns the URL of the changed item's document

Pop State Events

Events that occur when the window's history changes.

Popstate

The event occurs when the window's history changes

Properties and Methods

state

Returns an object containing a copy of the history entries

Hash Change Events

Events that occur when the anchor part of the URL changes, belongs to the HashChangeEvent Object.

onhashchange

The onhashchange event occurs when there has been changes to the anchor part (begins with a '#' symbol) of the current URL.

An example of what an anchor part actually is: Assume that the current URL is http://www.example.com/test.htm#part2 - The anchor part of this URL would be #part2.

To invoke this event, you can:

  • Change the anchor part by setting the location.hash or location.href property of the Location Object

  • Navigate to the current page with a different bookmark (Use the "back" or "forward" buttons)

  • Click on a link to a bookmark anchor

Properties and Methods

newURL

The newURL property returns the URL of the document, after the hash (anchor part) has been changed.

This is the URL that was navigated to.

oldURL

The oldURL property returns the URL of the document, before the hash (anchor part) was changed.

This is the URL that was navigated away from.

Focus Events

Events that occur when elements gets or loses focus, belongs to the FocusEvent Object.

onfocus

The onfocus event occurs when an element gets focus.

The onfocus event is most often used with <input>, <select>, and <a>.

Nope: The onfocus event is the opposite of the onblur event.

Nope: The onfocus event is similar to the onfocusin event. The main difference is that the onfocus event does not bubble. Therefore, if you want to find out whether an element or its child gets the focus, you could use the onfocusin event. However, you can achieve this by using the optional useCapture parameter of the addEventListener() method for the onfocus event.

onfocusin

The onfocusin event occurs when an element is about to get focus.

onfocusout

The onfocusout event occurs when an element is about to lose focus.

onblur

The onblur event occurs when an object loses focus.

The onblur event is most often used with form validation code (e.g. when the user leaves a form field).

Properties and Methods

relatedTarget

The relatedTarget property returns the element related to the element that triggered the focus/blur event.

Inherited Properties and Methods

The FocusEvent inherits all the properties and methods from:

  • The UiEvent

Clipboard Events

Events that occur when the clipboard is modified, belongs to the ClipboardEvent Object.

oncopy

The oncopy event occurs when the user copies the content of an element.

Tip: The oncopy event also occurs when the user copies an element, for example, an image, created with the <img> element.

Tip: The oncopy event is mostly used on <input> elements with type="text".

oncut

The oncut event occurs when the user cuts the content of an element.

onpaste

The onpaste event occurs when the user pastes some content in an element.

Properties and Methods

clipboardData

Returns an object containing the data affected by the clipboard operation