[JavaScript] Play Sound on Click Event of DOM Element


In this post, we will show how to use audio element provided in HTML5 standard to play sound when a HTML element is clicked. Before diving into this new feature, please take a look at browser compatibility of HTML5 audio tag.

Demo

Source Code for Demo:

play.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Play Sound on Click Event of DOM Element</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<button id="bt" type="button"
  onclick="javascript:PlaySound('Wat_Metta_Buddha_Qualities.mp3');">
  Click Me to Play Sound
</button>

<script type="text/javascript">

function PlaySound(path) {
  var audioElement = document.createElement('audio');
  audioElement.setAttribute('src', path);
  audioElement.play();
}

</script>

</body>
</html>

The PlaySound function plays audio file of given path or URL if the button is clicked.


References:

[1]Introduction to the HTML5 audio tag javascript manipulation
[2]<audio> - HTML (HyperText Markup Language) | MDN
[3][JavaScript] Toggle (Play/Pause) Sound on Click Event of DOM Element
[4][Golang] GopherJS DOM Example - Play Sound on Click Event
[5][Golang] GopherJS DOM Example - Toggle (Play/Pause) Sound on Click Event