Tuesday, August 16, 2016

JavaScript HTML DOM Elements



This page teaches you how to find and access HTML elements in an HTML page.

Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are a couple of ways to do this:
  • Finding HTML elements by id
  • Finding HTML elements by tag name
  • Finding HTML elements by class name
  • Finding HTML elements by CSS selectors
  • Finding HTML elements by HTML object collections

Finding HTML Element by Id

The easiest way to find an HTML element in the DOM, is by using the element id.
This example finds the element with id="intro":

Example

var myElement = document.getElementById("intro");
If the element is found, the method will return the element as an object (in myElement).
If the element is not found, myElement will contain null.

Finding HTML Elements by Tag Name

This example finds all <p> elements:

Example

var x = document.getElementsByTagName("p");
This example finds the element with id="main", and then finds all <p> elements inside "main":

Example

var x = document.getElementById("main");
var y = x.getElementsByTagName("p");

Finding HTML Elements by Class Name

If you want to find all HTML elements with the same class name, use getElementsByClassName().

This example returns a list of all elements with class="intro".

Example

var x = document.getElementsByClassName("intro");
Finding elements by class name does not work in Internet Explorer 8 and earlier versions.

Finding HTML Elements by CSS Selectors

If you want to find all HTML elements that matches a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the querySelectorAll() method.

This example returns a list of all <p> elements with class="intro".

Example

var x = document.querySelectorAll("p.intro");
The querySelectorAll() method does not work in Internet Explorer 8 and earlier versions.

Finding HTML Elements by HTML Object Collections

This example finds the form element with id="frm1", in the forms collection, and displays all element values:

Example

var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length; i++) {
    text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;

Friday, August 12, 2016

JavaScript HTML DOM EventListener



The addEventListener() method

Example

Add an event listener that fires when a user clicks a button:
document.getElementById("myBtn").addEventListener("click", displayDate);
The addEventListener() method attaches an event handler to the specified element.
The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
You can add many event handlers to one element.
You can add many event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener() method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
You can easily remove an event listener by using the removeEventListener() method.

Syntax

element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like "click" or "mousedown").
The second parameter is the function we want to call when the event occurs.
The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional.
Note that you don't use the "on" prefix for the event; use "click" instead of "onclick".

Add an Event Handler to an Element

Example

Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click", function(){ alert("Hello World!"); });
You can also refer to an external "named" function:

Example

Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click", myFunction);

function myFunction() {
    alert ("Hello World!");
}

Add Many Event Handlers to the Same Element

The addEventListener() method allows you to add many events to the same element, without overwriting existing events:

Example

element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
You can add events of different types to the same element:

Example

element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);

Add an Event Handler to the Window Object

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

Example

Add an event listener that fires when a user resizes the window:
window.addEventListener("resize", function(){
    document.getElementById("demo").innerHTML = sometext;
});

Passing Parameters

When passing parameter values, use an "anonymous function" that calls the specified function with the parameters:

Example

element.addEventListener("click", function(){ myFunction(p1, p2); });

Event Bubbling or Event Capturing?

There are two ways of event propagation in the HTML DOM, bubbling and capturing.
Event propagation is a way of defining the element order when an event occurs. If you have a <p> element inside a <div> element, and the user clicks on the <p> element, which element's "click" event should be handled first?
In bubbling the inner most element's event is handled first and then the outer: the <p> element's click event is handled first, then the <div> element's click event.
In capturing the outer most element's event is handled first and then the inner: the <div> element's click event will be handled first, then the <p> element's click event.
With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter:
addEventListener(event, function, useCapture);
The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.

Example

document.getElementById("myP").addEventListener("click", myFunction, true);
document.getElementById("myDiv").addEventListener("click", myFunction, true);

The removeEventListener() method

The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:

Example

element.removeEventListener("mousemove", myFunction);

Browser Support

The numbers in the table specifies the first browser version that fully supports these methods.
Method




addEventListener() 1.0 9.0 1.0 1.0 7.0
removeEventListener() 1.0 9.0 1.0 1.0 7.0
Note: The addEventListener() and removeEventListener() methods are not supported in IE 8 and earlier versions and Opera 6.0 and earlier versions. However, for these specific browser versions, you can use the attachEvent() method to attach an event handlers to the element, and the detachEvent() method to remove it:
element.attachEvent(event, function);
element.
detachEvent(event, function);

Example

Cross-browser solution:
var x = document.getElementById("myBtn");
if (x.addEventListener) {                    // For all major browsers, except IE 8 and earlier    x.addEventListener("click", myFunction);
} else if (x.attachEvent) {                  // For IE 8 and earlier versions    x.attachEvent("onclick", myFunction);
}

HTML DOM Event Object Reference

For a list of all HTML DOM events, look at our complete HTML DOM Event Object Reference.

JavaScript HTML DOM



With the HTML DOM, JavaScript can access and change all the elements of an HTML document.

The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects

DOM HTML tree
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
  • JavaScript can change all the HTML elements in the page
  • JavaScript can change all the HTML attributes in the page
  • JavaScript can change all the CSS styles in the page
  • JavaScript can remove existing HTML elements and attributes
  • JavaScript can add new HTML elements and attributes
  • JavaScript can react to all existing HTML events in the page
  • JavaScript can create new HTML events in the page

What You Will Learn

In the next chapters of this tutorial you will learn:
  • How to change the content of HTML elements
  • How to change the style (CSS) of HTML elements
  • How to react to HTML DOM events
  • How to add and delete HTML elements

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
  • Core DOM - standard model for all document types
  • XML DOM - standard model for XML documents
  • HTML DOM - standard model for HTML documents

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:
  • The HTML elements as objects
  • The properties of all HTML elements
  • The methods to access all HTML elements
  • The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

HTML DOM addEventListener() Method


Element Object Reference Element Object

Example

Attach a click event to a <button> element. When the user clicks on the button, output "Hello World" in a <p> element with id="demo":
document.getElementById("myBtn").addEventListener("click", function(){
    document.getElementById("demo").innerHTML = "Hello World";
});
More "Try it Yourself" examples below.

Definition and Usage

The addEventListener() method attaches an event handler to the specified element.
Tip: Use the removeEventListener() method to remove an event handler that has been attached with the addEventListener() method.
Tip: Use the document.addEventListener() method to attach an event handler to the document.

Browser Support

The numbers in the table specify the first browser version that fully supports the method.
Method




addEventListener() 1.0 9.0 1.0 1.0 7.0
Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions, and Opera 6.0 and earlier versions. However, for these specific browser versions, you can use the attachEvent() method to attach event handlers (see "More Examples" below for a cross-browser solution).

Syntax

element.addEventListener(event, function, useCapture)

Parameter Values

Parameter Description
event Required. A String that specifies the name of the event.

Note: Do not use the "on" prefix. For example, use "click" instead of "onclick".

For a list of all HTML DOM events, look at our complete HTML DOM Event Object Reference.
function Required. Specifies 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.
useCapture Optional. A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.

Possible values:
  • true - The event handler is executed in the capturing phase
  • false- Default. The event handler is executed in the bubbling phase

Technical Details

DOM Version: DOM Level 2 Events
Return Value: No return value
Changelog: The useCapture parameter became optional in Firefox 6 and Opera 11.60 (has always been optional for Chrome, IE and Safari)

HTML DOM Events



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).
Tip: The event model was standardized by the W3C in DOM Level 2.

HTML DOM Events

DOM: Indicates in which DOM Level the property was introduced.

Mouse Events

Event Description DOM
onclick The event occurs when the user clicks on an element 2
oncontextmenu The event occurs when the user right-clicks on an element to open a context menu 3
ondblclick The event occurs when the user double-clicks on an element 2
onmousedown The event occurs when the user presses a mouse button over an element 2
onmouseenter The event occurs when the pointer is moved onto an element 2
onmouseleave The event occurs when the pointer is moved out of an element 2
onmousemove The event occurs when the pointer is moving while it is over an element 2
onmouseover The event occurs when the pointer is moved onto an element, or onto one of its children 2
onmouseout The event occurs when a user moves the mouse pointer out of an element, or out of one of its children 2
onmouseup The event occurs when a user releases a mouse button over an element 2

Keyboard Events

Event Description DOM
onkeydown The event occurs when the user is pressing a key 2
onkeypress The event occurs when the user presses a key 2
onkeyup The event occurs when the user releases a key 2

Frame/Object Events

Event Description DOM
onabort The event occurs when the loading of a resource has been aborted 2
onbeforeunload The event occurs before the document is about to be unloaded 2
onerror The event occurs when an error occurs while loading an external file 2
onhashchange The event occurs when there has been changes to the anchor part of a URL 3
onload The event occurs when an object has loaded 2
onpageshow The event occurs when the user navigates to a webpage 3
onpagehide The event occurs when the user navigates away from a webpage 3
onresize The event occurs when the document view is resized 2
onscroll The event occurs when an element's scrollbar is being scrolled 2
onunload The event occurs once a page has unloaded (for <body>) 2

Form Events

Event Description DOM
onblur The event occurs when an element loses focus 2
onchange The event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <keygen>, <select>, and <textarea>) 2
onfocus The event occurs when an element gets focus 2
onfocusin The event occurs when an element is about to get focus 2
onfocusout The event occurs when an element is about to lose focus 2
oninput The event occurs when an element gets user input 3
oninvalid The event occurs when an element is invalid 3
onreset The event occurs when a form is reset 2
onsearch The event occurs when the user writes something in a search field (for <input="search">) 3
onselect The event occurs after the user selects some text (for <input> and <textarea>) 2
onsubmit The event occurs when a form is submitted 2

Drag Events

Event Description DOM
ondrag The event occurs when an element is being dragged 3
ondragend The event occurs when the user has finished dragging an element 3
ondragenter The event occurs when the dragged element enters the drop target 3
ondragleave The event occurs when the dragged element leaves the drop target 3
ondragover The event occurs when the dragged element is over the drop target 3
ondragstart The event occurs when the user starts to drag an element 3
ondrop The event occurs when the dragged element is dropped on the drop target 3

Clipboard Events

Event Description DOM
oncopy The event occurs when the user copies the content of an element  
oncut The event occurs when the user cuts the content of an element  
onpaste The event occurs when the user pastes some content in an element  

Print Events

Event Description DOM
onafterprint The event occurs when a page has started printing, or if the print dialogue box has been closed 3
onbeforeprint The event occurs when a page is about to be printed 3

Media Events

Event Description DOM
onabort The event occurs when the loading of a media is aborted 3
oncanplay The event occurs when the browser can start playing the media (when it has buffered enough to begin) 3
oncanplaythrough The event occurs when the browser can play through the media without stopping for buffering 3
ondurationchange The event occurs when the duration of the media is changed 3
onemptied The event occurs when something bad happens and the media file is suddenly unavailable (like unexpectedly disconnects) 3
onended The event occurs when the media has reach the end (useful for messages like "thanks for listening") 3
onerror The event occurs when an error occurred during the loading of a media file 3
onloadeddata The event occurs when media data is loaded 3
onloadedmetadata The event occurs when meta data (like dimensions and duration) are loaded 3
onloadstart The event occurs when the browser starts looking for the specified media 3
onpause The event occurs when the media is paused either by the user or programmatically 3
onplay The event occurs when the media has been started or is no longer paused 3
onplaying The event occurs when the media is playing after having been paused or stopped for buffering 3
onprogress The event occurs when the browser is in the process of getting the media data (downloading the media) 3
onratechange The event occurs when the playing speed of the media is changed 3
onseeked The event occurs when the user is finished moving/skipping to a new position in the media 3
onseeking The event occurs when the user starts moving/skipping to a new position in the media 3
onstalled The event occurs when the browser is trying to get media data, but data is not available 3
onsuspend The event occurs when the browser is intentionally not getting media data 3
ontimeupdate The event occurs when the playing position has changed (like when the user fast forwards to a different point in the media) 3
onvolumechange The event occurs when the volume of the media has changed (includes setting the volume to "mute") 3
onwaiting The event occurs when the media has paused but is expected to resume (like when the media pauses to buffer more data) 3

Animation Events

Event Description DOM
animationend The event occurs when a CSS animation has completed 3
animationiteration The event occurs when a CSS animation is repeated 3
animationstart The event occurs when a CSS animation has started 3

Transition Events

Event Description DOM
transitionend The event occurs when a CSS transition has completed 3

Server-Sent Events

Event Description DOM
onerror The event occurs when an error occurs with the event source  
onmessage The event occurs when a message is received through the event source  
onopen The event occurs when a connection with the event source is opened  

Misc Events

Event Description DOM
onmessage The event occurs when a message is received through or from an object (WebSocket, Web Worker, Event Source or a child frame or a parent window) 3
onmousewheel Deprecated. Use the onwheel event instead  
ononline The event occurs when the browser starts to work online 3
onoffline The event occurs when the browser starts to work offline 3
onpopstate The event occurs when the window's history changes 3
onshow The event occurs when a <menu> element is shown as a context menu 3
onstorage The event occurs when a Web Storage area is updated 3
ontoggle The event occurs when the user opens or closes the <details> element 3
onwheel The event occurs when the mouse wheel rolls up or down over an element 3

Touch Events

Event Description DOM
ontouchcancel The event occurs when the touch is interrupted  
ontouchend The event occurs when a finger is removed from a touch screen  
ontouchmove The event occurs when a finger is dragged across the screen  
ontouchstart The event occurs when a finger is placed on a touch screen  

Event Object

Constants

Constant Description DOM
CAPTURING_PHASE The current event phase is the capture phase (1) 1
AT_TARGET The current event is in the target phase, i.e. it is being evaluated at the event target (2) 2
BUBBLING_PHASE The current event phase is the bubbling phase (3) 3

Properties

Property Description DOM
bubbles Returns whether or not a specific event is a bubbling event 2
cancelable Returns whether or not an event can have its default action prevented 2
currentTarget Returns the element whose event listeners triggered the event 2
defaultPrevented Returns whether or not the preventDefault() method was called for the event 3
eventPhase Returns which phase of the event flow is currently being evaluated 2
isTrusted Returns whether or not an event is trusted 3
target Returns the element that triggered the event 2
timeStamp Returns the time (in milliseconds relative to the epoch) at which the event was created 2
type Returns the name of the event 2
view Returns a reference to the Window object where the event occured 2

Methods

Method Description DOM
preventDefault() Cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur 2
stopImmediatePropagation() Prevents other listeners of the same event from being called 3
stopPropagation() Prevents further propagation of an event during event flow 2

MouseEvent Object

Property Description DOM
altKey Returns whether the "ALT" key was pressed when the mouse event was triggered 2
button Returns which mouse button was pressed when the mouse event was triggered 2
buttons Returns which mouse buttons were pressed when the mouse event was triggered 3
clientX Returns the horizontal coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered 2
clientY Returns the vertical coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered 2
ctrlKey Returns whether the "CTRL" key was pressed when the mouse event was triggered 2
detail Returns a number that indicates how many times the mouse was clicked 2
metaKey Returns whether the "META" key was pressed when an event was triggered 2
pageX Returns the horizontal coordinate of the mouse pointer, relative to the document, when the mouse event was triggered  
pageY Returns the vertical coordinate of the mouse pointer, relative to the document, when the mouse event was triggered  
relatedTarget Returns the element related to the element that triggered the mouse event 2
screenX Returns the horizontal coordinate of the mouse pointer, relative to the screen, when an event was triggered 2
screenY Returns the vertical coordinate of the mouse pointer, relative to the screen, when an event was triggered 2
shiftKey Returns whether the "SHIFT" key was pressed when an event was triggered 2
which Returns which mouse button was pressed when the mouse event was triggered 2

KeyboardEvent Object

Property Description DOM
altKey Returns whether the "ALT" key was pressed when the key event was triggered 2
ctrlKey Returns whether the "CTRL" key was pressed when the key event was triggered 2
charCode Returns the Unicode character code of the key that triggered the onkeypress event 2
key Returns the key value of the key represented by the event 3
keyCode 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 2
location Returns the location of a key on the keyboard or device 3
metaKey Returns whether the "meta" key was pressed when the key event was triggered 2
shiftKey Returns whether the "SHIFT" key was pressed when the key event was triggered 2
which 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 2

HashChangeEvent Object

Property Description DOM
newURL Returns the URL of the document, after the hash has been changed
oldURL Returns the URL of the document, before the hash was changed

PageTransitionEvent Object

Property Description DOM
persisted Returns whether the webpage was cached by the browser  

FocusEvent Object

Property Description DOM
relatedTarget Returns the element related to the element that triggered the event 3

AnimationEvent Object

Property Description DOM
animationName Returns the name of the animation
elapsedTime Returns the number of seconds an animation has been running

TransitionEvent Object

Property Description DOM
propertyName Returns the name of the CSS property associated with the transition
elapsedTime Returns the number of seconds a transition has been running

WheelEvent Object

Property Description DOM
deltaX Returns the horizontal scroll amount of a mouse wheel (x-axis) 3
deltaY Returns the vertical scroll amount of a mouse wheel (y-axis) 3
deltaZ Returns the scroll amount of a mouse wheel for the z-axis 3
deltaMode Returns a number that represents the unit of measurements for delta values (pixels, lines or pages) 3