HTML DOM - Events
HTML DOM allows JavaScript to react to HTML events.
Examples
Reacting to Events
When an event occurs, JavaScript can be executed, such as when a user clicks an HTML element.
To execute code when a user clicks an element, add JavaScript code to the HTML event attribute:
Examples of HTML events:
- When the user clicks the mouse
- When a web page has loaded
- When an image has loaded
- When the mouse moves over an element
- When an input field is changed
- When an HTML form is submitted
- When the user presses a key
In this example, the content of the <h1> element is changed when the user clicks:
In this example, a function is called from the event handler:
Examples
Try it Yourself »
HTML Event Attributes
To assign events to HTML elements, you can use event attributes.
Examples
Assign an onclick event to a button element:
Try it Yourself »
In the example above, a function named displayDate is executed when the button is clicked.
Assigning Events Using the HTML DOM
The HTML DOM allows you to assign events to HTML elements using JavaScript:
Examples
Assign an onclick event to a button element:
Try it Yourself »
In the example above, a function named displayDate is assigned to the HTML element with id="myBtn".
When the button is clicked, the function will be executed.
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 version, in order to load different versions of the web page based on this information.
The onload and onunload events can be used to handle cookies.
onchange Event
The onchange event is often used for validation of input fields.
The following example shows how to use onchange. When the user changes the content of an input field, the upperCase() function will be called.
onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger functions when the mouse pointer moves over or leaves an element.
onmousedown, onmouseup, and onclick Events
The onmousedown, onmouseup, and onclick events are the entire process 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.
HTML DOM Event Object Reference Manual
For a complete description and examples of each event, please visit ourHTML DOM Reference Manual。
Other Extensions