Lecture 7
JavaScript Events
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these
events.
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
Each available event has an event handler, which is a block of code (usually a
JavaScript function that you as a programmer create) that will be run when the
event fires.
HTML allows event handler attributes, with JavaScript code, to be added to
HTML elements.
With single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
In the following example, an onclick attribute (with code), is added to
a <button> element:
Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The
time is?</button>
In the example above, the JavaScript code changes the content of the element
with id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
Example
<button onclick="displayDate()">The time is?</button>
Common HTML Events
Here is a list of some common HTML events:
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
What can JavaScript Do?
Event handlers can be used to handle, and verify, user input, user actions, and
browser actions:
Things that should be done every time a page loads
Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data
And more ...
Many different methods can be used to let JavaScript work with events:
HTML event attributes can execute JavaScript code directly
HTML event attributes can call JavaScript functions
You can assign your own event handler functions to HTML elements
You can prevent events from being sent or being handled
And more ...
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
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 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.
JavaScript - HTML DOM Methods
HTML DOM methods are actions you can perform (on HTML Elements).
HTML DOM properties are values (of HTML Elements) that you can set or
change.
The DOM Programming Interface
The HTML DOM can be accessed with JavaScript (and with other programming
languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an
HTML element).
A method is an action you can do (like add or deleting an HTML element).
Example
The following example changes the content (the innerHTML) of the <p> element
with id="demo":
Example
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
In the example above, getElementById is a method, while innerHTML is
a property.
The getElementById Method
The most common way to access an HTML element is to use the id of the
element.
In the example above the getElementById method used id="demo" to find the
element.
The innerHTML Property
The easiest way to get the content of an element is by using
the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML
elements.
The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.
JavaScript HTML DOM Document
The HTML DOM document object is the owner of all other objects in your
web page.
The HTML DOM Document Object
The document object represents your web page.
If you want to access any element in an HTML page, you always start with
accessing the document object.
Below are some examples of how you can use the document object to access
and manipulate HTML.
Finding HTML Elements
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
Changing HTML Elements
Property Description
element.innerHTML = new html content Change the inner HTML of an eleme
element.attribute = new value Change the attribute value of an HT
element.style.property = new style Change the style of an HTML elemen
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HT
Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream
Adding Events Handlers
Method Description
document.getElementById(id).onclick = function(){code} Adding event handler code to a
Finding HTML Objects
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections,
and properties. These are still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were
added.
Property Description
document.anchors Returns all <a> elements that have a name attribute
document.applets Returns all <applet> elements (Deprecated in HTML5)
document.baseURI Returns the absolute base URI of the document
document.body Returns the <body> element
document.cookie Returns the document's cookie
document.doctype Returns the document's doctype
document.documentElement Returns the <html> element
document.documentMode Returns the mode used by the browser
document.documentURI Returns the URI of the document
document.domain Returns the domain name of the document server
document.domConfig Obsolete. Returns the DOM configuration
document.embeds Returns all <embed> elements
document.forms Returns all <form> elements
document.head Returns the <head> element
document.images Returns all <img> elements
document.implementation Returns the DOM implementation
document.inputEncoding Returns the document's encoding (character set)
document.lastModified Returns the date and time the document was updated
document.links Returns all <area> and <a> elements that have a href at
document.readyState Returns the (loading) status of the document
document.referrer Returns the URI of the referrer (the linking document)
document.scripts Returns all <script> elements
document.strictErrorChecking Returns if error checking is enforced
document.title Returns the <title> element
document.URL Returns the complete URL of the document
JavaScript HTML DOM Events
HTML DOM allows JavaScript to react to HTML events:
Mouse Over Me
Click Me
Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on
an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an
HTML event attribute:
onclick=JavaScript
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks
on it:
Example
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!</h1>
</body>
</html>
In this example, a function is called from the event handler:
Example
<!DOCTYPE html>
<html>
<body>
<h1 onclick="changeText(this)">Click on this text!</h1>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
HTML Event Attributes
To assign events to HTML elements you can use event attributes.
Example
Assign an onclick event to a button element:
<button onclick="displayDate()">Try it</button>
Try it Yourself »
In the example above, a function named displayDate will be executed when the
button is clicked.
Assign Events Using the HTML DOM
The HTML DOM allows you to assign events to HTML elements using JavaScript:
Example
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick = displayDate;
</script>
In the example above, a function named displayDate is assigned to an HTML
element with the id="myBtn".
The function will be executed when the button is clicked.
The onload and onunload Events
The onload and onunload events are triggered when the user enters or leaves
the page.
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 and onunload events can be used to deal with cookies.
Example
<body onload="checkCookies()">
The onchange Event
The onchange event is often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will
be called when a user changes the content of an input field.
Example
<input type="text" id="fname" onchange="upperCase()">
The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when
the user mouses over, or out of, an HTML element:
Mouse Over Me
The onmousedown, onmouseup and onclick
Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click.
First when a mouse-button is clicked, the onmousedown event is triggered,
then, when the mouse-button is released, the onmouseup event is triggered,
finally, when the mouse-click is completed, the onclick event is triggered.