To understand those concepts, you should understand the meaning of propagation. Elements in a document are nested in a tree. Consider this example.
What happens if I click the anchor tag? Let's instead of saying click, saying trying to kill the anchor tag.
You try to kill the anchor tag. It tries to defend itself, and by default, it calls for help from his father (the p tag), and p in turn calls for help from his father (the div
tag). Now what if anchor is powerful enough to defend itself and stop you killing it (handle you)? Is there any necessity to call for help? No? Then how to stop that default behavior. This is done through e.stopPropagation()
for example.
Now consider that anchor tag always bites to defend itself. But this time, because you want to kill it, it should use a gun. How to override that biting default behavior? e.preventDefault()
is the answer.
Now, let's go back to our main story. When you click an anchor tag, what would be the default behavior of it? It simply follows the link, causing you to leave current page. But sometimes we developers want the anchor tag to respond differently. In other words, sometimes we want to tell it, "hey anchor tag, I know that you always go to another web page, but please, this time don't do that". We achieve this purpose using e.preventDefault()
function;
