Categories
JavaScript Answers

How to listen to the play event on a HTML video element with JavaScript?

Spread the love

Sometimes, we want to listen to the play event on a HTML video element with JavaScript.

In this article, we’ll look at how to listen to the play event on a HTML video element with JavaScript.

How to listen to the play event on a HTML video element with JavaScript?

To listen to the play event on a HTML video element with JavaScript, can set onplay property of the video element to the event listener function.

For instance, we write:

<video src='https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4' controls></video>

to add a video.

Then we write:

const video = document.querySelector('video')
video.onplay = () => {
  console.log('playing')
}

to select the video element with querySelector.

Then we set video.onplay to a function that logs 'playing'.

Therefore, if the video is playing, 'playing' is logged.

Conclusion

To listen to the play event on a HTML video element with JavaScript, can set onplay property of the video element to the event listener function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.