JavaScript Events


HTML events are things that happen to HTML elements.

When using JavaScript in an HTML page, JavaScript can trigger these events.


HTML Events

HTML events can be browser behaviors or user behaviors.

Here are some examples of HTML events:

  • An HTML page finishes loading
  • An HTML input field changes
  • An HTML button is clicked

Usually, when an event occurs, you can do something.

When an event is triggered, JavaScript can execute some code.

Event attributes can be added to HTML elements, and JavaScript code can be used to add HTML elements.

Single quotes:

<some-HTML-element some-event='JavaScript 代码'>

Double quotes:

<some-HTML-element some-event="JavaScript 代码">

In the following example, an onclick attribute (with code) is added to a button element:

Examples

<button onclick="getElementById('demo').innerHTML=Date()">The time is?</button>

Try it Yourself »

In the above example, the JavaScript code modifies the content of the element with id="demo".

In the next example, the code will modify the content of its own element (usingthis.innerHTML):

Examples

<button onclick="this.innerHTML=Date()">The time is?</button>

Try it Yourself »

Note JavaScript code is usually several lines of code. The more common way is to call it through event attributes:

Examples

<button onclick="displayDate()">The time is?</button>

Try it Yourself »


Common HTML Events

Below is a list of some common HTML events:

Event Description
onchange An HTML element changes
onclick The user clicks an HTML element
onmouseover Occurs when the mouse pointer moves over a specified element
onmouseout Occurs when the user moves the mouse away from an HTML element
onkeydown The user presses a keyboard key
onload The browser has finished loading the page

More event lists: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 events when the page loads
  • Trigger events when the page closes
  • Perform actions when the user clicks a button
  • Validate the legality of user input content
  • And so on ...

There are multiple 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 events from occurring.
  • And so on ...
Note In the HTML DOM chapter, you will learn more about events and event handlers.
Other Extensions