what is capture, propagation and bubbling of events? One or more terms are the same thing? Examples!

Asked

Viewed 77 times

0

I have read some posts on the subject, but it is not yet clear the concepts (and mainly examples, simple) on propagation, bubbling and list of events. One of these days, I needed to use Event.preventDefault and I came across such a question.

  • 2

    In that reply I explain the phases of events and propagation... take a look, maybe help you understand.

  • @fernandosavio this answer is excellent, +1. But I think it’s more related to this question than the other... :)

  • @Sergio thank you very much, it took work! hahaha. I did not mark as duplicate because the answer could better clarify the concept but really, does not answer the question. : D

  • I just left it as "extra stuff"

  • fernandosavio... so, basically, bubbling is the same as spreading, right? As for the preventDefault, was already very clear, as was the stopPropagation.

1 answer

2


The .preventDefault() and bubbling are different things. The .preventDefault() causes an expected/natural action of the browser to fail and the stopPropagation() stops the bubbling.

.preventDefault()

If you click an anchor like <a href="http://google.com"> the expected/natural is to be redirected to the Google site. Using the .preventDefault() you can prevent that. For example, notice how you can distinguish which anchors should have the natural behavior:

const ancoras = document.querySelectorAll('a');
ancoras.forEach(a => a.addEventListener('click', e => {
  if (a.href.includes('stack')) {
    // aqui vamos parar todos os cliques para sites com "stack" no nome
    e.preventDefault();
  }
}));
<a href="http://google.com">Google</a>
<a href="http://stackoverflow.com">Stackoverflow</a>

.stopPropagation()

When you click on an element the event comes from the window/Document, descends to the element and then goes back up in the DOM. In this "bubbling" you can stop the event from climbing the DOM with the .stopPropagation(). Take a look at the example below:

const divs = document.querySelectorAll('div');
divs.forEach(a => a.addEventListener('click', (e) => {
  console.log(`A borbulhar de ${e.target.id} para ${a.id}`);
  if (a.id === 'B') {
    // aqui vamos parar o borbulhamento para nunca chegar a <div id="A">
    e.stopPropagation();
  }

}));
div {
  padding: 30px;
  border: 2px solid black;
  background: transparent;
  transition: background .3s;
}

div:hover {
  background: rgba(50, 50, 50, .3);
}
<div id="A">
  <div id="B">
    <div id="C">
      <div id="D">Clica numa das divs...</div>
    </div>
  </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.