What are preventDefault() and stopPropagation() methods?

Have you ever thought of changing the default behavior of buttons, links, inputs etc.? Like stopping a link from navigating on click or stopping a form from submitting data on click of submit or stopping an input text box from writing anything while typing. Or have you ever wonder in nested elements if you click on child element why the parent element’s click event gets triggered right after child element’s click event?

Well, all of these behaviors you can get rid of with the help of preventDefault() and stopPropagation() methods.

The preventDefault() method

The preventDefault() method cancels the event or stops the browser from showing the default behavior if the event is cancelable.

For example: Preventing the default behavior of a link:

<a href="https://www.google.com" id="link"> Google.com </a>
document.getElementById('link').addEventListener('click', function(event){
    event.preventDefault();
});

Preventing a form to submit on click of submit button:

<form id="form">
     <input type="text" />
     <input type="checkbox" />
 </form>
document.getElementById('form').addEventListener('submit', function(event){
     event.preventDefault();
 });

In the same way you can prevent the default behavior of other input elements.

The preventDefault() method works for those events which are cancelable.

To check whether an event is cancelable or not, use the cancelable property.

 document.getElementById('elemId').addEventListener(click, function(event){
      const isCancelable = event.cancelable;
      console.log(isCancelable); // returns true if event is cancelable
 });

The stopPropagation() method

When there are nested elements present and both the elements have click events, then if you click on the child element, both child and parent click events will get triggered. This happens due to event propagation or bubbling.

To prevent such propagation we use stopPropagation().

For example, We have two nested buttons and both have click events.

<button onclick="clickParent()">
      Parent button
      <button onclick="clickChild()"> Child button </button>
</button>
function clickParent(event) {
    alert('Parent clicked')
}
  
function clickChild(event) {
    alert('Child clicked')
}

Now if you click the “parent button”, clickParent function will execute, but if you will click the “child button”, then first clickChild function will execute and then clickParent function will execute subsequently.

Let’s use stopPropagation() to prevent the event from bubbling.

function clickChild(event) {
    alert('Child clicked');
    event.stopPropagation();
}

Now if you’ll click on the “child button” it won’t bubble the event to the “parent button”.

Leave a Reply

Your email address will not be published. Required fields are marked *