Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
How to make sound play only on current page? Java Script

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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>
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda