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 boxvar btn = document.getElementById('hello-button');btn.addEventListener('click', () => {window.alert('Hello World!');});
Contribute to Docs
- 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.
Learn JavaScript on Codecademy
- Skill path
Create a Back-End App with JavaScript
Learn how to build back-end web APIs using Express.js, Node.js, SQL, and a Node.js-SQLite database library.Includes 8 CoursesWith CertificateBeginner Friendly30 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours