Reputation: 23
I'm relatively new to Javascript and Jquery. What I'm trying to do is to create a basic webpage with 2 buttons that will make sound whenever you click on them.
The function above is meant to select the audio file named "green.mp3" and play it when you click on the green button.
function sound(color){
var audio = new Audio("sounds/" + color + ".mp3");
audio.play();
}
$(".green").click(sound("green"))
The problem is, when I run this, it says "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.". I don't plan on autoplaying the audio when opening the webpage, it is meant to start audio after interaction, so I clearly made a very stupid mistake here. Can someone help me here considering I am the dumbest of beginners? :D
Upvotes: 2
Views: 1658
Reputation: 97707
Your sound function runs immediately when you try to attach the event handler, you have to wrap it in a function and pass that to the click handler
$(".green").click(event => sound("green"));
Upvotes: 2