Create your own
Lesson illustration

Preventing Default Browser Actions

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

In our last lesson, we learned how to bring a page to life by handling user interactions with addEventListener. We briefly used event.preventDefault() to stop a form from reloading the page. Today, we're going to explore that concept in depth.

This lesson is dedicated to the learning outcome: Prevent the default browser action for events, such as form submissions, using event.preventDefault().

As a UI/UX designer, you spend your time crafting ideal user flows. However, browsers have their own default behaviors that can sometimes disrupt that flow, like a full page reload after a user submits a form. event.preventDefault() is the key JavaScript tool that allows you to override these defaults. Mastering it means you can ensure the application behaves exactly as you designed it to, enabling seamless experiences like in-place form validation or smooth, animated transitions instead of jarring page jumps.

1. Understanding "Default Actions"

First, what exactly is a "default action"? It's the built-in behavior that a browser automatically performs when a specific event occurs on certain HTML elements. These defaults are generally sensible, but often not what we want for a modern, dynamic web application.

Let's watch a quick demonstration of two very common default actions.

EVENT.PREVENTDEFAULT in JavaScript, Simplified

The video "EVENT.PREVENTDEFAULT in JavaScript, Simplified" by Deeecode clearly demonstrates the browser's built-in behavior for forms and links.

Watch the segments from 00:29 to 01:28. Notice what happens when the form is submitted (the page tries to navigate and reload) and when the link is clicked (it navigates to Google). These are the default actions we're about to take control of.

Other default actions include:

  • Pressing a key in a text field causes that character to appear.
  • Clicking a checkbox toggles its checked state.
  • Right-clicking on a page opens the browser's context menu.

event.preventDefault() can be used to stop any of these.

2. How to Prevent Default Actions with event.preventDefault()

When you create an event listener, your callback function automatically receives an event object. This object contains details about the event and, crucially, methods to control it. The most important of these is preventDefault().

Calling event.preventDefault() as the very first line inside your event listener tells the browser, "Stop! Don't do your default thing. I'll handle it from here with my own code."

Let's see this in action.

EVENT.PREVENTDEFAULT in JavaScript, Simplified

Now, let's see how event.preventDefault() gives us control. The same video will now show how to stop those default actions we just observed.

Watch from 01:53 to 04:32. Pay close attention to where event.preventDefault() is called within the event listener function for both the form and the anchor tag. Notice that this single line of code stops the browser's default behavior, allowing the developer's custom code to run instead.

3. The submit Event: The Most Common Use Case

The most critical application of event.preventDefault() is with form submissions. In modern web development, we almost never want the browser to handle form submissions with a full page reload.

Why? Because preventing the default submission allows us to:

  1. Perform Client-Side Validation: Check if the user's input is valid (e.g., is the email field actually an email? is a required field empty?) before sending anything to a server. This provides instant feedback, which is a much better user experience.
  2. Send Data Asynchronously: Use JavaScript to send the form data to a server in the background. The user stays on the same page, and we can show a loading spinner or a success message without any disruptive page refresh. This is the foundation of Single-Page Applications (SPAs).
  3. Provide Custom UX Feedback: Instead of a blank white screen during a page load, we can display a subtle success message, highlight fields with errors, or update a part of the page with the new information.

The Mozilla Developer Network (MDN) provides the definitive documentation on web technologies. It's a great habit to consult it.

HTMLFormElement: submit event - Web APIs | MDN

Let's look at the official documentation for the submit event to solidify our understanding. This MDN page provides a concise and authoritative explanation.

First, read the introduction to understand when the submit event fires. Then, scroll down to the 'Examples' section. Study the short HTML and JavaScript code blocks to see the standard pattern for listening to a submit event and preventing its default action.

4. Your Turn: Adding Validation to the Profile Form

Let's apply this concept to the profile previewer we worked on in the last lesson. Currently, it prevents the form from submitting, but it doesn't check if the user has actually entered any information.

Your Goal: Add simple validation to the form. If the user tries to submit the form with an empty name or bio, you will display an error message instead of logging the data to the console.

Here is the code from our last exercise. I've added a div with the ID error-message to serve as a container for our validation feedback.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Interactive Profile Previewer with Validation</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; }
        .profile-card { border: 1px solid #ddd; padding: 1.5rem; border-radius: 8px; text-align: center; }
        .profile-card h3 { margin: 0 0 0.5rem 0; }
        .profile-card p { margin: 0; color: #666; }
        #error-message { color: #d93025; margin-top: 1rem; font-weight: bold; min-height: 1.2em; }
    </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>
        <div id="error-message"></div>
    </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>
        const nameInput = document.querySelector('#name-input');
        const bioInput = document.querySelector('#bio-input');
        const profileForm = document.querySelector('#profile-form');
        const cardName = document.querySelector('#card-name');
        const cardBio = document.querySelector('#card-bio');
        const errorMessage = document.querySelector('#error-message');

        nameInput.addEventListener('input', (event) => {
            cardName.textContent = event.target.value;
        });

        bioInput.addEventListener('input', (event) => {
            cardBio.textContent = event.target.value;
        });

        profileForm.addEventListener('submit', (event) => {
            // This is the most important line for this lesson!
            event.preventDefault();

            // --- YOUR TASK ---
            // 1. Get the current values from nameInput and bioInput.
            // 2. Check if either value is empty. An empty string is "".
            //    Hint: You can check if a string is empty with `nameInput.value.trim() === ''`. 
            //    The .trim() method removes whitespace from both ends of a string.
            // 3. If either is empty:
            //    - Set the textContent of `errorMessage` to "Name and bio cannot be empty."
            // 4. If both have content:
            //    - Clear any error message by setting `errorMessage.textContent` to "".
            //    - Log the profile data to the console like before.

            // YOUR CODE HERE
        });
    </script>

</body>
</html>

Your Task:
Copy the code above into an HTML file. Open it in your browser and implement the logic described in the // YOUR TASK section. Try submitting the form with an empty field to see your error message appear, and then with content to see the console log.

Click here to see the solution
profileForm.addEventListener('submit', (event) => {
    event.preventDefault();

    const currentName = nameInput.value.trim();
    const currentBio = bioInput.value.trim();

    if (currentName === '' || currentBio === '') {
        // If either field is empty, show an error.
        errorMessage.textContent = "Name and bio cannot be empty.";
    } else {
        // If both fields are filled, clear the error and log the data.
        errorMessage.textContent = "";
        
        const profileData = {
            name: currentName,
            bio: currentBio
        };
        console.log('Profile Saved:', profileData);
    }
});

Conclusion

Excellent work! You've now moved from simply stopping a form submission to using that power to enforce rules and provide immediate, helpful feedback to the user—a core principle of good UX.

Key Takeaways:

  • Browsers have default actions for events like form submit (reload page) and link click (navigate).
  • The event.preventDefault() method, called inside an event listener, stops these default actions from happening.
  • Preventing the default action gives you, the developer, full control to implement custom logic.
  • For forms, this is essential for client-side validation and creating the seamless, asynchronous user experiences that users expect from modern websites.

In this lesson, we took control of the form submission process. In our next lesson, we'll dive deeper into working with form data, learning more efficient ways to read and manipulate the information users provide.

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

Sign up