Preventing the Default Action

Learn about preventing the default action of an element and explore its use cases.

What is eventObj.preventDefault()?

In jQuery, we can prevent an element’s default behavior by calling the eventObj.preventDefault() method inside the event handler function.

For example, in the page HTML below, we have a hyperlink (<a>) element with the attribute href set to "https://www.educative.come". By default, if we click on this element, we are redirected to the link within href.

However, to prevent this default behavior, we can assign a click event handler to this hyperlink element. Then we call the eventObj.preventDefault() method within the event handler function, shown in the highlighted line below. Now when we click on the hyperlink element, we are not redirected to the link within href. Instead, an alert is generated with text “Default hyperlink behavior prevented.”

Why prevent the default action?

In various jQuery tasks, the preventDefault() method is extremely helpful. To understand why we need to prevent the default action, look at the following example.

Consider a simple web page:

Let’s say we want the user to be directed to Educative’s platform if, and only if, the user checks and agrees to certain terms and conditions. In other words, we want the hyperlink to work only if the checkbox is marked. This can be achieved using the preventDefault() method.

In the jQuery code below, we assign a click event handler to the hyperlink object. We verify if the checkbox is checked in line 3 using the is() method. You can look into the is() method here. If the box is unchecked, we call eventObj.preventDefault() in line 5 and generate an alert box notifying the user to mark the checkbox.

The example discussed above showcases one of the many scenarios where preventDeafult() comes in handy. You can easily imagine many other similar scenarios. Moreover, preventDefault() is also used within AJAX to avoid page reload.