Everything is working fine, only audioElement1
is not getting paused which is described in the else
statement, although the other feature of changing image written in the same else
statement is working fine…. so how is this happening…. I am confused.
My HTML
<div class="second-song-list">
<img class="second-img" src="images/covers/1.jpg" alt="" />
<div class="second-song-name">Warriyo - Mortals [NCS Release]</div>
<div>4:03
<img id="1"
class="second-icon"
src="images/circle-play-regular.png"
alt="play/pause"
srcset=""
/>
</div>
</div>
<div class="second-song-list">
<img class="second-img" src="images/covers/2.jpg" alt="" />
<div class="second-song-name">Cielo - Huma-Huma</div>
<div>4:43
<img id="2"
class="second-icon"
src="images/circle-play-regular.png"
alt="play/pause"
srcset=""
/>
</div>
</div>
My javascript
for (n = 0; n <= 9; n++) {
var icon = document.querySelectorAll(".second-icon");
icon[n].addEventListener("click", (e) => {
var x = e.target.getAttribute("id");
audioElement1 = new Audio("songs/" + x + ".mp3");
if (e.target.getAttribute("src") == "images/circle-play-regular.png") {
e.target.setAttribute("src", "images/circle-pause-regular.png");
audioElement1.play();
} else {
audioElement1.pause();
e.target.setAttribute("src", "images/circle-play-regular.png");
}
});
}
2
Answers
On each click you create a new
Audio
element:So the one that you "pause" doesn’t actually exist. You probably just need to define `audioElement1′ before the click handler and then wrap it in a closure or something to preserve the reference (since you are sharing the variable for each audioElement).
It’s easier just to have the
<audio>
tag in HTML and hide it by not addingcontrols
attribute to it. Having only one variableaudioElement1
to reference multiple Audio Objects is totally unnecessary (I thought impossible because it sounds ludicrous). Just to show other readers, in the example below the fourth<audio>
hascontrols
attribute. To prevent an exception, there’s a dummy<button>
that cannot be seen nor clicked. It’s there since the event handlers on the<audio>
expect a<button>
— normally you’d have it one way (all hidden) or the other (all visible).Details are commented in example