How to use Event Listeners In HTML

In this approach, we are using JavaScript event listeners to handle the ‘play‘ event for the HTML5 audio element. The code makes sure that the audio plays only once by pausing the playback and displaying an alert if it has already been played, and resets the play status when the audio has ended.

Syntax:

element.addEventListener(event, listener, useCapture);

Example: The below example uses the JavaScript Event Listeners to create Sound, which only plays once in HTML5 Audio.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Example 1</title>
</head>

<body>
    <h1 style="color: green;">
        w3wiki
    </h1>
    <h3>Using JavaScript Event Listeners</h3>
    <audio id="audioPlayer" controls>
        <source
            src=
"https://media.w3wiki.org/wp-content/uploads/20240228225306/twirling-intime-lenovo-k8-note-alarm-tone-41440.mp3"
            type="audio/mp3">
        Your browser does not support the audio element.
    </audio>
    <script>
        const audioPlayer =
            document.getElementById('audioPlayer');
        let hasPlayed = false;
        audioPlayer.addEventListener('play', () => {
            if (hasPlayed) {
                audioPlayer.pause();
                alert('Audio can only be played once.');
            } else {
                hasPlayed = true;
            }
        });
        audioPlayer.addEventListener('ended', () => {
            hasPlayed = true;
        });
    </script>
</body>

</html>

Output:

How to make Sound only Play Once in HTML5 Audio ?

In HTML5, we can validate the audio playing by using the proper event handling and control manipulation. In this article, we will explore two different approaches to create sound that only plays once in HTML5 Audio.

Table of Content

  • Using JavaScript Event Listeners
  • Using onended Attribute

Similar Reads

Using JavaScript Event Listeners

In this approach, we are using JavaScript event listeners to handle the ‘play‘ event for the HTML5 audio element. The code makes sure that the audio plays only once by pausing the playback and displaying an alert if it has already been played, and resets the play status when the audio has ended....

Using onended Attribute

In this approach, we are using the onended attribute within the