Sometimes, we want to detect if an HTML5 video element is playing with JavaScript.
In this article, we’ll look at how to detect if an HTML5 video element is playing with JavaScript.
Detect if an HTML5 Video Element is Playing with JavaScript
To detect if an HTML5 video element is playing with JavaScript, we can listen to various events emitted by the HTML5 video element.
To do this, we can add the video element with the following HTML:
<div id="output"></div>
<video id="myVideo" width="320" height="176" controls autoplay>
<source src="https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4" type="video/mp4">
</video>
to add a div to show some text when various events are triggered.
Then we add a video element with the video.
Next, we add the following JavaScript code to listen to video player events and set the div content according to the event triggered:
const media = document.getElementById('myVideo');
const output = document.getElementById('output');
media.addEventListener("playing", () => {
output.innerHTML = "Playing event triggered";
});
media.addEventListener("pause", () => {
output.innerHTML = "Pause event triggered";
});
media.addEventListener("seeking", () => {
output.innerHTML = "Seeking event triggered";
});
media.addEventListener("volumechange", () => {
output.innerHTML = "Volumechange event triggered";
});
We get the video and div elements with document.getElementById
.
Then we call addEventListener
on the video player to listen to various events emitted by it.
The 'playing'
event is emitted when the video is playing.
The 'pause'
event is emitted when the video is paused.
The 'seeking'
event is emitted when we’re moving the seek bar.
The 'volumechange'
event is emitted when the video volume is changed.
In the event handlers, we set the innerHTML
of the div to the content we want to display.
Conclusion
To detect if an HTML5 video element is playing with JavaScript, we can listen to various events emitted by the HTML5 video element.