0

I am trying to play a sound when a font awesome icon is clicked.

I have a page where a list of posts are pulled from a database and I am using jinja to display them all. Each post will have an icon that can be clicked and the contents of that post will be read out.

This works if I just have an audio control but I would rather have a small icon instead of the entire audio control.

My issue is that when I add in the code to make it an icon, it only ever seems to run the 'src' of the first result in the for loop. I have inspected the page to check what each of the icons 'srcs' are and they are all different and correct but clicking the icon outputs the wrong audio.

I think it is something to do with the onclick event having an ID and the ID is always set to the first element in my forloop.

I tried this post - Play Sound when Font Awesome Icon is Clicked

HTML

{% extends "layout.html" %}
{% block content %}
    <!--Using Jinja2 to get run code in HTML-->
    <legend class="border-bottom mb-4">All Posts</legend>
    {% for post in posts %}
        <article class="media content-section">
            <div>
                <i class="fas fa-volume-up" onclick="playContent()" style="color: blue;"></i>
                <audio id="content">
                    <source src="link-to-blob-storage/{{ post.ttsFileName }}" type="audio/mp3">
                </audio>

                <script>
                    var audio = document.getElementById("content");

                    function playContent() {
                        audio.play();
                    }
                </script>               
            </div>
        </article>

    {% endfor %}

{% endblock content %}


Darren_D19
  • 121
  • 9

1 Answers1

1

Try something like this:

{% for post in posts %}

    <audio id="audio_{{post.ttsFileName}}">
        <source src="{{post.ttsFileName}}" type="audio/mp3">
    </audio>
    <i onclick="document.getElementById('audio_{{post.ttsFileName}}').play()"></i>
    
{% endfor %}
        
JP_
  • 1,636
  • 15
  • 26
  • Sorry. I changed the code and forgot to add back in the ID. I have edited the post. I have tried doing it with the ID and that is what I think is causing it to always take the first element from my for loop – Darren_D19 Nov 23 '21 at 02:21
  • Use a class instead. IDs can only be used once. I'll update my answer. – JP_ Nov 23 '21 at 02:22
  • Would you be able to provide a code example of using a class instead? – Darren_D19 Nov 23 '21 at 02:27
  • Try the example I provided instead. It sets the ID dynamically instead of using classes since you have multiple audio files. Didn't see that before. I have no idea if the syntax is correct. The logic should be fine though. – JP_ Nov 23 '21 at 02:36