First problem: you're using both the
onclick="..."
attribute and the
addEventListener
method. Your event handlers are being wired up twice to the same event. Get rid of the
onclick
attributes, and stick to the
addEventListener
approach.
Second problem: you're wiring up a handler to the
ended
event of the
clickSound
, but you never remove it. Each time you click, you add another handler to the same event. You need to specify the
once
option to prevent the handler from being fired more than once.
Third problem: you need to set the properties and add the event listener
before playing the sound.
EventTarget.addEventListener() - Web APIs | MDN[
^]
Try something like this:
<div class="container-fluid border">
<div class="cards-box row ">
<div class="cards border animate__animated animate__fadeIn" id="card1">Beer</div>
<div class="cards border " id="card2" style="display:none;">Bee</div>
<div class="cards border " id="card3" style="display:none;">Bird</div>
</div>
</div>
function createVoice(name, nextCard) {
const result = new Audio("./audio-files/" + name + ".mp3");
result.volume = 0.5;
if (nextCard) {
result.addEventListener("ended", function(){
document.getElementById(nextCard).style.display = "block";
});
}
return result;
}
const voiceOfSonia = [
createVoice("Beers", "card2"),
createVoice("bee", "card3"),
createVoid("bird")
];
const clickSound = new Audio("./audio-files/click.wav");
clickSound.volume = 0.3;
function playVoice(index){
clickSound.addEventListener("ended", function () { voiceOfSonia[index].play(); }, { once: true });
clickSound.play();
}
document.getElementById("card1").addEventListener("click", function(){ playVoice(0); });
document.getElementById("card2").addEventListener("click", function(){ playVoice(1); });
document.getElementById("card3").addEventListener("click", function(){ playVoice(2); });