View video tutorial

HTML oncanplay Attribute

HTML

The oncanplay attribute in HTML defines a script that will be executed when the browser assumes that it can start playing the specified audio or video.

Definition and Usage


➔ This event can be used to buffer enough data to start playback. Although there is no guarantee that the entire media will play without any interruptions.

➔ The oncanplay attribute is mainly used with <audio> and <video>.

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML oncanplay attribute example</title>
    <meta charset="utf-8" />
</head>
<body>
    <h3>HTML oncanplay attribute example</h3>
    <div>
        <video controls oncanplay="myHandler()">
<!-- "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4" -->
            <source src="" type="video/mp4">
        </video>
        <script>
            function myHandler() {
                alert("Can start playing video");
            }
        </script>
        <p>Note: If you set src correctly, the handler will generate a alert.</p>
    </div>
</body>
</html>

Applies to

This attribute can be used on the following element.

Attribute Element
oncanplay <audio>, <embed>, <object>, <video>

➔ Using Scripting.

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML oncanplay attribute example</title>
    <meta charset="utf-8" />
</head>
<body>
    <h3>HTML oncanplay attribute example</h3>
    <div>
        <video controls id="myvideoid">
<!-- "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4" -->
            <source src="video-path.mp4"
                type="video/mp4">
        </video>
        <script>
            let myvideoid = document.querySelector("#myvideoid");
            myvideoid.oncanplay = myHandler;
            function myHandler() {
                alert("Can start playing video");
            }
        </script>
        <p>Note: If you set src correctly, the handler will generate a alert.</p>
    </div>
</body>
</html>

➔ Using Scripting with Listener.

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML oncanplay attribute example</title>
    <meta charset="utf-8" />
</head>
<body>
    <h3>HTML oncanplay attribute example</h3>
    <div>
        <video controls id="myvideoid">
<!-- "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4" -->
            <source src="path-ofthe-video.mp4"
                type="video/mp4">
        </video>
        <script>
            let myvideoid = document.querySelector("#myvideoid");
            myvideoid.addEventListener("canplay", myHandler);
            function myHandler() {
                alert("Can start playing video");
            }
        </script>
        <p>Note: If you set src correctly, the handler will generate a alert.</p>

    </div>
</body>
</html>

Click on the "copy" button and try this example in your project.