I have a video tag. I want to appear a button ‘next’ When 5 seconds have passed from the video. Below code but not work.
<script>
var vid1 = document.getElementById("MyVid1");
var btn = document.getElementById("btn");
btn.style.display = "none";
vid1.play();
if(vid1.currentTime==5){
btn.style.display = "block";}
</script>
<video width="320" height="240" id="MyVid1" controls >
<source src="vid/1.mp4" type="video/mp4">
</video>
<button id='btn' >tryit</button>
2
Answers
Instead of checking
.currentTime
just once, you can set an event listener on thetimeupdate
event and check.currentTime
whenever it is fired.Use track cues to synchronize events with video
This alternative solution is slightly more complex, but very useful when you need to synchronize UI events with a playing video. It also avoids the need to continuously check the video time.
Video tracks are typically used to display subtitles and captions at precise times. There are also metadata tracks that are hidden from view.
We can add a metadata track to the video and then add any number of time based cues to the track. Each cue has a start and stop time which can execute a function. Cues also trigger cuechange events. All of these can be used to synchronize UI changes with the video.
This simple example has only one track with one cue that displays a button at the 5 second mark. The button is hidden again when the video restarts.