Search code examples
htmlhtml5-videosettimeout

How to detect when HTML5 video is played the first frame?


I ask this because I would like to show a overlay image on exact play time like on 3:00.

Therefore, I binded the "play" event and state setTimeout(...,18000) to show the image.

However, it seems the setTimeout is done too early. The image is shown faster than expected. I can unterstand as the "play" event is fired BEFORE the video is prepared.

So I also tried to bind "loadeddata" and "playing" event. But this time, the image is shown slower than expected.

Also, the image seems to show in "random manner" (not always show on the same time with a few tests, a little bit different).

Is there a event that I can use setTimeout to show image on exact time? Or in simple, how can I show an image on video exact time?


Solution

  • There is another way to do this using currentTime and defining a function for everytime the time for the video changes. Set a div on top of HTML5 video element and modify that element when currentTime is between 3 and 4 seconds.

    Sample code would look like this:

    HTML:

    <div id="wrap_video">
    
    <div id="video_box">
        <div id="video_overlays"></div>
        <div>
            <video id="myVideo" width="320" height="176" controls autoplay>
      <source src="https://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">
    
      Your browser does not support HTML5 video.
           </video>
        </div>
    </div>
    
    </div>
    

    CSS:

    #video_box{
        position:relative;
    }
    #video_overlays {
        position:absolute;
        width:160px;
        min-height:100px;
        background:transparent;
        z-index:300000;
        bottom:50px;
        left:10px;
        text-align:center;
    }
    

    JavaScript:

    var vid = document.getElementById("myVideo");
    
    // Assign an ontimeupdate event to the video element, and execute a function if the current playback position has changed
    vid.ontimeupdate = function() {myFunction()};
    
    function myFunction() {
        //if currentTime is greater than 3 but less than 4, as in second 3+, go into if statement, otherwise go to else statement
        if (vid.currentTime > 3 && vid.currentTime < 4) {
            document.getElementById("video_overlays").innerHTML = '<p>Image Here</p>';
        }
        else {
            document.getElementById("video_overlays").innerHTML = '';
        }
    }
    

    You can inside the first if statement pause the video and then show an image and then make the video start again after a certain timeout, if that was your intention but this code is essentially the skeleton to do something like that.

    Working sample: http://jsfiddle.net/l33tstealth/wgcbcf1t/10/