gonzalo2000 gonzalo2000 - 4 months ago 14
Javascript Question

Only top audio_tag button plays

I'm stating out with audio on my site; I've previously implemented an audio_tag with a glyph button in one of my views. In a different view, I'm trying to list all of my word objects, and I would like to have a button to play each of their associated audio. As of now, this functionality only works for the very first word object listed in this view. How can I make the buttons play the sound upon click for all of the objects in the view?

Lesson show view:

<div class ="col-xs-10 col-xs-offset-1">
<% @lesson.words.each do |word| %>
<%= image_tag word.image_url(:thumb) if word.image? %>

<b><%= word.term %></b>

<%= audio_tag word.sound, class: "audio-play" %>
<button type="button" class="btn btn-default", id="audioButton">
<span class="glyphicon glyphicon-play" aria-hidden="true"></span>

<i>(<%= word.reference %>)</i>

<% end %>


// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require_tree .

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


Give each one it's own unique id.

In html ids must be unique. eg "#audioButton1" "#audioButton2" etc... alternatively, don't use ids, use class names eg class="btn btn-default audio-button" then $(".audio-button").on("click", function()