Your implementation is done pooly, because you're creating a new Audio()
on a changeBackground
method. So this will create a new audio
every time the click
event is fired.
But to answer your question, To stop an audio
you must use pause()
method which is defined in the Audio API.
Here's an example:
// First create the audios
var audioElements = document.querySelectorAll(".audio");
var audioObj = {};
// Create audios for each element
audioElements.forEach((el, i)=>
{
audioObj[el.getAttribute("data-name")] = new Audio((el.getAttribute("data-name") + ".mp3"));
});
// Methods to operate those audios
function playAudio(el)
{
var audioName = el.getAttribute("data-name");
// Create audios for each element
Object.keys(audioObj).forEach((keyName, i)=>
{
if(audioName != keyName)
{
audioObj[keyName].pause();
return;
}
audioObj[audioName].play();
console.log(audioName);
document.body.style.backgroundColor = audioName.concat(".png");
});
}
function changeBackground(imageSource)
{
document.body.style.backgroundImage = `url(${imageSource})`;
}
<button data-name="winter" class="audio winter" onclick="return playAudio(this)">Play Winter</button>
<button data-name="summer" class="audio summer" onclick="return playAudio(this)">Play Summer</button>
<button data-name="spring" class="audio spring" onclick="return playAudio(this)">Play Spring</button>
So in your case, you could pause()
all other videos when another is clicked. I have done this only to control two audios.