JavaScript Document ended Event: The Complete Guide

JavaScript offers a wide range of events that help us create interactive and dynamic web pages. One such useful event is the ended event. This guide will explain everything you need to know about the ended event. We’ll cover what it is, why it’s useful, where to use it, how to implement it, and when it comes into play. Letโ€™s dive in!

What is the ended Event?

The ended event in JavaScript is fired when the playback of a media element (like a video or audio) has ended. This event is particularly useful for triggering actions that should occur once media playback is complete, such as displaying a message, playing another media file, or resetting the media element.

Why Use the ended Event?

Using the ended event is beneficial because it allows you to execute code right after a media file has finished playing. This can be useful for creating playlists, showing a message to users, or performing any cleanup actions. It enhances the user experience by making interactions more dynamic and responsive.

Where Can You Use the ended Event?

You can use the ended event on any HTML media element, such as <audio> and <video>. This event is particularly useful in web applications that involve media playback, such as video players, music players, and multimedia presentations.

How to Use the ended Event

Let’s dive into some examples to see how the ended event works in different scenarios.

Basic Example

Hereโ€™s a simple example to show how the ended event works with a video element.

HTML
<video id="myVideo" width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4" />
  Your browser does not support the video tag.
</video>
<p id="status">Status: Waiting for video to end โณ</p>

<script>
  const video = document.getElementById("myVideo");
  const status = document.getElementById("status");

  video.addEventListener("ended", () => {
    status.textContent = "Status: Video ended! ๐ŸŽ‰";
  });
</script>

In this example, the status message updates when the video ends.

Example with Audio Playback

Letโ€™s see how the ended event works with an audio element.

HTML
<audio id="myAudio" controls>
  <source src="audio.mp3" type="audio/mpeg" />
  Your browser does not support the audio element.
</audio>
<p id="audioStatus">Status: Waiting for audio to end โณ</p>

<script>
  const audio = document.getElementById("myAudio");
  const audioStatus = document.getElementById("audioStatus");

  audio.addEventListener("ended", () => {
    audioStatus.textContent = "Status: Audio ended! ๐ŸŽถ";
  });
</script>

In this example, the status message updates when the audio ends.

Example with Playlist

Letโ€™s see how the ended event can be used to play the next media in a playlist.

HTML
<video id="playlistVideo" width="320" height="240" controls>
  <source src="movie1.mp4" type="video/mp4" />
  Your browser does not support the video tag.
</video>
<p id="playlistStatus">Status: Playing first video ๐ŸŽฅ</p>

<script>
  const video = document.getElementById("playlistVideo");
  const status = document.getElementById("playlistStatus");
  const playlist = ["movie1.mp4", "movie2.mp4", "movie3.mp4"];
  let currentIndex = 0;

  video.addEventListener("ended", () => {
    currentIndex++;
    if (currentIndex < playlist.length) {
      video.src = playlist[currentIndex];
      video.play();
      status.textContent = `Status: Playing video ${currentIndex + 1} ๐ŸŽฌ`;
    } else {
      status.textContent = "Status: Playlist ended! ๐ŸŽ‰";
    }
  });
</script>

In this example, the video player automatically plays the next video in the playlist when the current video ends.

When to Use the ended Event

The ended event is particularly useful in scenarios where:

  • You need to trigger actions after media playback ends.
  • You want to create playlists that automatically play the next media.
  • You need to show messages or perform other actions when media playback is complete.

Comparing ended with Other Media Events

To understand the ended event better, letโ€™s compare it with other common media events.

EventDescriptionExample Usage
endedFired when media playback has endedShow messages, play next media
playFired when media playback is startedUpdate UI, log playback start
pauseFired when media playback is pausedUpdate UI, save playback position
timeupdateFired when the playback position changesUpdate progress bar, sync subtitles
seekingFired when a seek operation is initiatedDisplay loading indicator

Code Examples of Different Events

Here’s how you can use some of these events in your code:

HTML
<video id="mediaVideo" width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4" />
  Your browser does not support the video tag.
</video>
<p id="mediaStatus">Status: Waiting for interaction โณ</p>

<script>
  const video = document.getElementById("mediaVideo");
  const status = document.getElementById("mediaStatus");

  video.addEventListener("play", () => {
    status.textContent = "Status: Video playing! โ–ถ๏ธ";
  });

  video.addEventListener("pause", () => {
    status.textContent = "Status: Video paused! โธ๏ธ";
  });

  video.addEventListener("timeupdate", () => {
    status.textContent = `Status: Current time ${video.currentTime.toFixed(2)}s โฐ`;
  });

  video.addEventListener("seeking", () => {
    status.textContent = "Status: Seeking... ๐Ÿ”";
  });

  video.addEventListener("ended", () => {
    status.textContent = "Status: Video ended! ๐ŸŽ‰";
  });
</script>

Conclusion

The ended event in JavaScript is a powerful tool for handling user interactions when media playback ends. By understanding and using this event, you can create more interactive and user-friendly web applications. Whether you are showing messages, playing the next media in a playlist, or performing other actions, the ended event helps you ensure that your applications work smoothly and effectively.

Summary

  • What: The ended event fires when media playback has ended.
  • Why: It helps in triggering actions after media playback ends, creating playlists, and showing messages.
  • Where: Use it on any HTML media element that can capture media playback.
  • How: By adding an event listener for ended and handling the necessary actions.
  • When: Use it whenever you need to manage actions triggered by media playback ending to improve user experience.

Feel free to use the examples provided and modify them to suit your needs. Happy coding! ๐ŸŽ‰

What are JavaScript Browser Events?

JavaScript browser events are key to creating interactive web applications. These events are actions or occurrences detected by the browser, such as user interactions, document changes, or window modifications. By responding to events like clicks, key presses, and form submissions, developers can enhance user experience and functionality.

This comprehensive list of JavaScript browser events is a valuable reference for developers. It covers a wide range of events, from mouse and keyboard actions to document and window changes. Understanding and handling these events is essential for building responsive and engaging web applications, ensuring a seamless and intuitive user experience.

See List of all JavaScript Browser Events – Cheat Sheet

Leave a Reply