Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!