I have something I am working on in HTML5 and javascript that is a clicker type game. It is very bland as of now, but I plan to add to it. I have a button and a counter, when you click the button the amount of "points" increases, and audio (should) play. It plays, but if you click again before the audio has ended, the audio won't play. I want the audio to play on each click. Thanks. Code:
const audio = new Audio ('btnClick.mp3')
let counterDisplayElem = document.querySelector('.points');
let counterPlusElem = document.querySelector('.bigButton');
let count = 0;
updateDisplay();
counterPlusElem.addEventListener("click", () => {
count = count + 1;
updateDisplay();
play()
});
function updateDisplay() {
counterDisplayElem.innerHTML = "points : " + count;
};
// :family: :blue_car: :boom: ;)
function play() {
audio.play();
}
I tried adding an audio playing function, and that to play when you clicked the button each time through an event listener. What happened was that the audio would play on click, but only once it had ended.
I don't quite understand your question, but if you wanted to replay the audio from beginning on re-clicking, try the following.
const audio = new Audio("https://file-examples.com/storage/fe0eca90ba64a099e9d0525/2017/11/file_example_MP3_700KB.mp3");
let counterDisplayElem = document.querySelector(".points");
let counterPlusElem = document.querySelector(".bigButton");
let count = 0;
function updateDisplay() {
counterDisplayElem.innerHTML = "points : " + count;
}
updateDisplay();
function play() {
audio.play();
}
counterPlusElem.addEventListener("click", () => {
count = count + 1;
updateDisplay();
if (audio.paused === true) {
play();
} else {
audio.pause();
audio.currentTime = 0;
play();
}
});
<div class="points"></div>
<button class="bigButton">Click</button>
Basically, what I'm doing here is to check whether the audio is paused or not. If paused, this means that the user has opened the page for the first time, so play()
function would run otherwise which means that the audio is already playing, I'd pause the audio using pause()
and then set currentTime
to 0
then run play()
function.