This example demonstrates how to confirm that playback has begun and how to gracefully
handle blocked automatic playback:
let
videoElem
=
document
.
getElementById
(
"video"
)
;
let
playButton
=
document
.
getElementById
(
"playbutton"
)
;
playButton
.
addEventListener
(
"click"
,
handlePlayButton
,
false
)
;
playVideo
(
)
;
async
function
playVideo
(
)
{
try
{
await
videoElem
.
play
(
)
;
playButton
.
classList
.
add
(
"playing"
)
;
}
catch
(
err
)
{
playButton
.
classList
.
remove
(
"playing"
)
;
}
}
function
handlePlayButton
(
)
{
if
(
videoElem
.
paused
)
{
playVideo
(
)
;
}
else
{
videoElem
.
pause
(
)
;
playButton
.
classList
.
remove
(
"playing"
)
;
}
}
In this example, playback of video is toggled off and on by the
async
playVideo()
function. It tries to play the video, and if successful sets
the class name of the
playButton
element to
"playing"
. If
playback fails to start, the
playButton
element's class is cleared,
restoring its default appearance. This ensures that the play button matches the actual
state of playback by watching for the resolution or rejection of the
Promise
returned by
play()
.
When this example is executed, it begins by collecting references to the
<video>
element as well as the
<button>
used to toggle
playback on and off. It then sets up an event handler for the
click
event
on the play toggle button and attempts to automatically begin playback by calling
playVideo()
.
You can
try out or remix this example in real time on Glitch
.