Home > Software engineering >  How to detect if the video reached a certain duration with jquery?
How to detect if the video reached a certain duration with jquery?

Time:12-05

I have an HTML video tag that plays a video with a duration of 02:40:

<video  controls controlsList="nodownload" id="video_player" stream-type="on-demand">
<source id="update_video_source" src="./video.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>

I would like to know how to use jquery to add an event listener capable of showing an alert when the video duration reaches 45 seconds.

CodePudding user response:

To add an event listener that shows an alert when the video duration reaches 45 seconds in jQuery, you can use the timeupdate event of the HTMLMediaElement interface, which is triggered whenever the time position of the media changes.

Here is an example:

// Select the video element
let video = $('#video_player');

// Add a timeupdate event listener to the video
video.on('timeupdate', function() {
  // Check if the video duration is 45 seconds
  if (this.currentTime === 45) {
    // Show an alert
    alert('The video duration is 45 seconds!');
  }
});

In this example, i use the $('#video_player') jQuery selector to select the video element with the id attribute set to video_player. We then add an event listener to the timeupdate event of the video element using the on method.

The event listener function is called whenever the timeupdate event is triggered, which occurs whenever the time position of the media changes. Inside the event listener function, we check if the currentTime property of the video element is equal to 45 seconds. If it is, we show an alert using the alert function.

  • Related