JavaScript Events
HTML events are things that happen to HTML elements.
When JavaScript is used in an HTML page, JavaScript can trigger these events.
HTML Events
HTML events can be browser actions or user actions.
The following are examples of HTML events:
- An HTML page has finished loading
- An HTML input field has changed
- An HTML button was clicked
Usually, when an event occurs, you can do something.
JavaScript can execute some code when an event is triggered.
Event attributes can be added to HTML elements, using JavaScript code to add HTML elements.
Single quotes:
Double quotes:
In the following example, an onclick attribute (with code) is added to the button element:
Example
<button onclick="getElementById('demo').innerHTML=Date()">What is the time now?
button
Try it »
In the example above, the JavaScript code modifies the content of the element with id="demo".
In the next example, the code will modify the content of its own element (using this.innerHTML):
Example
<button onclick="this.innerHTML=Date()">What is the time now?
button
Try it »
![]() |
JavaScript code is usually several lines. It is more common to call it through an event attribute: |
|---|
Example
<button onclick="displayDate()">What is the time now?
button
Try it »
Common HTML events
The following is a list of some common HTML events:
| Events | Description |
|---|---|
| onchange | An HTML element has changed |
| onclick | A user clicks an HTML element |
| onmouseover | Occurs when the mouse pointer moves over a specified element |
| onmouseout | Occurs when the user moves the mouse away from an HTML element |
| onkeydown | A user presses a keyboard key |
| onload | The browser has finished loading the page |
More event list: JavaScript Reference - HTML DOM Events。
What can JavaScript do?
Events can be used to handle form validation, user input, user actions, and browser actions:
- An event is triggered when the page loads
- An event is triggered when the page closes
- A user clicks a button to perform an action
- Validate the legitimacy of user input
- etc. ...
There are several ways to execute JavaScript event code:
- HTML event attributes can directly execute JavaScript code
- HTML event attributes can call JavaScript functions
- You can specify your own event handlers for HTML elements
- You can prevent events from happening.
- etc. ...
![]() |
In the HTML DOM chapter you will learn more about events and event handlers. |
|---|
