JavaScript Events
HTML events are things that happen on HTML elements.
JavaScript can trigger these events when used in HTML pages.
HTML events
HTML events can be browser actions or user actions.
The following are examples of HTML events:
HTML page finishes loading
HTML input field changes
HTML button is clicked
Usually, when an event occurs, you can do something.
JavaScript can execute some code when an event is triggered.
Event attributes can be added to HTML elements and HTML elements can be added using JavaScript code.
Single quotes:
<some-HTML-element some-event='some JavaScript'>
Double quotes:
<some-HTML-element some-event="some JavaScript">
In the following example, the onclick attribute (and code) is added to the button element:
Example
<button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>
In the above example, the JavaScript code will modify the id=" demo" element.
In the next example, the code will modify the content of its own element (using this.innerHTML):
Example
<button onclick="this.innerHTML=Date()">The time is?</button>
JavaScript code is usually a few lines of code. The more common ones are called through event attributes:
Instance
<button onclick="displayDate()">The time is?</button>
Common HTML events
The following is a list of some common HTML events:
Event
Description
onchange HTML element change
onclick The user clicks on an HTML element
onmouseover The user moves the mouse on 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 completed loading the page
More Event List: JavaScript Reference Manual - HTML DOM Events.
What can JavaScript do?
Events can be used to handle form validation, user input, user behavior and browser actions:
The event is triggered when the page is loaded
The event is triggered when the page is closed
The user clicks the button to perform the action
Verify the legality of user input
and so on...
You can use multiple methods to execute JavaScript event code:
HTML event attributes can directly execute JavaScript code
HTML event attributes can call JavaScript functions
You can Specify your own event handler for HTML elements
You can prevent events from happening.
And more...
In the HTML DOM chapter you will learn more about events and event handlers.
The above is the content of JavaScript events in [JavaScript Tutorial]. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!