Get audio id played

Asked

Viewed 47 times

1

I need to get the audio ID that the play user, I figured something like this would work:

document.addEventListener('play', function(e){
   $(this).attr('id');
}, true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio controls id="musica1">
   <source src="https://65381g.ha.azioncdn.net/9/9/5/3/onlinepontocom-01-mais-uma-vez.mp3" type="audio/mpeg">
</audio>
<audio controls id="musica2">
   <source src="https://65381g.ha.azioncdn.net/9/9/5/3/onlinepontocom-01-mais-uma-vez.mp3" type="audio/mpeg">
</audio>

It even detects the click on play, but does not return the ID, there is some way?

2 answers

1


It’s just that you have to understand what’s the difference between this, Event.target and Event.currentTarget in the scope of an event?, if you give a console.log($(this)) you will see that it is not the return you were expecting. As you can see in the example below, if you use the parameter e plus the property target, you will be able to obtain the element that was clicked on screen, taking the value of your id:

document.addEventListener('play', function(e) {
  console.log(e.target.getAttribute('id'))
}, true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<audio controls id="musica1">
   <source src="https://65381g.ha.azioncdn.net/9/9/5/3/onlinepontocom-01-mais-uma-vez.mp3" type="audio/mpeg">
</audio>
<audio controls id="musica2">
   <source src="https://65381g.ha.azioncdn.net/9/9/5/3/onlinepontocom-01-mais-uma-vez.mp3" type="audio/mpeg">
</audio>

OBS: In the case using jQuery: $(e.target).prop('id');

0

Do it this way. So it checks play on any audio element and shows you the id assigned to the element.

    $('audio').on('play', function(){
        var id_aud = $(this).attr("id");
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<audio controls id="musica1">
   <source src="https://65381g.ha.azioncdn.net/9/9/5/3/onlinepontocom-01-mais-uma-vez.mp3" type="audio/mpeg">
</audio>
<audio controls id="musica2">
   <source src="https://65381g.ha.azioncdn.net/9/9/5/3/onlinepontocom-01-mais-uma-vez.mp3" type="audio/mpeg">
</audio>

Browser other questions tagged

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