+ 3

How to make a jquery button that on clicking plays audio

I want some help making a web game but I am unable to use audio in it

7th May 2017, 8:21 AM
Palash Chatterjee
Palash Chatterjee - avatar
2 ответов
+ 8
You have to know that on mobile device, playing is allowed dynamically ( with JS ) only after the user play it manually ^^ Some workarounds exists, but it's not recommended, as the behaviour of this limit, is to prevent user spending mobile data without their agreement ;) Anyway, to do it, you need to select the audio element ( or create an audio instance with JS ), and simply use its play() method :P I'm not sure of valid JQuery syntax to do it, but I can do it without it...
7th May 2017, 9:01 AM
visph
visph - avatar
0
<body> <button id="btn" type="button">Click here for sound</button> <audio id="audio" src="example.mp3"></audio> <script> //option 1 $("#btn").on("click", function() { var audio = $("#audio")[0]; audio.play(); }); // option 2 $("#btn").on("click", function() { var audio = document.getElementById("audio"); audio.play(); }); </script> </body> The option 1 uses play() method which is not part of jQuery. To access the selector using jQuery and use the play() method, it needs to be accessed as jQuery array-like object. It is the first item in the array-like object so it starts at zero, like this: $selector[0] The option 2 also uses jQuery method on() to respond to the "click" event. But then, it uses plain javascript to select the element that has id of "audio" and apply the play() method
8th May 2017, 4:30 AM
Ari
Ari - avatar