I want to use 6 of these Before/After Audio Players on my website: https://github.com/mattbartley/AB-Audio-Player
However, the sources of the audio files are set in the JavaScript code. So when I implement multiple instances of this player in my HTML, they all play the same two audio files. I want to set data attributes in the HTML code in each player div for the src of the files and let the JavaScript use that instead. How do I go about it?
<div class="player__wrapper" data-audio-before="Song-1-before.mp3" data-audio-after="Song-1-after.mp3">
...
<div class="player__wrapper" data-audio-before="Song-2-before.mp3" data-audio-after="Song-2-after.mp3">
...
And so on. This would be the updated HTML code.
I think it's a pretty basic solution, I'm just not good in JavaScript.
Here is the current JavaScript code:
//Set up audio elements
var soundA = document.createElement("audio");
//Set audio A src here
soundA.src = "./assets/a.mp3";
soundA.preload = "auto";
soundA.setAttribute("hidden", "true");
soundA.setAttribute("onplaying", "stepA()");
document.body.append(soundA);
var soundB = document.createElement("audio");
//Set audio B src here
soundB.src = "./assets/b.mp3";
soundB.preload = "auto";
soundB.setAttribute("hidden", "true");
soundB.setAttribute("onplaying", "stepB()");
document.body.append(soundB);
I tried something like this: Hover over div, use its data-attribute to change the src of an img And other approaches as well. Couldn't get it to work.
ab-player.jswould be a better way to go. For example, you could wrap the entire source into a function, and the function would take an element as its argument. You would then set thesoundA.srcandsoundB.srcto whatever the value ofdata-audio-beforeanddata-audio-afterare. You'd also need to adapt thegetElementByIdparts to match the appropriate players (you could get them by class, or withquerySelector).function source() { const player = document.querySelectorAll('.player__wrapper') soundA.src = player.dataset.dataAudioBefore; soundB.src = player.dataset.dataAudioAfter; }; source();? And why would I need to change thegetElementByIdparts? They are just for the button elements and the progress bar. Maybe I misunderstood you.<div class="player__wrapper">as an argument, and work with it. You would also need to rearrange the HTML elements a bit, so that the controls are within that specific div, and you would collect them not withdocument.getElementById, but with<your_player_wrapper_used_as_function_argument>.querySelector(<class_of_specific_player_control). You would also need to reconfigure the wayplaySoundAandplaySoundBare working - they would need arguments as well. And so on.