patie patie -4 years ago 121
Javascript Question

Add link over video on certain time

I would like to add a link over a video on a certain time, between seconds 6 and 12, for example.
At the moment, I am getting the video current time, but I would like to do something like: if the video is playing between seconds 6 and 12, show this link.
This is my code:

<div id="video_container">
<video id="myVideo" controls>
<source src="video.mp4" type="video/mp4">
</video>
</div>

<div>Video current time: <p id="demo">0</p></div>

<div id="overlay">This is HTML overlay on top of the video! </div>


<script>
var vid = document.getElementById("myVideo");
vid.ontimeupdate = function() {myFunction()};

function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
document.getElementById("demo").innerHTML = vid.currentTime;
}

//This piece of code is where I'm trying to display the link
//**EDITED**
var overlay = document.getElementById('overlay');

var video = document.getElementById('myVideo');

video.addEventListener('progress', function() {
var show = video.currentTime >= 5 && video.currentTime < 10;
overlay.style.visibility= show ? 'visible' : 'visible';
}, false);

</script>

Answer Source

You can create an element and position it such that it overlays the video, and then remove this element once outside of the desired bounds in the video. However, it would be easier if you use a control that already does that like this one (igVideoPlayer).

That control has banners and commercials that you can configure and is available freely (open source).

I made a change to your code:

var overlay = document.getElementById('overlay');
overlay.style.visibility = "hidden";

var video   = document.getElementById('myVideo');

video.addEventListener('progress', function() {
  var show = video.currentTime >= 5 && video.currentTime < 10;
    overlay.style.visibility= show ? 'visible' : 'hidden';
}, false);

It works for me in your fiddle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download