What is the difference between preventDefault and stopPropagation?
These two methods control two completely separate things. preventDefault() stops the browser's own default action for the event, such as following a link, submitting a form, or scrolling to an anchor. stopPropagation() stops the event from travelling any further through the tree, so the listeners on the ancestors never see it at all.
// A tiny stand-in for the DOM that models a cancelable default action.
const link = {
tagName: 'A',
listeners: {},
defaultPrevented: false,
addEventListener(type, handler) {
if (!this.listeners[type]) {
this.listeners[type] = [];
}
this.listeners[type].push(handler);
},
dispatchEvent(event) {
const payload = {
type: event.type,
cancelable: event.cancelable,
defaultPrevented: false,
propagationStopped: false,
preventDefault() {
this.defaultPrevented = true;
},
stopPropagation() {
this.propagationStopped = true;
},
};
const handlers = this.listeners[event.type] || [];
for (const handler of handlers) {
handler(payload);
if (payload.cancelable && payload.defaultPrevented) {
console.log('default action cancelled');
return;
}
}
console.log('default action ran');
},
};
link.addEventListener('click', function (event) {
event.preventDefault(); // stop the browser following the link
event.stopPropagation(); // stop the event going further up
console.log('handled');
});
link.dispatchEvent({ type: 'click', cancelable: true });
There is a third method that completes the picture. The stopImmediatePropagation() method stops the event from travelling and also prevents any other listener on the same element from running. Both preventDefault() and stopPropagation() only act on the current event, and neither of them stops the other listeners on the same element from being called.
One detail matters a great deal in practice. preventDefault() only works when the event is cancelable, and not every event is cancelable. The click event on a link is cancelable, but the load event on an image is not, so calling preventDefault() on it does nothing at all. The cancelable property on the event tells you which kind of event you are holding.
Another detail is worth remembering. The browser only respects preventDefault() for the default action of that event. It has no effect on what your own code does, so if your handler has already run and has already changed something on the page, that change still happened.