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

216
Vistas
Javascript button sound effect

I ran into a problem in a project I had done. I used the function I threw below to have a sound effect when we press the button. It works fine, but when I give direction to the button, there is no sound. Where could I be doing the mistake? Thank you.

function playMyAudio() {
  document.getElementById("myAudio").play();
}
<audio src="https://css-tricks.com/examples/SoundOnHover/audio/beep.mp3" preload="auto" id="myAudio"></audio>

<a href="index.html">

  <button onClick="playMyAudio()">Play Audio</button>
</a>

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Actually what's happening is when the when you click on the button wrapped in a tag the link is making the browser load the link instead of calling the function ! ... Check this code snippet it will help you make link in a better way

Solution =>

<audio src="https://css-tricks.com/examples/SoundOnHover/audio/beep.mp3" preload="auto" id="myAudio"></audio>


<button href="index.html" onClick="playMyAudio()">Play Audio</button>

<script>

  const audioEl = document.getElementById("myAudio");
  function playMyAudio() {
    audioEl.play();
  }

  const buttonLinks = document.querySelectorAll("button[href]");
  const delay = 100;//milliseconds

  audioEl.addEventListener("canplaythrough", ()=> {
    buttonLinks.forEach(btn => {
      btn.addEventListener("click", (e)=> {
        setTimeout(()=> {
          window.location = btn.getAttribute("href")
        }, audioEl.duration + delay);
      })
    });
  });
</script>

about 4 years ago · Santiago Trujillo Denunciar

0

You could remove the a tag and redirect to index.html after a short delay using JS :

function playMyAudio(){
   document.getElementById("myAudio").play();
   setTimeout(() => window.location.href = "index.html", 200);
}
about 4 years ago · Santiago Trujillo 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