What is event.preventDefault() and event.stopPropagation()?
Two event methods that control different things.
preventDefault() — cancels the browser's default action (e.g. stop a form submitting or a link navigating).
stopPropagation() — stops the event travelling further through the DOM (no more bubbling/capturing).
Independent: one blocks the default behaviour, the other blocks the event's journey — use either or both.
// preventDefault — stop default browser action
form.addEventListener('submit', (e) => {
e.preventDefault(); // No page reload!
submitViaAjax(form);
});
link.addEventListener('click', (e) => {
e.preventDefault(); // No navigation!
openModal(link.href);
});
// stopPropagation — stop event traveling
// <div class="card" onclick="selectCard()">
// <button class="delete">Delete</button>
// </div>
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation(); // Card click handler does NOT fire
deleteItem();
});
// Both together
link.addEventListener('click', (e) => {
e.preventDefault(); // Don't navigate
e.stopPropagation(); // Don't bubble to parent
openInNewTab(link.href);
});preventDefault stops the browser action (form submit, link navigation). stopPropagation stops the event from reaching parent elements. The delete button inside a clickable card needs stopPropagation to prevent the card's click handler from firing when the delete button is clicked.
preventDefault = stop browser default (form reload, link navigation). stopPropagation = stop event from reaching other elements. The delete-button-in-clickable-card is the classic stopPropagation example.
Both can be used together.