0

I have 4 buttons that each play their own music when pressed. I needed something that pauses one music when another button is clicked so that I dont have all 4 music playing on top of each other. I found this code to solve it:

document.addEventListener('play', function(event){
var allAudios = document.getElementsByTagName('audio');
debugger;
for(var i = 0; i<allAudios.length; i++){
    if(allAudios[i] != event.target){
        allAudios[i].pause();
    }
}
}, true);

However, I'm not understanding the exact purpose of the true at the end. I understand its telling the event listener to use capture event but when I set up an alert on the event target's parents, the order of events gets triggered up from the event target to its parents (bubbling) and parents to event target (capturing). Does anyone have an explanation to this phenomena and why useCapture is needed in this case to begin with?

I got the code from this website if anyone needs a reference.

https://teamtreehouse.com/community/auto-stop-when-playing-other-files

Thank you

BoopityBoppity
  • 929
  • 2
  • 9
  • 11

1 Answers1

1

tl;dr: because the play event doesn't bubble up and you want to listen (capture) all the play events happening in the document.

useCapture allows you to capture events that normally don't bubble up. In the context of the script you are referencing, you are listening for the play event. The play event doesn't bubble up like other events and you want to capture (listen to) all the play events happening in the document, so you enable useCapture to capture all the play events so you can know when to pause all other music playing.

How to know when you'll need to set useCapture to true:

  1. Visit the Event Reference page on MDN.
  2. Click on the event you want to use.
  3. Under "General info" at the top, look for whether "bubbles" is set to "yes" or "no".

If the event doesn’t bubble and you’ll be listening for events on an element other than the one that will trigger the event, set use capture to true.

Source: https://gomakethings.com/when-to-use-use-capture-in-your-event-listeners/

Edit More details in how useCapture works: Unable to understand useCapture parameter in addEventListener

delroh
  • 1,100
  • 12
  • 10