JavaScript Event defaultPrevented Property: Checking if Default Actions Are Prevented

The defaultPrevented property of a JavaScript Event object is a read-only boolean value that indicates whether the default action associated with the event has been prevented by a call to the preventDefault() method. Understanding how to use this property is crucial for managing event behavior and creating custom interactions on your web pages.

What is the defaultPrevented Property?

When an event occurs in the browser (e.g., a user clicks a link, submits a form, or presses a key), the browser often has a default action associated with it. For example, clicking a link navigates the user to the linked URL. The preventDefault() method allows you to stop this default behavior, giving you control over what happens in response to the event. The defaultPrevented property reflects whether this prevention has taken place.

  • Boolean Value: The property returns true if preventDefault() was called on the event, and false otherwise.
  • Read-Only: You cannot set this property directly; it’s a reflection of the event’s current state.
  • Event Information: It provides a way to verify whether the default action was prevented, allowing you to conditionally execute code.

Purpose of the defaultPrevented Property

The primary purpose of this property is to enable you to:

  • Verify Prevention: Check if an event’s default action has been blocked.
  • Conditional Execution: Implement logic that depends on whether the default action was prevented.
  • Event Debugging: Help diagnose event-related issues, especially when dealing with complex event handling scenarios.
  • Custom Control: Build more flexible and controlled user interfaces by managing default event actions.

Syntax

The syntax to access the defaultPrevented property is straightforward:

event.defaultPrevented

Where event is an Event object. This will return true if preventDefault() has been called on the event, otherwise it returns false.

Examples

Let’s explore various examples demonstrating how to use the defaultPrevented property effectively.

Basic Example: Checking Default Action of a Link Click

In this example, we prevent the default navigation of a link and then check if the default action was prevented.

<a href="https://www.codelucky.com" id="linkPreventDefault">
  Visit CodeLucky.com
</a>
<div id="output1"></div>

<script>
  const linkPreventDefault = document.getElementById("linkPreventDefault");
  const output1 = document.getElementById("output1");

  linkPreventDefault.addEventListener("click", function (event) {
    event.preventDefault();
    output1.textContent =
      "Default action prevented: " + event.defaultPrevented;
  });
</script>

Here, we use preventDefault() to stop the browser from navigating to the specified URL. The defaultPrevented property confirms that the default action was indeed blocked.

Example with a Form Submit Event

This example demonstrates how to use defaultPrevented with form submission. If the form is invalid, submission is prevented.

<form id="myForm">
  <input type="text" id="myInput" required />
  <button type="submit">Submit</button>
</form>
<div id="output2"></div>

<script>
  const myForm = document.getElementById("myForm");
  const output2 = document.getElementById("output2");

  myForm.addEventListener("submit", function (event) {
    if (!myForm.checkValidity()) {
      event.preventDefault();
      output2.textContent =
        "Form submission prevented: " + event.defaultPrevented;
    } else {
        output2.textContent =
        "Form submission default action: " + event.defaultPrevented;
    }
  });
</script>


If the input field is empty, the checkValidity() method returns false. The submission is cancelled by preventDefault() and defaultPrevented property confirms that. If you enter some text in the input field, the form submission will not be prevented and the defaultPrevented will be false.

Checking defaultPrevented After an Event

Here we check defaultPrevented property after an event is triggered.

    <button id="checkButton">Click Me</button>
    <div id="output3"></div>

<script>
    const checkButton = document.getElementById('checkButton');
    const output3 = document.getElementById('output3');
    let event_check = null;

    checkButton.addEventListener('click', (event) => {
        event_check = event;
        event.preventDefault(); // Prevent default click
    });

    checkButton.addEventListener('contextmenu', function(event){
         output3.textContent = `Right Click Default Prevented: ${event.defaultPrevented}`;
         event.preventDefault();
    });

    // Set timeout to check the defaultPrevented after some delay.
    setTimeout(() => {
        if(event_check){
           output3.textContent = `Click Default Prevented: ${event_check.defaultPrevented}`;
           event_check = null; //Reset event
        }
    }, 100);
</script>

In this example, the default behavior of the button click and context menu (right click) are prevented. The code demonstrates the usage of defaultPrevented property after the event has happened.

Browser Support

The defaultPrevented property is supported in all modern browsers, ensuring consistent behavior across different platforms.

Browser Support
Chrome Full Support
Firefox Full Support
Safari Full Support
Edge Full Support
Opera Full Support

Tips and Notes

  • Event Bubbling: Remember that events bubble up the DOM tree. If you call preventDefault() on an event handler at one level, it may affect handlers at higher levels. 🫧
  • Conditional Prevention: Use the defaultPrevented property to conditionally execute code based on whether the default behavior has been prevented.
  • Debugging: Use console.log() and debugger to inspect the event object and its defaultPrevented property. 🐞
  • User Experience: Be careful when preventing default actions; ensure your custom behavior provides a smooth user experience. ⚠️

Conclusion

The defaultPrevented property in JavaScript provides vital functionality for managing and controlling the default behavior of events. By leveraging this property, you can create more dynamic and interactive web applications while ensuring a controlled and predictable user experience. Understanding and utilizing this property is an essential skill for any web developer working with events.