Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda