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

215
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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