Respond to Events
We can execute JavaScript when an event occurs, such as when a user clicks on an HTML element.
To execute code when a user taps an element, add JavaScript code to an HTML event property:
Examples of HTML events:
- When the user clicks the mouse
- When the page is loaded
- When the image is loaded
- When the mouse moves over the element
- When the input field is changed
- When you submit an HTML form
- When the user triggers the button
<H1 onclick= "this.innerhtml= ' ooops! '" > Tap text!//Tap text, text content changes
HTML Event Properties
// assign the OnClick event to the button element:<button onclick= "displaydate ()" >try it</button>
Use HTML DOM to assign events
<script>document.getElementById ("mybtn"). onclick=function() {displaydate ()}; </script>
In the example above, a function named Displaydate is assigned to the HTML element of Id=mybutn ". The JavaScript function will be executed when the button is clicked.
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 detect the browser type and browser version of the visitor and to load the correct version of the Web page based on that information.
The onload and OnUnload events can be used to process cookies.
onchange Events
OnChange events are often used in conjunction with validation of input fields.
onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when a user moves the mouse over an HTML element or moves out of an element.
OnMouseDown, onmouseup, and onclick events
OnMouseDown, onmouseup, and onclick form all parts of the mouse click event. First, when the mouse button is clicked, the OnMouseDown event is triggered, and when the mouse button is released, the OnMouseUp event is triggered, and the onclick event is triggered when the mouse click is completed.
JavaScript HTML DOM Events