JavaScript facilitates the ability to respond to user activity on a web page or application, which is referred to as an event. Javascript has events to provide a dynamic interface to a webpage. Examples of events include button clicks, page scrolling, form submissions, etc. Upon the occurrence of an event, JavaScript allows you to execute specific code that performs a desired action in response. In this article, we will see how to prevent the default action of an event in JavaScript, along with understanding the different methods that can be utilized from preventing the default action of an event with the help of examples.
Sometimes, you may want to prevent the default action of an event from occurring. For example, you may want to perform some custom behavior instead of the default action, or you may want to prevent the default action from happening altogether. To prevent such default action of an event in JavaScript, you can use the preventDefault() method on the event object. This method can be called within the event handler function for the event, and it will stop the browser from executing the default action associated with that event. For instance, if you have a form that you want to validate before it is submitted, you can use the preventDefault() method to stop the form from being submitted if it fails validation:
Syntax:
event.preventDefault();
Javascript default event action: The default action is the action that the browser takes in response to an event, without any additional code or intervention from the developer. For example, when a user clicks on a link, the default action is for the browser to navigate to the URL specified in the link’s href attribute. Similarly, when a user submits a form, the default action is for the browser to send the form data to the server.
Approach to prevent the default action of an event in Javascript: There are several approaches that we can take to prevent the default action of an event in JavaScript, depending on the specific use case and the type of event you are working with. Here are some common approaches, which are described below:
Approach 1: Use the “return false” statement: In some cases, you can prevent the default action of an event by returning false from the event listener function. This approach only works for certain types of events, such as form submissions and links, and it is generally not recommended as it can cause unexpected behavior in some cases.
Syntax:
const form = document.querySelector("form"); form.addEventListener("submit", function () { // Your code to handle the form submit event goes here return false; });
Approach 2: Use the “stopPropagation()” method: The stopPropagation() method can be used to prevent an event from bubbling up to parent elements, which may have their own event listeners that could trigger the default action. Here, we prevent the click event on the child element from bubbling up to the parent element by using the “stopPropagation()” method on the event object.
Syntax:
const child = document.querySelector(".child"); const parent = document.querySelector(".parent"); child.addEventListener("click", function (event) { event.stopPropagation(); // Your code to handle the click event goes here });
Approach 3: Modify the default action using the “returnValue” property: This approach is not recommended, but in some cases, you can modify the default action of an event by setting the returnValue property on the event object. Note that this approach may not work in all browsers, and it is generally better to use the “preventDefault() “method instead.
Syntax:
link.addEventListener("click", function (event) { event.returnValue = false; // Your code to handle the click event goes here });
Approach 4: Use the “preventDefault()” method: This is the most common approach to prevent the default action of an event. The preventDefault() method is available on the event object that is passed to the event listener function, and it can be used to prevent the default action associated with the event. For example, to prevent a link from navigating to a new page when clicked, you can use the following code:
Syntax:
const link = document.querySelector("a"); link.addEventListener("click", function (event) { event.preventDefault(); // Your code to handle the click event goes here });
In general, the preventDefault() method is the recommended approach to prevent the default action of an event in JavaScript, as it is widely supported and provides a clear and consistent way to handle events in a web page or application.
Example 1: Below is an example of Clicking on a “Submit” button, to prevent submitting a form. Here, we first define an <form> element with two <input> fields (course, description) with a submit button. The id attribute is set to “my-form” so that we can reference it in our JavaScript code. After that, we define a JavaScript function that listens for the form’s “submit” event. When the form is submitted, the function first prevents the default form submission behavior using event.preventDefault().
HTML
<!DOCTYPE html> < html > < head > < meta charset = "UTF-8" > < title > Preventing the Javascript default event action </ title > </ head > < body > < h1 >Submit Form Example</ h1 > < form id = "my-form" method = "post" action = "/submit" > < label for = "course" > Course Name: </ label > < input type = "text" id = "course" name = "course" > < br >< br /> < label for = "description" > Description: </ label > < input type = "text" id = "description" name = "description" > < br >< br /> < button type = "submit" > Submit </ button > </ form > < script > const form = document.getElementById('my-form'); form.addEventListener('submit', function (event) { // Prevent the form from submitting event.preventDefault(); // Handle the form submit event const formData = new FormData(form); // Create a new FormData object console.log(formData.get('course')); // Log the value of the 'course' field console.log(formData.get('description')); // Log the value of the 'description' field }); </ script > </ body > </ html > |
Output:
Example 2: In this example, the preventDefault() method should be called before any other actions you want to perform in response to the event. Otherwise, the default action may already have occurred by the time you try to prevent it. To prevent a link from navigating to a new page when clicked, you can use the following code:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta http-equiv = "X-UA-Compatible" content = "IE=edge" > < meta name = "viewport" content=" width = device -width, initial-scale = 1 .0"> < script src = </ script > </ head > < body > < h1 >Example: </ h1 > < p > To prevent a link from navigating to a new page when clicked </ p > < p >Click the Below link:</ p > < a href = neveropen </ a > < script > $(document).ready(function () { $("a").click(function (event) { event.preventDefault(); alert("Link prevented"); }); }); </ script > </ body > </ html > |
Output:
In conclusion, using “preventDefault()” is a useful technique for controlling the behavior of events in JavaScript, and can help you create more robust and user-friendly web applications.