The HTML onplay attribute is an event handler used to specify a script that will run when an audio or video element starts playing or is no longer paused.
Definition and Usage
➔ The user can initiate the play using media controls or programmatically.
➔ onplay is the opposite of the onpause event attribute.
Syntax
//In HTML
<video controls onplay="myFunction()" id="sample">
<source src="myvideo.mp4" type="video/mp4">
</video>
//In javascript
document.getElementById("sample").onplay=function() {myFunction();};
//OR
document.getElementById("sample").addEventListener("play", myFunction);
//OR
document.getElementById("sample").addEventListener("play", (event) => {
myFunction();
});
Example
<html>
<head>
<title>HTML onplay attribute example</title>
</head>
<body>
<h3>HTML onplay attribute example</h3>
<p>Set the src correctly and play/pause to trigger the event.</p>
<!-- "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4" -->
<video controls onplay="myFunction()" id="sample">
<source src="myvideo.mp4" type="video/mp4">
This browser does not support the video tag.
</video>
<script>
//In javascript
//document.getElementById("sample").onplay=function() {myFunction();};
//OR
//document.getElementById("sample").addEventListener("play", myFunction);
function myFunction() {
alert("The video has started to play!");
}
</script>
</body>
</html>