JavaScript Events

HTML events are things that happen to HTML elements. When using JavaScript in HTML pages, JavaScript can trigger these events.

HTML Events

HTML events can be browser or user behavior.

Here are examples of HTML events:

  • HTML page finishes loading
  • When the HTML input field changes
  • HTML button is clicked

Usually, you can do something when an event occurs.

JavaScript can execute some code when the event fires.

You can add event attributes to HTML elements and use JavaScript code to add HTML elements.

Single quote:

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

With twofold quotes:

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

In the accompanying precedent, an onclick trait (with code), is added to a catch element:


<button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>
Try it Yourself »
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):


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


<button onclick="displayDate()">The time is?</button>
Try it Yourself »

Common HTML Events

Here is a rundown of some regular HTML events:

Event Description
onchange HTML element changes
onclick User clicks on HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user removes the mouse from an HTML element
onkeydown User presses a keyboard key
onload The browser has finished loading the page

What can JavaScript Do?

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

  • Event is triggered when the page loads
  • Event is triggered when the page is closed
  • The user clicks a button to perform an action
  • Verify the legitimacy of user input
  • Wait ...

There are several ways to execute JavaScript event tags:

  • HTML event attributes can execute JavaScript code directly
  • HTML event attributes can call JavaScript functions
  • You can specify your own event handler for HTML elements
  • You can prevent the event from happening.
  • Wait ...
Note You will learn more about events and event handlers in the HTML DOM chapter.