I have the script that plays audio, the problem with the below script is that it plays when mouse click is released.
JavaScript
x
22
22
1
<!doctype html>
2
<html>
3
4
<head>
5
<title>Audio</title>
6
</head>
7
8
<body>
9
10
<script>
11
function play() {
12
var audio = document.getElementById("audio");
13
audio.play();
14
}
15
</script>
16
17
<input type="button" value="PLAY" onclick="play()">
18
<audio id="audio" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>
19
20
</body>
21
22
</html>
I want the above script to play on mouse click (similar to active
on CSS)
Any help would be appreciated. Thanks.
Advertisement
Answer
Listen for the mousedown
event instead:
JavaScript
1
19
19
1
<!doctype html>
2
<html>
3
<head>
4
<title>Audio</title>
5
</head>
6
<body>
7
8
<script>
9
function play() {
10
var audio = document.getElementById("audio");
11
audio.play();
12
}
13
</script>
14
15
<input type="button" value="PLAY" onmousedown="play()">
16
<audio id="audio" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>
17
18
</body>
19
</html>