perkes456 perkes456 - 1 year ago 83
jQuery Question

Playing sound after jquery onclick

I have a following HTML in my web forms like following:

<asp:GridView ID="gridLanguages" AutoGenerateColumns="false" runat="server">
<a class="audio">
<%# Eval("Name") %>
<audio >
<source src="<%# "/languages/" + Eval("Path") %>" type="audio/mpeg">

And here is the function that I'm using to trigger the event:


$('document').ready(function () {
$(".audio").click(function (event) {
console.log("Event triggered"); // this line is shown in console so this part is ok
var audio = $(this)[0];


As you can see gridview data source can contain multiple paths to mp3 files that I've loaded successfully. Now what I'm trying to achieve is to when the event is triggered on a element, I'd like to play the corresponding audio file for that which was clicked.
I'm also trying to figure out how to, if the user clicks on another mp3 link, all previous audio files would be stopped and the current one would play... How can I achieve that ?

Can someone help me out ??


You can use .each() to iterate all .audio element, set currentTime to 0, call .pause(); then call .load(), .play() on audio = $(this)[0];. Note, document is an object, not a string

    $(document).ready(function () {
        var elems = $(".audio"); (event) {
            elems.find("audio").each(function() {                 
              this.currentTime = 0;
            console.log("Event triggered");
            var audio = $(this).find("audio")[0];