Preventing Default Behavior And Event Propagation
When an event occurs on an element, it can trigger a default behavior associated with that event, such as submitting a form when the user clicks on the submit button. However, sometimes we may want to prevent that default behavior from occurring, or stop the event from propagating further to other elements.
1. preventDefault()
We can prevent the default behavior of an event by calling the preventDefault() method on the event object.
Example : <!DOCTYPE html> <html> <head> <title>Prevent form submission</title> </head> <body> <form> <label for="name">Name:</label> <input type="text" id="name" name="name"> <br><br> <label for="email">Email:</label> <input type="email" id="email" name="email"> <br><br> <button type="submit" id="submitBtn">Submit</button> </form> </body> <script> const form = document.querySelector('form'); const submitBtn = document.getElementById('submitBtn'); submitBtn.addEventListener('click', (event) => { event.preventDefault(); console.log('Form not submitted.'); // do something else instead of submitting the form }); </script> </html>
Output :


Explanation :
In this example, we use querySelector to select the form element, and getElementById to select the submit button. We then add an event listener to the submit button that calls the preventDefault() method to prevent the form from being submitted, and logs a message to the console.
2. stopPropagation()
We can also stop an event from propagating further to other elements by calling the stopPropagation() method on the event object.
Example :<!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"> <title>Document</title> </head> <body> <div id="parent"> <button id="child">Click me</button> </div> </body> <script> const parent = document.querySelector('#parent'); const child = document.querySelector('#child'); child.addEventListener('click', (event) => { event.stopPropagation(); console.log('Child element clicked'); }); parent.addEventListener('click', (event) => { console.log('Parent element clicked'); }); </script> </html>
Output :


Explanation :
This HTML code creates a parent div element with a child button element inside it. The JavaScript code adds event listeners to both the parent and child elements for the click event. When the child button is clicked, its event listener is triggered first and logs a message to the console. The event propagation to the parent element is stopped using the stopPropagation() method of the event object, so the parent element’s event listener is not triggered. If the parent element is clicked instead, only the parent’s event listener is triggered, and the console logs a message reflecting that.
No Comment! Be the first one.