HTML onended Event Attribute

Description

The HTML onended event attribute specifies a JavaScript function to be run when an audio or video element has finished playing. This can be useful for performing actions such as displaying a message, playing another media file, or updating the user interface.

To use the onended event attribute, simply add it to the <audio> or <video> element you want to listen for the event on. The value of the attribute should be the name of the JavaScript function to be run when the event occurs.

For example, the following code will display a message when the video element with the ID myVideo has finished playing:

<video id="myVideo" onended="myFunction()">
  <source src="myVideo.mp4" type="video/mp4">
</video>

<script>
function myFunction() {
  alert("The video has finished playing!");
}
</script>

The onended event can also be used to perform more complex tasks, such as updating the user interface or playing another media file. For example, the following code will play the next video in a playlist when the current video has finished playing:

<video id="myVideo" onended="playNextVideo()">
  <source src="myVideo1.mp4" type="video/mp4">
</video>

<script>
var videos = ["myVideo1.mp4", "myVideo2.mp4", "myVideo3.mp4"];
var currentVideoIndex = 0;

function playNextVideo() {
  currentVideoIndex++;

  if (currentVideoIndex < videos.length) {
    // Play the next video in the playlist.
    document.getElementById("myVideo").src = videos[currentVideoIndex];
  } else {
    // The end of the playlist has been reached.
    alert("The end of the playlist has been reached.");
  }
}
</script>

The onended event is a powerful tool for controlling the playback of audio and video content on your web pages. By using this event, you can create custom experiences that meet the specific needs of your users.

Syntax

<element onended="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE HTML>
<html>
<body>

<audio id="myAudio" controls onended="myFunction()">
<source src="audio.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>

<p>Play sound file.</p>

<script>
function myFunction() {
alert("EXAMPLE: Thank you for listening.");
}
</script>

<p>
This example shows how to use the onended attribute for an AUDIO element.</p>

</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onended Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 14th October 2023