Home > Mobile >  How to give a unique id to multiple audio elements in order to play them with Jquery
How to give a unique id to multiple audio elements in order to play them with Jquery

Time:10-07

I'm working on a audio player in coldfusion jQuery, I achieved to set a SRC for each and it's corresponding.

My problem now is i can't play the audio src cause when i .play() with jQuery it "tries" i guess to play everything with the same id.

I need to set a new unique id but i don't understand how to do it, i tried with jQuery but with no success.

Here an exemple :

$('.btn_player').click(function(event) {
event.preventDefault();
console.log('button audio player clicked');
var idtemp = $(this).attr("id");
        var idtemp = idtemp.split("_");
        var idtemp = idtemp[1];
        console.log(idtemp);
document.getElementsByClassName("audio")[0].play();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<td><a  id="player">foo
                <audio id="audio"><src="./assets/vocab/#formation_id#/5/#voc_cat_id#/word_#voc_id#_#formation_id#_5.mp3" type="audio/mp3"></audio>
                <i ></i></a></td>
            
            <td><a  id="player">foo2
                <audio id="audio"><src="./assets/vocab/#formation_id#/8/#voc_cat_id#/word_#voc_id#_#formation_id#_8.mp3" type="audio/mp3"></audio>
                <i ></i></a></td>
            
            <td><a  id="player">foo3
                <audio id="audio"><src="./assets/vocab/#formation_id#/10/#voc_cat_id#/word_#voc_id#_#formation_id#_10.mp3" type="audio/mp3"></audio>
                <i ></i></a></td>
            
            <td><a  id="player">foo4
                <audio id="audio"><src="./assets/vocab/#formation_id#/15/#voc_cat_id#/word_#voc_id#_#formation_id#_15.mp3" type="audio/mp3"></audio>
                <i ></i></a></td>

i'm looking for a solution with jQuery or Coldfusion.

CodePudding user response:

Depending on how your logic works around the number after vocab/#formation_id#/ (#formation_id#/5/, #formation_id#/8/, etc.), you can

  1. put them in an array
  2. loop the array and use the index and the numbers in your element IDs.

This way, you will have unique IDs for all your anchor and audio elements

<cfset nums = [ 5, 8, 10, 15 ] />

<cfloop array="#nums#" item="item" index="index">
    <cfset idPrefix = "-#item#-#index#" />

    <td>
        <a  id="player-#idPrefix#">
            foo#index#
            <audio id="audio-#idPrefix#"><src="./assets/vocab/#formation_id#/#item#/#voc_cat_id#/word_#voc_id#_#formation_id#_#item#.mp3" type="audio/mp3"></audio>
            <i ></i>
        </a>
    </td>
</cfloop>
  • Related