SantinoDu
SantinoDu

Reputation: 43

Why isn't my event bubbling

Here's some demo code:

<div id="test">
    <div class="child">
        click
    </div>
</div>
<script>
   document.addEventListener('click', function (e) {
       if(e.target.classList.contains('child')){
           console.log('child')
       }
       if(e.target.id==='test'){
           console.log('test')
       }
       if(e.target.tagName === 'HTML'){
           console.log('html')
       }
   }, false)
</script>

When I click text, the console only logs 'child'. Why doesn't the click event bubble up to the parentNode #test? Even the html element can't get the click event.

Can anyone explain what the problem is?

Upvotes: 3

Views: 496

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

The event is bubbling that is why the handle registered to the document object is getting fired. The document object is the top most object in the dom, ie it is the parent of the html element. If the bubbling was not happening then the handler would not have got called.

But in all the handlers Event.target will refer to the original element from where the event started that is why it is always referring to the child element

A reference to the object that dispatched the event. It is different than event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.

If you want to test the ancestor element, then you need to traverse up from the event target and see whether any of those satisfies the condition

document.addEventListener('click', function(e) {
  var target = e.target;
  while (target) {
    if (target.classList.contains('child')) {
      snippet.log('child')
    }
    if (target.id === 'test') {
      snippet.log('test')
    }
    if (target.tagName === 'HTML') {
      snippet.log('html')
    }
    target = target.parentNode;
  }
}, false)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<div id="test">
  <div class="child">
    click
  </div>
</div>

Upvotes: 6

Related Questions