JavaScript onended
Event: Detecting Media Playback Completion
The JavaScript onended
event is a crucial tool for web developers when working with HTML5 media elements, such as <audio>
and <video>
. This event is triggered when the playback of a media file has finished, providing a way to execute specific actions or functions upon completion. This guide will provide a comprehensive understanding of how to use the onended
event, with practical examples for both audio and video.
What is the onended
Event?
The onended
event is fired by HTML5 media elements (<audio>
and <video>
) when the media reaches the end of its duration and stops playing. This event is essential for creating interactive media experiences, allowing you to perform actions such as:
- Displaying a replay button
- Loading the next media item in a playlist
- Showing a post-playback message or animation
- Resetting the media player for another playback
Syntax of the onended
Event
The onended
event can be added to an HTML media element in two primary ways:
-
HTML Attribute: You can directly add the
onended
attribute to the HTML element.<audio onended="myFunction()"></audio>
-
JavaScript Event Listener: You can attach an event listener to the media element using JavaScript.
const mediaElement = document.getElementById("myAudio"); mediaElement.onended = myFunction; // or mediaElement.addEventListener("ended", myFunction);
onended
Event Attributes
The onended
event, when triggered, doesn’t provide specific additional attributes but rather the standard Event
interface properties. Here’s a table summarizing those most commonly used in the context of media playback:
Attribute | Type | Description |
---|---|---|
`target` | Element | The element that triggered the event (i.e., the audio or video element). |
`type` | String | The type of event, which is `”ended”` in this case. |
`timeStamp` | Number | The time (in milliseconds) when the event occurred. |
Note: The target
property is particularly useful when dealing with multiple media elements, allowing you to identify which one triggered the event. π‘
Practical Examples
Let’s explore how to use the onended
event with both audio and video elements, starting with simple demonstrations and progressing to more complex use cases.
Basic Audio onended
Example
Here’s a simple example demonstrating how to use the onended
event with an audio element to display an alert when the audio finishes playing:
<audio
id="audioPlayer1"
controls
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
></audio>
<script>
const audioElement1 = document.getElementById("audioPlayer1");
audioElement1.onended = function () {
alert("Audio playback ended!");
};
</script>
In this example, when the audio finishes playing, an alert box pops up, displaying “Audio playback ended!”. This demonstrates the basic usage of the onended
event.
Basic Video onended
Example
Hereβs an example of using the onended
event with a video element to display a message below the video when it finishes playing:
<video
id="videoPlayer1"
width="320"
height="240"
controls
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
></video>
<p id="videoMessage1" style="display:none">Video playback ended!</p>
<script>
const videoElement1 = document.getElementById("videoPlayer1");
const messageElement1 = document.getElementById("videoMessage1");
videoElement1.onended = function () {
messageElement1.style.display = "block";
};
</script>
In this case, when the video finishes, the message “Video playback ended!” will appear under the video, showing how the onended
event can be used to alter the page content.
Using Event Listeners with Audio
Using addEventListener
is a recommended approach for handling events in JavaScript. Hereβs how you can do it with an audio element:
<audio
id="audioPlayer2"
controls
src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
></audio>
<p id="audioMessage2" style="display:none">Audio playback ended!</p>
<script>
const audioElement2 = document.getElementById("audioPlayer2");
const messageElement2 = document.getElementById("audioMessage2");
audioElement2.addEventListener("ended", function () {
messageElement2.style.display = "block";
});
</script>
This example sets up an event listener for the ‘ended’ event, and when the audio finishes, it shows a message similar to the previous video example.
Using Event Listeners with Video
This example demonstrates the use of event listeners for the onended
event with a video element. After the video completes, it displays a message and also resets the video to its beginning.
<video
id="videoPlayer2"
width="320"
height="240"
controls
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
></video>
<p id="videoMessage2" style="display:none">Video playback ended!</p>
<script>
const videoElement2 = document.getElementById("videoPlayer2");
const messageElement2 = document.getElementById("videoMessage2");
videoElement2.addEventListener("ended", function () {
messageElement2.style.display = "block";
videoElement2.currentTime = 0; // Reset video to start
});
</script>
Here, in addition to displaying a message, the video is reset to its starting point when finished playing.
Advanced Example: Playlist with onended
Let’s create a more complex example using onended
with a playlist, where the next song is automatically played when the current song finishes.
<audio id="audioPlayer3" controls></audio>
<ul id="playlist">
<li data-src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3">
Song 1
</li>
<li data-src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3">
Song 2
</li>
<li data-src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3">
Song 3
</li>
</ul>
<script>
const audioElement3 = document.getElementById("audioPlayer3");
const playlistItems3 = document.querySelectorAll("#playlist li");
let currentSongIndex3 = 0;
function playSong(index) {
const songItem = playlistItems3[index];
const songSrc = songItem.getAttribute("data-src");
audioElement3.src = songSrc;
audioElement3.play();
}
audioElement3.addEventListener("ended", function () {
currentSongIndex3++;
if (currentSongIndex3 < playlistItems3.length) {
playSong(currentSongIndex3);
} else {
currentSongIndex3 = 0; // Loop back to the first song
playSong(currentSongIndex3);
}
});
//Initial Song Play
playSong(currentSongIndex3);
</script>
In this example, when a song ends, the next one in the playlist starts automatically. If all songs have been played it will loop back to the first one. This shows how onended
can be used to manage more dynamic media interactions.
Real-World Applications of the onended
Event
The onended
event is widely used in various media-related web applications, such as:
- Streaming Platforms: Automating playback of the next episode or song.
- Online Courses: Navigating between lecture videos or audio segments.
- Interactive Presentations: Triggering next slide or animation after media ends.
- E-learning Modules: Displaying quizzes or assessments after a video.
Browser Support
The onended
event is widely supported across all modern web browsers, making it a reliable event for media handling.
Note: Always test your code across different browsers to ensure it performs consistently. β
Conclusion
The onended
event is a fundamental tool for managing media playback in web applications, providing a way to execute custom actions after a media file has completed its playback. By understanding its usage, you can create more engaging, interactive, and seamless media experiences for users. This guide should give you all the necessary knowledge to use onended
effectively. Happy coding! π