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

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

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 Report

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