JavaScript Events
HTML events are "things" that happen to HTML elements.
When using JavaScript in an HTML page, JavaScript can "handle" these events.
HTML events
HTML events can be something that browsers or users do.
Below are some examples of HTML events:
- HTML web page is fully loaded
- HTML input field is modified
- HTML button is clicked
通常,when an event occurs, users usually want to do something.
JavaScript allows you to execute code when an event is detected.
Through JavaScript code, HTML allows you to add event handlers to HTML elements.
Use single quotes:
<element event='Some JavaScript>
Use double quotes:
<element event="Some JavaScript">
In the following example,onclick
Attributes (and code) are added to <button>
Element:
Example
<button onclick='document.getElementById("demo").innerHTML=Date()'>What time is it now?</button>
In the above example, the JavaScript code changed the content of the element with id="demo".
In the following examples, the code (using this.innerHTML
)Changed the content of its own element:
Example
<button onclick="this.innerHTML=Date()">What time is it now?</button>
JavaScript code usually has many lines. It is more common to call functions via event attributes:
Example
<button onclick="displayDate()">What time is it now?</button>
Common HTML events
Below are some common HTML events:
Event | Description |
---|---|
onchange | The HTML element has been changed |
onclick | The user clicks the HTML element |
onmouseover | The user moves the mouse over the HTML element |
onmouseout | The user moves the mouse away from the HTML element |
onkeydown | The user presses a keyboard key |
onload | The browser has finished loading the page |
A more complete list:CodeW3C.com JavaScript Reference Manual HTML DOM Events.
What can JavaScript do?
Event handlers can be used to handle, validate user input, user actions, and browser actions:
- What should be done every time the page is loaded
- What should be done when the page is closed
- The action that should be executed when the user clicks the button
- The content that should be validated when the user enters data
- And so on
There are many different ways to let JavaScript handle events:
- HTML event properties can execute JavaScript code
- HTML event properties can call JavaScript functions
- You can assign your own event handler function to HTML elements
- You can prevent events from being sent or handled
- And so on
You will learn more about events and event handlers in the HTML DOM chapter.