user3774924 user3774924 - 28 days ago 5
Javascript Question

Play audio when checkbox is checked with javascript

I'm trying to make a short audio file play when a html checkbox is checked. I'm probably missing something elementary.
Here is my code:

<body>
<input type="checkbox" id="cena" onchange="myfunction()"></input><label for="cena"></label>
</label><script>
function myfunction(){
var audio = new audio('rusbtaudio.mp3');
audio.play();
}
</script>
</body>


rusbtaudio.mp3
is in same folder as html file.

Answer

<input> element is self-closing. Use .load(), canplay event. Substitute new Audio() for new audio()

<body>
    <input type="checkbox" id="cena" onchange="myfunction(this)" />
    <label for="cena"></label>
<script>
  var audio = new Audio('rusbtaudio.mp3');
  audio.oncanplay = function() {
    if (document.getElementById("cena").checked) this.play()
  }
  function myfunction(el) {    
    if (el.checked) {
      audio.load();
    }
  }
</script>
</body>
Comments