Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Handling User Events with addEventListener

Hello! Welcome back to your front-end development course.

In our last lesson, we built a dynamic to-do list. A key part of that was using addEventListener to run our code when the "Add Task" button was clicked. That was our first taste of making a webpage truly interactive.

Today, we're going to dive deep into that concept. This lesson focuses on the learning outcome: Handle user events including click, submit, and input using addEventListener. Events are the cornerstone of user experience on the web; they are the signals that a user has done something. As a designer, you define how a user should interact with a product; today, you'll learn how to program the application's response to those interactions.

We will cover:

  • The three most common event types for user interaction.
  • How to listen for these events using addEventListener.
  • How to access information about an event, such as which element was clicked or what text was entered.

1. What are Events and Event Listeners?

In JavaScript, an event is an action that occurs in the browser, such as a user clicking a button, submitting a form, or typing in a text field. An event listener is a function that "listens" for a specific event to occur on a specific HTML element and then executes a block of code in response.

The method we use to attach a listener is addEventListener(). Its basic structure is:

element.addEventListener('eventType', functionToRun);
  • eventType: A string that specifies the name of the event (e.g., 'click').
  • functionToRun: The function that will be executed when the event occurs. This is often called a "callback function."

This short video provides a great high-level overview of what event listeners are and what they can do.

Learn JavaScript EventListeners in 4 Minutes

Watch this introduction from the video "Learn JavaScript EventListeners in 4 Minutes" by Coding2GO to get a quick sense of the power of event listeners.

Watch the first 18 seconds of the video for a quick introduction to the concept of event listeners.

2. The click Event

The click event is the most fundamental user interaction. It fires when a user clicks on an element. We already used this in our to-do list, but let's formalize it.

Event listeners in JavaScript - click, submit and change

The video "Event listeners in JavaScript - click, submit and change" by Geekcentric provides a clear, practical example of handling a click event.

Watch the segment from 00:25 to 01:44. Notice the three main steps: 1) select the button, 2) add the event listener for the 'click' event, and 3) define the function to run when the click happens.

As you saw, the process is simple: select an element and attach a listener that performs an action, like logging a message or changing a style.

3. The submit Event and The Event Object

The submit event is specific to <form> elements. It fires when the user attempts to submit the form, either by clicking a <button type="submit"> or pressing Enter in a text field.

Handling form submissions is a little different because browsers have a default behavior: they try to send the form data to a server and reload the page. In modern front-end development, we almost always want to prevent this.

To do that, we need to use the event object. The function you provide to addEventListener automatically receives an argument, which is an object containing details about the event. By convention, we often name this parameter event or just e.

This object has a crucial method: event.preventDefault().

Event listeners in JavaScript - click, submit and change

This next segment from the same Geekcentric video is essential. It demonstrates the default form submission behavior and how to stop it.

Watch from 01:44 to 04:42. Pay close attention to: The page refreshing when the form is submitted initially. How event.preventDefault() is called inside the listener function to stop the refresh. The event parameter being added to the function definition: function(event) { ... }.

Stopping the default page reload is the first and most important step in handling forms with JavaScript. We'll explore preventDefault() in more detail in our next lesson, but for now, just know that you will almost always use it when listening for a submit event.

4. The input Event

The input event is incredibly useful for creating responsive user interfaces. It fires every time the value of an <input>, <select>, or <textarea> element changes. This allows you to react instantly as the user types.

Think about features you've designed:

  • A character counter under a textarea.
  • A password strength indicator that updates as you type.
  • A search bar that shows results as you type.

All of these are powered by the input event.

To get the current value of the input field, we use the event object again. The property event.target refers to the element that the event happened on (in this case, the input field). So, event.target.value gives us the text inside it.

Learn JavaScript EventListeners in 4 Minutes

Let's return to the Coding2GO video to see a great example of the input event in action.

Watch the segment from 03:07 to 03:52. The video demonstrates creating a "live display" that updates a heading with the text from an input field as the user types. Notice the use of event.target.value to get the text.

For a comprehensive reference on addEventListener, the MDN documentation is the industry standard. It's a good habit to consult it when you have questions.

EventTarget: addEventListener() method - Web APIs | MDN

The MDN Web Docs page for addEventListener() is the definitive guide. You don't need to memorize it, but it's good to know where to find authoritative information.

Skim through the introduction, the "Syntax" section, and "The event listener callback" section. This will reinforce the structure and show you the different parameters you can use.

5. Your Turn: Building an Interactive Previewer

Let's combine all three event types to build a small, practical feature: a live profile card previewer. The user will fill out a form, see their information appear on a card in real-time, and then "save" it.

Your Goal: Write the JavaScript to make the profile card interactive.

  1. input events: Update the name and bio on the card as the user types in the form.
  2. submit event: When the form is submitted, prevent the page from reloading and log the final profile data to the console.
  3. click event: When the "Change Theme" button is clicked, toggle a class on the card to change its color.

Here is the starting code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Interactive Profile Previewer</title>
    <style>
        body { font-family: sans-serif; display: flex; justify-content: center; align-items: flex-start; gap: 40px; padding-top: 40px; background-color: #f4f4f9; }
        .form-container, .card-container { background: #fff; padding: 2rem; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); width: 350px; }
        h2 { margin-top: 0; }
        .form-group { margin-bottom: 1rem; }
        label { display: block; margin-bottom: 0.5rem; font-weight: bold; }
        input[type="text"], textarea { width: 100%; padding: 0.5rem; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
        button { width: 100%; padding: 0.75rem; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; }
        .btn-submit { background-color: #007bff; color: white; }
        .btn-theme { background-color: #6c757d; color: white; margin-top: 1rem; }
        .profile-card { border: 1px solid #ddd; padding: 1.5rem; border-radius: 8px; text-align: center; transition: background-color 0.3s, color 0.3s; }
        .profile-card.dark-theme { background-color: #333; color: white; }
        .profile-card h3 { margin: 0 0 0.5rem 0; }
        .profile-card p { margin: 0; color: #666; }
        .profile-card.dark-theme p { color: #ccc; }
    </style>
</head>
<body>

    <div class="form-container">
        <h2>Edit Your Profile</h2>
        <form id="profile-form">
            <div class="form-group">
                <label for="name-input">Name</label>
                <input type="text" id="name-input" value="Jane Doe">
            </div>
            <div class="form-group">
                <label for="bio-input">Bio</label>
                <textarea id="bio-input" rows="3">UI/UX Designer & Problem Solver</textarea>
            </div>
            <button type="submit" class="btn-submit">Save Profile</button>
        </form>
        <button id="theme-btn" class="btn-theme">Change Theme</button>
    </div>

    <div class="card-container">
        <h2>Live Preview</h2>
        <div id="profile-card" class="profile-card">
            <h3 id="card-name">Jane Doe</h3>
            <p id="card-bio">UI/UX Designer & Problem Solver</p>
        </div>
    </div>

    <script>
        // --- Element Selections ---
        const nameInput = document.querySelector('#name-input');
        const bioInput = document.querySelector('#bio-input');
        const profileForm = document.querySelector('#profile-form');
        const themeBtn = document.querySelector('#theme-btn');
        
        const cardName = document.querySelector('#card-name');
        const cardBio = document.querySelector('#card-bio');
        const profileCard = document.querySelector('#profile-card');

        // --- Event Listeners ---

        // 1. Listen for 'input' on the nameInput.
        //    Update cardName.textContent with the input's value.
        nameInput.addEventListener('input', (event) => {
            // YOUR CODE HERE
        });

        // 2. Listen for 'input' on the bioInput.
        //    Update cardBio.textContent with the textarea's value.
        bioInput.addEventListener('input', (event) => {
            // YOUR CODE HERE
        });

        // 3. Listen for 'submit' on the profileForm.
        //    a. Prevent the default form submission.
        //    b. Create an object with the final name and bio.
        //    c. console.log the object.
        profileForm.addEventListener('submit', (event) => {
            // YOUR CODE HERE
        });

        // 4. Listen for 'click' on the themeBtn.
        //    Toggle the 'dark-theme' class on the profileCard.
        themeBtn.addEventListener('click', () => {
            // YOUR CODE HERE
        });
    </script>

</body>
</html>

Your Task:
Copy the code into an HTML file and fill in the // YOUR CODE HERE sections inside the event listeners.

Click here to see the solution
// 1. Listen for 'input' on the nameInput.
nameInput.addEventListener('input', (event) => {
    cardName.textContent = event.target.value;
});

// 2. Listen for 'input' on the bioInput.
bioInput.addEventListener('input', (event) => {
    cardBio.textContent = event.target.value;
});

// 3. Listen for 'submit' on the profileForm.
profileForm.addEventListener('submit', (event) => {
    event.preventDefault(); // a. Prevent default
    const profileData = {
        name: nameInput.value,
        bio: bioInput.value
    }; // b. Create object
    console.log('Profile Saved:', profileData); // c. Log object
});

// 4. Listen for 'click' on the themeBtn.
themeBtn.addEventListener('click', () => {
    profileCard.classList.toggle('dark-theme');
});

Conclusion

Fantastic work! You've now learned how to make a web page react to the user in three fundamental ways. This is the core of front-end development: responding to user input to create a dynamic, living interface.

Key Takeaways:

  • addEventListener is your primary tool for handling user interactions.
  • The click event is for any clickable element.
  • The input event provides real-time feedback from form fields like <input> and <textarea>.
  • The submit event is for capturing form submissions.
  • The event object (e.g., event) provides crucial information, like event.target.value to get data and event.preventDefault() to stop default browser actions.

In this lesson, we saw how critical event.preventDefault() is for handling forms. In the next lesson, we will explore this method in more detail, learning about other default browser actions we might want to prevent, such as following a link, to gain even finer control over the user experience.

Can't find a good explanation? Sign up and we'll make it for you

Sign up