HTML oncanplay Event Attribute

Description

The oncanplay HTML event attribute specifies a script to run when the browser can start playing the specified media (when it has buffered enough to begin). It is a non-cancelable event that does not bubble.

The oncanplay event is fired when the browser can start playing a media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.

This event is often used to start playing a media when it is ready, without having to wait for the entire media to be loaded. It can also be used to display a loading indicator while the media is buffering, and then hide the indicator when the media is ready to play.

Here is an example of how to use the oncanplay event attribute:

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

<script>
function myFunction() {
  // Start playing the video
  document.getElementById("myVideo").play();
}
</script>

In this example, the myFunction() function will be called when the browser can start playing the video, but before the entire video has been loaded. This function can then start playing the video, or perform any other actions that are needed.

The oncanplay event is a useful event attribute for controlling the playback of media on your web pages.

Syntax

<element oncanplay="script">

Values

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

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Событие oncanplay (элемент audio)</title>
</head>
<body>

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

<script>
function myFunction() {
alert("EXAMPLE: Audio file ready to play");
}
</script>

<p>Demonstration of the "oncanplay" attribute in the AUDIO element.</p>

</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML oncanplay 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