Today I learned, when to use:
event.preventDefault();
event.stopPropagation();
Ever need to have a click event on a child element trigger but not on the parent element?
Anyone use event.preventDefault on a regular basis?
Found a really good explanation with working examples on stack overflow 🎉
Examples 3 and 4, were the aha moment:
https://stackoverflow.com/a/30473685/5283424
I knew the keywords and have used them for specific solutions,
but mostly stayed away and used hacks to get around problems like using: getElementById('').click()
😅
setTimeout(() => {
getElementById('').click()
},100)
<a href='http://stackoverflow.com' onclick='executeChild()'/>
<script>
function doNotNavigate() {
event.preventDefault();
}
</script>
enable click on child element but disable click on parent element
event.stopPropagation();
// see example 4 from this stack overflow: https://stackoverflow.com/a/30473685/5283424
other links:
https://javascript.info/bubbling-and-capturing
https://www.freecodecamp.org/news/event-bubbling-in-javascript
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture
https://blog.logrocket.com/deep-dive-into-event-bubbling-and-capturing/