Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Events

JavaScript Events


HTML events are things that happen to HTML elements.

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


HTML Events

HTML events can be browser actions or user actions.

The following are examples of HTML events:

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, using JavaScript code to add HTML elements.

Single quotes:



Double quotes:



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

Example

<button onclick="getElementById('demo').innerHTML=Date()">

What is the time now?

button

Try it »

In the example above, 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 (using this.innerHTML):

Example

<button onclick="this.innerHTML=Date()">

What is the time now?

button

Try it »

Note JavaScript code is usually several lines. It is more common to call it through an event attribute:

Example

<button onclick="displayDate()">

What is the time now?

button

Try it »


Common HTML events

The following is a list of some common HTML events:

Events Description
onchange An HTML element has changed
onclick A 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 A user presses a keyboard key
onload The browser has finished loading the page

More event list: JavaScript Reference - HTML DOM Events。


What can JavaScript do?

Events can be used to handle form validation, user input, user actions, and browser actions:

There are several ways to execute JavaScript event code:

Note In the HTML DOM chapter you will learn more about events and event handlers.