JavaScript Events
HTML Events
An HTML event can be an action performed by the web browser or an action initiated by a user.
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 allows you to run code whenever certain actions happen.
HTML lets you add event handler attributes to HTML elements using JavaScript code.
With single quotes:
With double quotes:
In this example, we're adding an action called onclick
to a button element <button>
.
In the provided example, the JavaScript code alters the information inside an element that has an identifier called demo.
In this next example, the code modifies what's inside its own box (by using this.innerHTML
):
JavaScript code is often several lines long. It is more common to see event attributes calling functions:
Common HTML Events
Here is a list of a few frequently used events in HTML:
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 |
JavaScript Event Handlers
Event handlers help manage and check what users type or do on a website, as well as how the web browser behaves:
- Things that should be done every time a page loads
- Things that should be done when the page is closed
- Action that should be performed when a user clicks a button
- Content that should be verified when a user inputs data
- And more ...
There are various ways to make JavaScript interact with events.
- 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 ...