javascripthtmlif-statementcurrent-time

perform function when video's current time is greater than a certain value


i would like to hide a div after a video has reached a certain time. The following code is what I thought would in theory work but is not currently. Any solution would be appreciated!

 <body>
 <video id="vid" src="somevideo.mp4"></video>
 <div id="box"></div>
 <script>
    function hideDiv() {
  if (vid.currentTime > 5) {
  document.getElementById('box').style.display = 'none';
 }}

 </script>
 </body>

Solution

  • You need to attach an event handler to the timeupdate event.

    document.querySelector('video').addEventListener('timeupdate', (e) => {
      if (e.currentTarget.currentTime > 5) {
        document.querySelector('#box').style.display = 'none';
      }
    });
    

    You may also want to remove this event handler when done with it as well.

    See also: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/timeupdate_event