2

I am working on a project where I bind one eventListener to an <audio> element for play event and another eventListener to its parent element for the same event. I noticed that the child's callback is always called, but the parent's callback is never called.

If I use capture mode of addEventListener(), then both callbacks are called normally - first parent, then child.

To further investigate, I wrote a piece of code and found that play event doesn't bubble back to the parent.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div><audio src="song.mp3" controls="true"></audio></div>
</body>
<script type="text/javascript">
    parent = document.querySelector('div');
    child = document.querySelector('div audio');

    parent.addEventListener('click', function() {console.log('parent-click-capture');}, true);
    parent.addEventListener('click', function() {console.log('parent-click-bubble');}, false);
    parent.addEventListener('play', function() {console.log('parent-play-capture');}, true);
    parent.addEventListener('play', function() {console.log('parent-play-bubble');}, false);

    child.addEventListener('click', function() {console.log('child-click-capture');}, true);
    child.addEventListener('click', function() {console.log('child-click-bubble');}, false);
    child.addEventListener('play', function() {console.log('child-play-capture');}, true);
    child.addEventListener('play', function() {console.log('child-play-bubble');}, false);
</script>
</html>

And this was the output:

parent-click-capture
child-click-capture
child-click-bubble
parent-click-bubble
parent-play-capture
child-play-capture
child-play-bubble


Does anyone know if this behaviour is particular only of play event or are there other events that don't enter bubble phase (or capture phase)?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
zhirzh
  • 3,273
  • 3
  • 25
  • 30

1 Answers1

2

All JS events enter the capture phase.

Whether or not an event enters the bubble phase can be checked by reading the event's bubbles property.

element.addEventListener('ACTION', (e) => console.log(e.bubbles))
zhirzh
  • 3,273
  • 3
  • 25
  • 30