Content: How to prevent event bubbling and default events, and precautions for using return false.
JS Event Binding Methods
- Inline binding
- Direct DOM element binding:
btn.onclick - Using
addEventListener/attachEvent
1 | // Inline binding |
Preventing Bubbling:
event.stopPropagation();
event.cancelBubble = true;
1 | // Prevent event bubbling |
Preventing Default Events:
event.preventDefault();
event.returnValue = false;
1 | // Prevent default behavior |
Notes on return false:
- It can only prevent the default behavior when binding events directly to a DOM element;
- It cannot prevent the default behavior when using
addEventListenerfor event binding; return falsecannot stop event propagation in vanilla JS;- In jQuery, it can both stop propagation and prevent default behavior;
1 | // Issues with return false |
Additional Points:
- Inline event handlers like
onclickattribute in HTML should be avoided where possible in favor of unobtrusive JavaScript techniques. - When preventing default behavior, it’s a good practice to do so only if necessary, as it can prevent other event listeners from executing properly if not handled carefully.
- When using
addEventListener, if you want to prevent both default behavior and event bubbling, you need to call bothevent.preventDefault()andevent.stopPropagation()within the event handler function. - The use of
event.returnValueandevent.cancelBubbleis considered old-fashioned and should be replaced withevent.preventDefault()andevent.stopPropagation()respectively, which are standardized across modern browsers.