May 09, 2021 HTML DOM
4. Use HTML DOM to assign events
5.. onload and onunload events
9.. onmouseover and onmouseout events
HTML DOM allows JavaScript to react to HTML events.
JavaScript can be performed when an event occurs, such as when a user clicks on an HTML element.
If you need to execute code when a user clicks on an element, add JavaScript code to the HTML event properties:
Examples of HTML events:
In this example, when the user clicks, the contents of the element are changed:
In this case, the function is called from the event handler:
If you need to assign events to HTML elements, you can use event properties.
Assign an onclick event to the button element:
In the example above, when you click the button, a function called displayDate is executed.
HTML DOM allows you to assign events to HTML elements using JavaScript:
Assign the onclick event to the button element:
In the example above, a function named displayDate is assigned to an HTML element of id=myButn".
When the button is clicked, the function is executed.
Onload and onunload events are triggered when a user enters or leaves the page.
The onload event can be used to check the browser type and version of the visitor so that different versions of the page can be loaded based on this information.
Onload and onunload events can be used to process cookies.
Onchange events are often used for validation of input fields.
The following example shows how to use onchange. The upperCase() function is called when the user changes the contents of the input field.
Onmouseover and onmouseout events can be used to trigger functions when the mouse pointer moves to or away from an element.
Onmousedown, onmouseup, and onclick events are all mouse clicks. First, when a mouse button is clicked, the onmousedown event is triggered, then when the mouse button is released, the onmouseup event is triggered, and finally, when the mouse click is complete, the onclick event is triggered.
If you need a complete description and example of each event, visit our HTML DOM reference manual.