JavaScript Events
HTML events are things that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can trigger these events.
HTML Events
HTML events can be browser behaviors or user behaviors.
The following are examples of HTML events:
HTML page finished loading
When the HTML input field changes
HTML button is clicked
Usually, when an incident occurs, you can do something.
JavaScript can execute some code when the event is triggered.
You can add event attributes to HTML elements, and use JavaScript code to add HTML elements.
apostrophe:
<some-HTML-element some-event = 'JavaScript code'>
Double quotes:
<some-HTML-element some-event = "JavaScript codes">
In the following example, the onclick attribute (plus code) is added to the button element:
Example
<button onclick="getElementById('demo').innerHTML=Date()">What is the time now?</button>
In the above example, the JavaScript code will modify the content of 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()">What is the time now?</button>
![]() | JavaScript code is usually a few lines of code. It is more common to call through the event properties: |
---|
Example
<button onclick="displayDate()">What is the time now?</button>
Common HTML Events
Below is a list of some common HTML events:
Event | Description |
---|---|
onchange | HTML element changes |
onclick | User clicks on HTML element |
onmouseover | The user moves the mouse on an HTML element |
onmouseout | The user removes the mouse from an HTML element |
onkeydown | The user presses a keyboard key |
onload | The browser has finished 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:
Trigger an event when the page loads
Event triggered when the page is closed
The user clicks a button to perform an action
Verify the legitimacy of user input
and many more...
There are several ways 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 handlers for HTML elements
You can prevent the incident from happening.
and many more...
![]() | In the HTML DOM chapter you will learn more about events and event handlers. |
---|