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

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

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