Canceling Events

A handler can cancel what the browser would do next, such as sending a form that failed validation, by calling preventDefault() on the event object the browser passes in.

Journeyman · JavaScript · Updated

After this lesson you can

  • Cancel an event's default action, such as a form submitting, with event.preventDefault()

Key takeaways

  • Many events have a default action, something the browser does by itself. Sending a form, following a link and checking a checkbox are all default actions.
  • Call event.preventDefault() in the handler to cancel the default action. The handler needs the event parameter to do it.
  • stopPropagation() is different. It stops the event moving up to the parent elements, and the default action still happens.

Your code can cancel some of what the browser would do next. For example, if a visitor presses Register with the email box empty, you'd rather keep them on the form than send it half filled in.

Sending the form is the submit event's default action: something the browser does by itself unless a handler cancels it. Other events have default actions too: a click on a link follows the link, and a click on a checkbox checks or unchecks it.

To cancel an event, your event handler must accept the event object as an input parameter. The browser passes the event object to the handler function when the event is raised, and calling its preventDefault() method cancels the default action.

function submitForm(event)
{
    const email = document.getElementById("email");

    if (email.value === "")
    {
        event.preventDefault();
        console.log("Please enter your email address.");
    }
}

// console.log keeps the example short; a real page shows the message next to the box.

const form = document.getElementById("registrationForm");

form.addEventListener("submit", submitForm);

When the email box is empty, the form stays on the page. When it's filled in, the handler doesn't cancel anything, and the form is sent.

preventDefault() isn't stopPropagation()

An event doesn't stop at the element it happened on. After the listeners on a clicked button run, the same click moves up to the button's parent, then to that element's parent, and their click listeners run too. This is called bubbling.

event.stopPropagation() stops the event moving up, so the parents never hear about it. It doesn't cancel the default action: that's what preventDefault() is for.

<div id="productCard">
    <h3>Hiking Boots</h3>
    <button id="addButton">Add to cart</button>
</div>
const card = document.getElementById("productCard");
const addButton = document.getElementById("addButton");

card.addEventListener("click", () => console.log("Open the product"));

addButton.addEventListener("click", (event) => {
    event.stopPropagation();
    console.log("Added to cart");
});

Clicking Add to cart prints only Added to cart. Without stopPropagation(), the card would hear the click too, and print Open the product as well.

Use stopPropagation() rarely: it hides the click from every listener above, including ones you didn't write, such as a menu that closes when you click anywhere else on the page.

Summary

JavaScript applications are event driven applications. A rich user experience means creating an application that gives users intuitive options for interacting with the web page.

When a user triggers an event a JavaScript event handler function is executed.

Additional Event Documentation:

Check yourself

2 questions to try on the lesson page.

So what

The browser does a lot for you by default. preventDefault() is how your code says "not this time", such as when a form isn't ready to be sent.

Key terms