JavaScript events allow developers to execute code when something happens on a web page, like a user clicking a button. However, sometimes you may want to prevent the default browser behavior tied to an event, like following a link or submitting a form. In JavaScript, there are a few main ways to cancel events:

Using event.preventDefault()

The easiest way to cancel an event‘s default behavior is by calling the preventDefault() method on the event object. For example:

const link = document.getElementById(‘myLink‘);

link.addEventListener(‘click‘, (event) => {
  event.preventDefault();

  // Custom code here  
}); 

When the #myLink element is clicked, calling event.preventDefault() will stop the browser from following the link. This allows you to run custom JavaScript code instead.

Under the hood, preventDefault() sets the cancelable property on the event object to true. Browsers know that if an event is marked as cancelable, they shouldn‘t perform the default action.

One key thing about preventDefault() is that it only works on cancelable events. According to the DOM spec, things like submitting forms, clicking links, and touching elements are cancelable by default. However, other events like scroll, resize, load, etc are not. Calling preventDefault() on a non-cancelable event will simply do nothing.

Real World Examples

Canceling link clicks is a very common use case for preventDefault(). For example, say you wanted to override all external links to show a confirmation dialog instead:

// Get all links
const links = document.querySelectorAll(‘a‘);

// Add click event listener
links.forEach(link => {

  link.addEventListener(‘click‘, (e) => {

    // Check if external link
    if (!link.href.startsWith(window.location.origin)) {

      // Cancel default behavior  
      e.preventDefault();

      // Show confirm dialog 
      if (confirm(‘Leave site?‘)) { 
        window.location = link.href; 
      }

    }

  });

});

The key thing here is that we call preventDefault() which stops the browser from following the link. Then we manually check if the user confirmed navigation before setting window.location.

This kind of advanced event handling isn‘t possible without first canceling the default behavior.

Another common use case is canceling form submission:

const form = document.getElementById(‘signup‘);

form.addEventListener(‘submit‘, (e) => {

  // Validate fields
  if (firstName.value === ‘‘) {
    alert(‘Please enter your first name.‘);

    // Cancel submit
    e.preventDefault(); 
  } else {
    form.submit(); 
  }

});

Here we want to validate user input before allowing the form submit. Calling preventDefault() avoids submitting the form until validation passes. Then we can manually submit the form with form.submit().

Returning false

An older technique that still works in some browsers is returning false from an event handler function. For example:

const link = document.getElementById(‘termsLink‘);

link.addEventListener(‘click‘, () => {

  // Custom code

  return false;

});

When false is returned from the listener, the browser knows not to execute the default action.

However, support for this technique is a bit spotty across browsers. Chrome stopped supporting return false to prevent default a few versions ago. So I only recommend using event.preventDefault() for consistency.

Using event.stopPropagation()

The event.stopPropagation() method serves a different, but related purpose. While preventDefault() cancels the default browser behavior, stopPropagation() prevents the event from bubbling further up the DOM tree.

For example:

<body onclick="alert(‘body clicked‘)">

  <button onclick="alert(‘button clicked‘); event.stopPropagation()">
    Submit 
  </button>

</body>

Here clicking the button will first show the "button clicked" alert. Normally the click event would then bubble up to the <body> handler and show "body clicked" as well.

But event.stopPropagation() prevents this bubbling from happening. So only the button click alert is shown.

This can be useful for isolating event handling logic. For example, maybe you only want to run certain code when a specific <div> is clicked directly vs bubbled events from children elements.

Using event modifiers

Vue and some other frameworks provide special event modifiers that make canceling events cleaner.

For example, Vue has .prevent and .stop:

<!-- Prevent submit default -->
<form @submit.prevent="onSubmit">

<!-- Stop click propagation -->  
<button @click.stop="handleButtonClick">Click</button>

React doesn‘t have first-class event modifiers. But libraries like react-use provide similar capabilities.

The benefit here is declarative handling without needing manual preventDefault() calls. This helps keep components cleaner and more reusable.

Canceling Other Events

We‘ve focused mainly on click and submit events. But preventDefault() and stopPropagation() work to cancel just about any browser event, including:

  • Scroll events – Prevent scrolling on mobile/desktop
  • Focus events – Stop focus changing on tab keydown
  • Resize events – Stop viewport resizing
  • Clipboard events – Block copy/paste actions
  • Keyboard events – Stop specific key presses
  • Mouse events – Disable right click context menu
  • Touch events – Disable mobile touch capabilities
  • Drag & drop events – Disallow dropping elements
  • Media events – Stop video/audio playback
  • Animation events – Stop CSS keyframe animations
  • Transition events – Halt transition effects

And many more.

The process is the same. You attach an event listener, then call event.preventDefault() to override the native behavior.

For example, to block pinch-to-zoom on touch devices:

document.addEventListener(‘touchmove‘, (e) => {
  if (e.touches.length > 1) {
    e.preventDefault(); 
  }
});

Or to disable the right click context menu:

document.addEventListener(‘contextmenu‘, (e) => {
  e.preventDefault();
}); 

So preventDefault() provides a simple, consistent way to override all kinds of default browser behaviors.

Browser Support

The Event.preventDefault() method has excellent browser support, working in all modern & legacy browsers. Firefox, Chrome, Safari, Edge, Opera, and IE9+ are all supported.

Event.stopPropagation() also has nearly universal browser support. The only exception is IE8 and below.

So unless you need to support extremely outdated browsers, you can safely use these methods. Just be aware that utilizing event cancellation disables default accessibility features. So alternative interfaces will need to be provided for impaired users when necessary.

Summary

Canceling browser events is a powerful technique that unlocks greater control over web page behavior. The main methods to know are:

  • preventDefault() – Stops the default action tied to an event. This disables browser functionality like opening links or submitting forms.
  • stopPropagation() – Stops the event from bubbling up the DOM tree. This contains event handling to a specific target.
  • Returning false – Older technique that works inconsistently across browsers. Generally avoid in favor of preventDefault().
  • Event modifiers – Declarative wrappers like Vue‘s .prevent and .stop that call preventDefault()/stopPropagation() under the hood.

With these tools, you can override and customize all kinds of browser events – clicks, taps, scrolls, media playback, animations, clipboard access, and many more. Just be mindful of accessibility, and ensure your custom interfaces provide adequate functionality when you cancel default behaviors.

Similar Posts