Events

Published Jul 30, 2021Updated May 15, 2024
Contribute to Docs

Events are things that happen in HTML objects that can trigger scripting code. JavaScript can be executed by events in HTML via two methods:

  • The JavaScript code can appear within the appropriate HTML attribute in the HTML object.
  • Or a separate script can define an event handler on the object that executes when the event is fired.

Syntax 1

You can assign JavaScript code to an event attribute in an HTML object.

<!-- Clicking pops up a "Hello World!" dialog box -->
<button onclick="window.alert('Hello World!');">Click Me!</button>

Syntax 2

There’s HTML on the page with the object of interest.

<button id="hello-button">Click Me!</button>

In a separate script the object is referred to and assigned an event handler.

// Clicking the "hello-button" button pops up a "Hello World!" dialog box
var btn = document.getElementById('hello-button');
btn.addEventListener('click', () => {
window.alert('Hello World!');
});

All contributors

Looking to contribute?

Learn JavaScript on Codecademy