I am a graphic designer building website in Cargo Collective. I want to make sound play when user clicks the mouse or tap the screen. I use this code:
<script>
function MouseSound() {
var fileUrl = "https://files.cargocollective.com/c1242413/sound-1.mp3";
var audio = new Audio(fileUrl);
audio.play();
}
window.addEventListener('click', MouseSound , false);
</script>
I use function MouseSound() to do it. But I have a problem — the sound keeps playing on the next website page on click, even if there's no script in it. I want to play sound only on pages with the script.
I guess it's because window thing? Or it's script just stays in cache? How it's possible to play different sounds on different pages OR just play them only on pages, that have the script? Thank you.
Yes. You are right. The problem is occurring because of the window thing. So, in the other webpage, you can add this script:
<script>
function EmptyMethod() {}
window.addEventListener('click', EmptyMethod , false);
</script>
Just use document instead of window. document refers to this webpage or DOM. You could do:
document.addEventListener("mouseleave", stopSound);
This will fire whenever you leave the page, go to a new tab, leave the browser window, close the browser window. You can make a stopSound() function that pauses the sound like so:
function stopSound() {
audio.pause();
}
You can also mute the sound with audio.muted = true, but this will not pause the sound and sound will play in the background but we cannot hear it.
Now resume the sound with audio.play(). you can do:
document.addEventListener("mouseenter", playSound);
function playSound() {
audio.play();
}
Just play with the code and see what suites your need.