I am creating a music player, I can play the audio when an album is clicked but when another album is clicked both songs play simultaneously, I need to pause the previous song and play the new song. I have written the code in such a way that I need to get the inner text of the clicked album and then play the song.
I have 27 album div tags, If we click on one album div this code will take the inner HTML and play the song of that name, if we click another album div, it will take the inner HTML and play the song along with the already playing song, I just need to pause the old song and play the new song
Here is the JavaScript code:
// PLAY MUSIC OF CLICKED ALBUM
for (var i = 0; i < 27; i++) {
document.querySelectorAll(".album")[i].addEventListener("click", function () {
//getting inner text of clicked album
let songName = this.querySelector("div.album > h4").innerText;
//playing song of the album clicked
let playThisSong = "assets/songs/" + songName + ".mp3";
let playSong = new Audio(playThisSong);
playSong.play();
//need code to pause previous audio and play the clicked album audio
});
}
Here is the required HTML code:
<div class="albums-container">
<div class="album">
<img src="./assets/images/Dooriyan.jpg" alt="dooriyan-logo">
<h4>Dooriyan</h4>
<img class="play-btn" src="./assets/images/play-btn.png" alt="playBtn">
</div>
<div class="album">
<img src="./assets/images/Zara Zara.jpg" alt="dooriyan-logo">
<h4>Zara Zara</h4>
<img class="play-btn" src="./assets/images/play-btn.png" alt="playBtn">
</div>
<div class="album">
<img src="./assets/images/Tu Aake Dekhle.jpg" alt="dooriyan-logo">
<h4>Tu Aake Dekhle</h4>
<img class="play-btn" src="./assets/images/play-btn.png" alt="playBtn">
</div>
</div>
The solution can be: Remove query selector all or for loop and use another method, or use if-else to play and pause. Or something else.
Going to create a new answer since you updated your code.
Store a variable OUTISDE of your query selector function for the last song that has been played. Then, every time you start playing a new song, first pause the old song.
let lastPlayedSong = null;
// PLAY MUSIC OF CLICKED ALBUM
for (var i = 0; i < 27; i++) {
document.querySelectorAll(".album")[i].addEventListener("click", function () {
//getting inner text of clicked album
let songName = this.querySelector("div.album > h4").innerText;
//playing song of the album clicked
let playThisSong = "assets/songs/" + songName + ".mp3";
let playSong = new Audio(playThisSong);
playSong.play();
//need code to pause previous audio and play the clicked album audio
if (lastPlayedSong) lastPlayedSong.pause();
lastPlayedSong = playSong;
});
}