1

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>
lucidigi
  • 47
  • 4

1 Answers1

0

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

Brad
  • 159,648
  • 54
  • 349
  • 530
  • thank you! works beautifully! two other questions if you have the time. 1.) how would you remove the event listener from that (the arrow functions seem to be a bit trickier). 2.) how could you make it so the vid is paused if the display of the div is = "none". appreciate it! – lucidigi Mar 08 '21 at 00:17
  • @lucidigi If you want to remove the event listener, you'll need to use a named function. As for handling pause/play, there are events named `pause` and `play` you can use, as well as the `paused` property. All the documentation is available on MDN: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement – Brad Mar 08 '21 at 00:48