John Davidson

javascript - Get the value of a variable made in a loop

0 comments
Message:


I have a loop that makes a table, and each of the rows have an audio file, the audio playing has an ID of "audio"+i to give unique ids to the different audios.


I'm making a progress bar but I need the "i" variable to determine which of the audios the progress bar should act on, if I replace "i" with a number, then it works. I just haven't found a way to get the "i" variable.


HTML/PHP where the loop and audio are:


for($i=0; $i<$count; $i++){
$res = mysqli_fetch_array($result);
echo('<tbody id="tbody">
<tr>
<audio id="audio'.$i.'" src="mp3/'.$res["song_artist"].'-'.$res["song_title"].'.mp3">
<td><button class="playbutton" id="playbtn'.$i.'" onclick="playStop('.$i.')">▷</button></td>
<td><img class="songimg" src="getimage.php?id='.$res["song_id"].'"/> </td>
<td>'.$res["song_title"].'</td>
<td>'.$res["song_artist"].'</td>
<td>'.$res["song_genre"].'</td>
<td>'.$res["song_album_name"].'</td>
</tr>
</tbody>');
}
}

Progress bar code where I need the "i" variable:


 var progressbar = document.getElementById("progress-bar");
progressbar.onclick = function(e) {
var audio = document.getElementById("audio"+i);
audio.currentTime = ((e.offsetX/progressbar.offsetWidth) * audio.duration);
}
}

Thank you in advance.



My Answer:
"audio" + i, where i is the index of the loop. I want to be able to get the value of the variable i when the audio is clicked. How can I achieve this in JavaScript?

You can achieve this by using a closure to capture the value of i in a separate function. Here's an example code snippet:

javascript
for (let i = 0; i < 5; i++) {
let audio = document.createElement('audio');
audio.id = 'audio' + i;
audio.src = 'audio' + i + '.mp3';

audio.addEventListener('click', (function(index) {
return function() {
console.log('Clicked on audio with index: ' + index);
};
})(i));

document.body.appendChild(audio);
}


In this code snippet, we create a closure by wrapping the event listener function in an immediately invoked function expression (IIFE) that captures the value of i at each iteration of the loop. When the audio element is clicked, the event listener function will log the value of i corresponding to that audio element.

Rate this post

4 of 5 based on 6500 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us