JQuery bind: run function before ends

I am creating a simple php page that plays back a video playlist using HTML5 video, and a jQuery bind function for fadeIn and play the next video after the current video ends.

Binding functions to a completed event works very well, but I would like to run the fadeIn and play function (say) 20 seconds before the video ends.

But I can’t figure out how to do this. Is it possible?

My HTML:

<video controls preload="auto"> <source src="sequence01.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' /> </video> <video controls preload="auto"> <source src="sequence01.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' /> </video> 

My jQuery:

 $('video').bind("ended", function(){ $(this).fadeOut(20000).next().fadeIn(20000).get(0).play(); }); 

SOLVE!

 $('video').on('timeupdate', function(event) { var current = Math.round(event.target.currentTime * 1000); var total = Math.round(event.target.duration * 1000); if ( ( total - current ) < 20000 ) { $(this).fadeOut(2000).next().fadeIn(2000).get(0).play(); } }); 

Thank you so much for helping the guys, I was able to compose the answer using your wonderful comments, and this other seemingly inappropriate publication of SO:

Uncaught TypeError: Object [object Object] does not have a method of 'addEventlistner'

if anyone has a cleaner way to put this together, it will be awesome, but it seems to work very well for my purposes.

+6
source share
2 answers

The first answer I gave had some problems. I changed it to be right

 var myVid = document.getElementById("video1"); myVid.addEventListener('timeupdate', function() { if( (myVid.duration - myVid.currentTime ) < 20000 ) { console.log("less than 20 seconds left"); } }); 

this requires that you specify the video tag identifier, and console.log should be replaced with what you want to do inside the function. however, I tested this and it works well.

in your case, you will need to start the loop and bind the event to each video, but make sure that you are referring to the actual video and not to its properties, such as length or element.

if you copy and paste this code into the <script> tags in the "Try it yourself" section of this example, it will work.

http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_event_progress

here is a link to the properties and events of video objects

http://www.w3schools.com/tags/ref_av_dom.asp

+1
source

You can use any of them:

 $('video').currentTime; $('video').duration; 

I will not write code, but you should check that

 if ( ( this.duration - this.currentTime ) < 20000 ) 

Check out http://dev.opera.com/articles/view/custom-html5-video-player-with-css3-and-jquery/

0
source

All Articles