I am building a Flask app that also uses JS and I encountered an error. I am building a timer which will play and pause as the user clicks on each respective button. I built it a few months ago and it was working, but I didn’t finish it. Now, I want to finish it but the error occurs. The error is,
play.addEventListener is not a function
at timer (index.js:26)
at index.js:84
Here is my code:
const timer = () => {
const song = document.querySelectorAll(".song");
const play = document.querySelectorAll(".play");
const reset = document.querySelectorAll(".reset");
// Time display
const minuteDisplay = document.querySelectorAll(".minute");
const secondDisplay = document.querySelectorAll(".second");
//Duration
// const formDuration = document.getElementById("duration").value;
const formDuration = 20;
let duration = formDuration * 60;
let displayMinutes = ("0" + Math.floor(duration / 60)).slice(-2);
let displaySeconds = ("0" + Math.floor(duration % 60)).slice(-2);
for (const mdisplay in minuteDisplay) {
mdisplay.textContent = `${displayMinutes}`;
}
for (const sdisplay in secondDisplay) {
sdisplay.textContent = `${displaySeconds}`;
}
play.addEventListener("click", () => { //This is the error
checkPlaying(song);
});
const checkPlaying = (song) => {
if (song.paused) {
song.play();
play.textContent = `Pause`;
play.classList.toggle("btn-active");
} else {
song.pause();
play.innerHTML = `Play`;
play.classList.remove("btn-active");
}
};
song.ontimeupdate = () => {
let currentTime = song.currentTime;
let elapsed = duration - currentTime;
let seconds = Math.floor(elapsed % 60);
let minutes = Math.floor(elapsed / 60);
// Edit time display
formatMinutes = ("0" + minutes).slice(-2);
formatSeconds = ("0" + seconds).slice(-2);
minuteDisplay.textContent = `${formatMinutes}`;
secondDisplay.textContent = `${formatSeconds}`;
reset.addEventListener("click", () => {
song.pause();
song.currentTime = 0;
play.innerHTML = `Play`;
play.classList.remove("btn-active");
if (reset.classList.contains("btn-active")) return;
reset.classList.add("btn-active");
// remove class after 2 seconds
setTimeout(() => {
reset.classList.remove("btn-active");
}, 150);
});
if (currentTime >= duration) {
song.pause();
song.currentTime = 0;
play.innerHTML = "Play";
play.classList.remove("btn-active");
}
};
};
timer();
My timer is based on a song, and when the song pauses, the timer should too. The same should happen when the song is reset or played. Any feedback will be greatly appreciated. Thankyou!