JS Events
JavaScript's interaction with HTML is handled through events.
HTML events are “things” that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can “react” on 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:
- An HTML web page has finished loading
- An HTML input field was changed
- An 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.
<element event='some JavaScript'>
Changing HTML Using Events
In the following example, JavaScript changes the content of the element from which it was called, using this.innerHTML.
Event Handlers with Functions
It is common to call a JavaScript function when an event happens, keeping your HTML clean.
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 pushes a keyboard key |
onload | The browser has finished loading the page |