Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onplay — handling the play event

The onplay attribute contains JavaScript executed for the play event, typically on an audio or video element. This event signals leaving the paused state, not a guarantee that sound or video is already playing.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

onplay="JavaScript statements"

onplay is an event handler content attribute for play. Its value is a JavaScript function body, not a file address or a Boolean attribute. It is typically used on audio and video elements; adding the attribute does not start playback.

The browser fires play when paused changes from true to false, for example through play() or autoplay. This does not yet mean actual playback: data may be unavailable. The playing event, handled through onplaying, concerns playback starting or resuming after stopping because of insufficient data.

In JavaScript, assign a function to media.onplay or use media.addEventListener('play', handler). Assigning the property replaces the previous function for that event handler slot. Content Security Policy can block code written directly in the attribute.

The example dispatches a synthetic play, so it needs no media file. The expected text is play; this tests handler wiring, not playback.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>onplay test</title>
<audio id="media" onplay="document.getElementById('result').textContent = event.type;"></audio>
<p id="result">pending</p>
<script>
  document.getElementById('media').dispatchEvent(new Event('play'));
</script>
</html>

Result

play

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources