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

189
Visualizações
audio.play() working within existing function but not as lone function

I am trying to make a sound play when a button is clicked. Here is the function that I am trying to use:

function sound(){

  var audio = new Audio("button.wav");
  audio.play();

}

and then I have this at the bottom of the file:

document.getElementById("convert").onclick = function() { sound(); };

I know that the code works because if I put the 2 lines of code inside the sound function inside of another function that performs a calculation on the button click, the sound plays. Why is the code only working when added to an existing function, but not as its own?

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

0

I'm assuming that by "its own" you are referring to this:

document.getElementById("convert").onclick = sound();

In this case, you are assigning the returned value of sound() to the onclick property of the element. If you want sound to be called when the button is clicked, remove the parenthesis:

document.getElementById("convert").onclick = sound;

Demo:

function sound(){
  var audio = new Audio("https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3");
  audio.play();
}
document.getElementById("convert").onclick = sound;
<button id="convert">Play</button>

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