Reputation: 862
I am trying to add an 'onclick' event-listener to my video after 5 seconds that the video has started playing and it should redirect user to a certain URL. My current js code:
document.getElementById('my_video_1').addEventListener("timeupdate", myfunc, false);
function myfunc() {
console.log('in my func');
if (this.currentTime > 5) {
console.log('in if');
this.onclick = function () {
location.href = "www.google.com";
};
}
}
The problem is that it seems the function is being executed every time 'timeupdate' fires. But I want to assign the onclick handler to video once the video currenttime reaches 5 and then finish executing myfunc.
Any ideas how I can do this?
Is there any better way to serve my purpose?
Upvotes: 0
Views: 56
Reputation: 966
As I mentioned in the comments, instead of using the timeupdate
event (which means your function is executed every time your video is playing, or the playback position of it is moved), it's better to use just the click
event (with the addEventListener
method, or with the onclick
property).
/* Attach the click event with the addEventListener() method
By default, the third parameter, useCapture, is false */
document.getElementById("my_video_1").addEventListener("click", myfunc);
/* Attach the click event with the onclick property */
document.getElementById("my_video_1").onclick = myfunc;
Then, in the function who executes by the click event trigerring, you check if the current time of the video is over 5 seconds.
function myfunc() {
if (this.currentTime > 5) {
location.href = "http://www.google.com";
};
}
This is the full sample code (contains both HTML and JavaScript):
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
</head>
<body>
<video id="my_video_1" width="426px" height="240px" autoplay controls muted>
<source src="https://media.w3.org/2010/05/sintel/trailer.mp4" type="video/mp4"/>
</video>
</body>
<script>
document.getElementById("my_video_1").addEventListener("click", myfunc);
// document.getElementById("my_video_1").onclick = myfunc;
function myfunc() {
if (this.currentTime > 5) {
location.href = "https://www.google.com";
};
}
</script>
</html>
Upvotes: 1