In this lesson, you will learn how to respond to user clicks using the addEventListener method in JavaScript. Understanding this method is crucial because it allows you to create interactive web applications.
When you click a button or a link on a website, it often triggers an action. For example, when you click a “Submit” button in a form, it sends your information somewhere. Using the addEventListener method helps you control what happens when the user clicks. As a result, you can enhance the user experience significantly.
File: button-click.js
// Select the button element
const button = document.getElementById('myButton');
// Add a click event listener
button.addEventListener('click', function() {
alert('Button clicked!');
});
Expected Output:
A pop-up alert saying "Button clicked!" when the button is clicked.
In the code above, we first select a button using document.getElementById. Then we use addEventListener to listen for the click event. When the button is clicked, the function runs and shows an alert. This shows how dynamic JavaScript can make your web pages.
Now, create a button on your page with an ID of “myButton”. Add your own message to the alert that shows when the button is clicked. This will help you practice using the addEventListener method. To get started, refer back to our previous lesson on connecting JavaScript files.
// Select the button element
const button = document.getElementById('myButton');
// Add a click event listener
button.addEventListener('click', function() {
alert('You have clicked the button!');
});
getElementById.addEventListener properly by typing it out correctly. For instance, check for any typos.addEventListener to watch for user clicks.For more JavaScript concepts, check our previous lesson.