HTML onplay Event Attribute
Description
The onplay
HTML event attribute is used to specify a JavaScript function that will be executed when an audio or video element starts playing. The function can be used to perform any task, such as updating the display, starting a timer, or playing another media element.
The onplay
event is fired when the paused
property of the audio or video element is changed from true
to false
. This can happen as a result of the user clicking the play button, or by calling the play()
method on the element.
The onplay
event is not cancelable and does not bubble. This means that it cannot be prevented from firing, and it does not propagate up the DOM tree.
Example:
<audio onplay="myFunction()">
<source src="my-audio-file.mp3" type="audio/mpeg">
</audio>
function myFunction() {
// Do something when the audio element starts playing.
}
Use cases:
- Update the display to show that the media is playing.
- Start a timer to track the duration of the media.
- Play another media element when the current one starts playing.
- Pause or stop another media element when the current one starts playing.
- Update the playback controls to show the current playback position.
- Send an event to a server to notify it that the media has started playing.
Syntax
<element onplay="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
<!DOCTYPE HTML>
<html>
<body>
<audio id="myAudio" controls onplay="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: audio file is playing.");
}
</script>
<p>This example shows how to use the onplay attribute for an AUDIO element.</p>
</body>
</html>
Browser Support
The following table will show you the current browser support for the HTML onplay
Event Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023