Skip to content

JavaScript equivalent of :active in CSS

I have the script that plays audio, the problem with the below script is that it plays when mouse click is released.

<!doctype html>
<html>

<head>
  <title>Audio</title>
</head>

<body>

  <script>
    function play() {
      var audio = document.getElementById("audio");
      audio.play();
    }
  </script>

  <input type="button" value="PLAY" onclick="play()">
  <audio id="audio" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>

</body>

</html>

I want the above script to play on mouse click (similar to active on CSS)

Any help would be appreciated. Thanks.

Answer

Listen for the mousedown event instead:

<!doctype html>
<html>
  <head>
    <title>Audio</title>
  </head>
  <body>

    <script>
      function play() {
        var audio = document.getElementById("audio");
        audio.play();
      }
    </script>

    <input type="button" value="PLAY" onmousedown="play()">
    <audio id="audio" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>

  </body>
</html>