Hello! Welcome back to our journey of building your first AI-powered web application.
In our last lesson, you took a major step forward by learning how to use JavaScript to dynamically change the content and style of your webpage. You practiced responding to a button click, which is the foundation of all user interaction.
Today, we will deepen that knowledge. This lesson focuses on fully understanding event listeners, the mechanism that makes your JavaScript code react to user actions. We will explore different types of events, solidify the best way to handle them, and, most importantly, learn how to manage form submissions. This is a crucial skill for your project, as it's how you'll capture the user's text to send to the AI.
By the end of this lesson, you will be able to confidently respond to various user events, particularly button clicks and form submissions, setting the stage for connecting your frontend to a backend service.
What are Events and Event Listeners?
In JavaScript, an event is any action that occurs in the browser that the system can recognize. This could be:
- A user clicking a mouse button.
- A user pressing a key on the keyboard.
- A form being submitted.
- The mouse pointer moving over an element.
- A webpage finishing its loading process.
An event listener is a procedure or function in your code that "listens" for a specific event to occur on a specific HTML element. When the event happens, the listener executes a block of code called an event handler.

To start, let's watch a short video that introduces event listeners and the two primary ways to set them up.
Event Listeners - Javascript - Tutorial 14
This video from Giraffe Academy provides a great overview of what event listeners are and demonstrates the two main approaches for using them. Pay close attention to the distinction between the two methods.
Watch the video from the beginning until 05:37. The first part (until 00:48) explains the concept. The second part demonstrates how to add an onclick attribute directly in HTML and how to call a separate function, which is a cleaner approach.
As you saw, you can add an onclick attribute directly to your HTML tags. While this works for very simple cases, it mixes your HTML structure with your JavaScript logic, which is generally considered bad practice. It can make your code harder to read and maintain as your application grows.
The modern, professional, and recommended approach is to keep your HTML and JavaScript separate by using the addEventListener() method.
The Recommended Method: addEventListener()
The addEventListener() method is the standard for registering event handlers. You call it on the HTML element you want to monitor, and you provide two main arguments:
- The name of the event to listen for (e.g.,
'click'). - The function to run when the event occurs (the event handler).

Let's explore the official documentation and a clear example.
Introduction to events - Learn web development | MDN
The Mozilla Developer Network (MDN) is the gold standard for web documentation. This article explains events clearly and reinforces why addEventListener() is the best choice.
First, read the section 'Using addEventListener()'. It breaks down the syntax and shows how to use both a separate, named function and an anonymous (unnamed) function as the handler. Then, read 'Other event listener mechanisms' to understand why the onclick property and inline handlers are not recommended.
Here is the basic pattern you will use most often:
// 1. Select the element you want to listen to.
const analyzeButton = document.querySelector('#analyze-btn');
// 2. Define the handler function that contains the logic.
function handleAnalysis() {
console.log('Analysis started!');
// In our app, this is where we would get the text from the textarea.
}
// 3. Attach the event listener to the element.
analyzeButton.addEventListener('click', handleAnalysis);
Notice that when we pass handleAnalysis to the event listener, we don't include the parentheses (). We are passing the function itself to be called later, not calling it immediately.
Handling Form Submissions: A Special Case
For your AI writing assistant, the user will type text into a <textarea> and click a "submit" button. This will almost certainly be inside an HTML <form> element.
Forms have a default behavior: when a submit event is triggered (e.g., by clicking a <button type="submit">), the browser tries to send the form's data to a server and then reloads the page. For a modern web app like ours, we want to handle this process with JavaScript without a full page reload.
To do this, we need to:
- Listen for the
submitevent on the<form>element itself. - Tell the browser to prevent its default action.
The following video demonstrates this perfectly.
Event listeners in JavaScript - click, submit and change
This video from Geekcentric clearly explains how to handle the submit event and, crucially, how to use event.preventDefault() to stop the default page refresh.
Watch the segment from 01:44 to 05:34. Notice how the page reloads at first, and see how passing the event object to the handler function allows the code to call event.preventDefault() to stop it.
As the video showed, the handler function automatically receives an event object as its first argument. This object contains information about the event that just happened. We can call the .preventDefault() method on this object to stop the browser's default behavior.
Here's how that looks in code for our project:
<!-- In your index.html -->
<form id="text-form">
<textarea id="user-text" placeholder="Enter text here..."></textarea>
<button type="submit">Analyze Text</button>
</form>
<div id="results"></div>
// In your script.js
const textForm = document.querySelector('#text-form');
textForm.addEventListener('submit', function(event) {
// 1. PREVENT THE PAGE RELOAD!
event.preventDefault();
// 2. Now you can safely get the data and process it.
const userText = document.querySelector('#user-text').value;
console.log('Form submitted!');
console.log('User entered:', userText);
// 3. Later, we'll send this text to our backend and display results.
const resultsDiv = document.querySelector('#results');
resultsDiv.textContent = 'Analysis complete for: ' + userText;
});
This pattern is fundamental for nearly all web applications that take user input.
Test your understanding!
You have a simple search form in your HTML: <form id="search-form">. How would you write the JavaScript to listen for its submission and prevent the page from reloading? You don't need to do anything else, just stop the reload.
Show answer
const searchForm = document.querySelector('#search-form');
searchForm.addEventListener('submit', function(event) {
event.preventDefault();
console.log('Default form submission prevented.');
});
Exploring Other Event Types
While click and submit are the most common events you'll use initially, there are many others that can make your application feel more dynamic. For example:
mouseover/mouseout: Fired when the mouse pointer enters or leaves an element.change: Fired when the value of an input element like a dropdown or checkbox changes.keydown: Fired when a user presses any key on the keyboard.
You don't need to memorize these, but it's good to know they exist. The following resource provides a list of common events.
This w3schools page is a handy reference that lists many of the most common HTML events. It's a great page to bookmark for future use.
Briefly review the table under the 'Common HTML Events' heading. This will give you a quick idea of the range of interactions you can listen for.
Conclusion
Great job today! You've moved from simply triggering actions to understanding the formal system of events and listeners that brings a webpage to life. This is the last core piece of frontend interactivity we need before we can start building our backend.
Key Takeaways:
- Events are actions that happen in the browser, like clicks or form submissions. Event Listeners wait for these events to happen and then run an Event Handler function.
- Using
element.addEventListener('eventName', handlerFunction)is the modern and recommended way to manage events, as it keeps your code clean and organized. - For forms, you should listen for the
submitevent on the<form>element itself. - The
event.preventDefault()method is essential for stopping the default browser behavior, like page reloads on form submission.
In the next module, we will shift our focus from the frontend (what the user sees and interacts with) to the backend (the server-side logic). You'll start by installing Flask, a Python web framework, and creating your very first web server. This will be the "brain" that will eventually connect to the Gemini API and perform the text analysis for your application.