GOKTU
GOKTU

Reputation: 45

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>

Upvotes: 1

Views: 387

Answers (2)

Sanmeet
Sanmeet

Reputation: 1410

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>

Upvotes: 1

Tom
Tom

Reputation: 5677

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);
}

Upvotes: 1

Related Questions