What is the use of preventDefault() Method in jQuery

| | 1 min read

The preventDefault() method is used to stop any element form behaving its default behaviour. For example, if we have a hyperlink linked to a particular location. Using preventDefault() function we can restrict it from navigating to it the by a custom location in our javascript. You can use the method isDefaultPrevented to know whether this method was ever called (on that event object).

The event.preventDefault() method stops the default action of an element to happen. Possible examples for event.preventDefault() are,

  • Detain's from submitting a form by the submit button.
  • Prevent a link from following the URL.

    Syntax

    Below is the syntax used for the method:

    event.preventDefault()

    Parameters

    Here is a description on all parameters used by this method:

    event - The event comes from the event binding function

    Example:

    Following is a simple example showing the usage of this method. This example demonstrates how you can stop the browser from changing the page to the href of any anchors.

    Add following code to your js file,

    $(document).ready(function() {
      $("a").click(function(event) {
        event.preventDefault();
        alert( "Behaviour changed!" );
      });
    });

    Often event.preventDefault() compare with return false; But return false do three thnings on calling it,
    return false is doing 2 separate things when you call it:

    • e.preventDefault
    • e.stopPropagation

    e.preventDefault() will prevent the default behavious from happening, e.stopPropagation() will prevent the event from popping up and return false.