Sometimes, we want to tell if a video element is currently playing with JavaScript.
In this article, we’ll look at how to tell if a video element is currently playing with JavaScript.
How to tell if a video element is current
To tell if a video element is currently playing with JavaScript, we check a few properties in the video element.
For instance, we write
const isVideoPlaying = (video) =>
!!(
video.currentTime > 0 &&
!video.paused &&
!video.ended &&
video.readyState > 2
);
to define the isVideoPlaying function that takes a video element object.
In it, we check if the currentTime is bigger than 0 seconds.
We then check it’s not paused with paused and negating that.
We check it’s not ended with ended and negating that.
And then we check that its readyState is bigger than 2, which means the video is loaded.
If they’re all truthy, then the video is playing.
Conclusion
To tell if a video element is currently playing with JavaScript, we check a few properties in the video element.