JavaScript Events
HTML events are things that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can react to 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:
HTML page has finished loading
HTML input field was changed
HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
Single quotes:
Double quotes:
In the following example, an onclick
attribute (with code) is added to a button element:
Example
<button onclick="getElementById('demo').innerHTML=Date()">What is the time now?</button>
In this example, 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()">What is the time now?</button>
| | JavaScript code is often several lines long. It is common to call a function instead: | | --- | --- |
Example
<button onclick="displayDate()">What is the time now?</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 presses a keyboard key |
onload | The browser has finished loading the page |
For a full list of events, see: JavaScript Reference - HTML DOM Events.
What can JavaScript Do?
Events can be used to handle form validation, user input, user actions, and browser actions:
Trigger an event when the page loads
Trigger an event when the page is closed
Perform an action when a user clicks a button
Validate user input
And more...
There are many ways to execute JavaScript event code:
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...
| | You will learn more about events and event handlers in the HTML DOM chapter. <br> | | --- | --- |