gonzalo2000 gonzalo2000 - 5 months ago 6
Javascript Question

audio_tag plays same file for different buttons

I'm new at using audio_tag; I'm trying to use a set of buttons to play short audio files. I'm going off this post to implement this feature. I currently have two audio tags with associated buttons, which should play different files. However, both buttons play the first audio file. I'm assigning different IDs to each button, but this is not helping. If I remove the first file, then the second button plays the expected file. (The mp3 files are located in /public/audios).

How can I go about associating the correct file to its button?

view:

<%= audio_tag "a.mp3", class: "audio-play" %>
<button type="button" class="btn btn-primary btn-lg", id="audioButtonA">A</button>

<br>

<%= audio_tag "e.mp3", class: "audio-play" %>
<button type="button" class="btn btn-primary btn-lg", id="audioButtonE">E</button>


application.js:

jQuery(document).ready(function() {
$("#audioButtonA").on("click", function() {
$(".audio-play")[0].currentTime = 0;
return $(".audio-play")[0].play();
});
});

jQuery(document).ready(function() {
$("#audioButtonE").on("click", function() {
$(".audio-play")[0].currentTime = 0;
return $(".audio-play")[0].play();
});
});

Answer

By using $(".audio-play")[0].play() you are always selecting the same element with the file (a.mp3), generally the first element with the class audio-play. To achieve your aim, on button click you have to select the previous element wich is an audio tag like so:

$("#audioButtonE").on("click", function() {
    var audio = $(this).prev()[0];
    audio.currentTime = 0;
    return audio.play();
});
Comments