JS Events
HTML events are “things” that occur within HTML components.
When JavaScript is used in HTML pages, it can “react” to certain occurrences.
HTML Events
An HTML event can be initiated by either the browser or the user.
Below are some examples of HTML events:
- A page in HTML has completed loading.
- An input field in HTML was altered
- A button for HTML was pressed.
Frequently, you might wish to take action when something happens.
When events are recognized, JavaScript enables code to be executed.
HTML allows you to add event handler properties to HTML elements with JavaScript code.
With single quotes:
In the example below, a onclick attribute (with code) is applied to a <button> element.
Example
-----Example mukavu -----
In the above example, the JavaScript code modifies the content of the element with id=”demo”.
In the following example, the code alters the content of its own element (via this.innerHTML):
Example
----- Example mukavu -----
JavaScript code is frequently many lines lengthy. It is more frequent to find event characteristics that call functions:
Example
Common HTML Events
Below is a list of some typical 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 |
JavaScript Event Handlers
Event handlers can be used to handle and validate user input, user actions, and browser activities:
- What should be done every time a page loads.
- What should be done when the page is closed.
- When a user hits a button, what action should be performed?
- Content that should be validated when a user enters data
- There’s more…
JavaScript may work with events using a variety of techniques, including:
- HTML event properties provide the ability to directly run JavaScript code
- JavaScript functions can be called by HTML event attributes.
- You can designate HTML components with your own custom event handler routines.
- You have the ability to stop events from being transmitted or handled.
- Plus more…
The HTML DOM chapters include a wealth of information on events and event handlers.