Events

christian.dinh2481 total contributions
Published Jul 30, 2021Updated Sep 9, 2021
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 boxvar btn = document.getElementById('hello-button');btn.addEventListener('click', () => {window.alert('Hello World!');});
All contributors
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- StevenSwiniarski475 total contributions
- christian.dinh
- Anonymous contributor
- StevenSwiniarski
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.