最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Trigger an event in javascript before a video has ended - Stack Overflow

programmeradmin5浏览0评论

I have a video that I fade in, play for ca. 25 seconds, fade out, wait 30 seconds and then fade in again. I use the following to trigger playback after video has ended:

$('.header-video').get(0).onended = function(e) {
  $(this).fadeOut(200);

  setTimeout(function(){
    playVideo();
  },8000);
}

Problem is that fading don't start until the video has actually stopped playback, so I wondered if there is some clever way I can get an event a few seconds in advance of the video ending? (probably not)

Alternatively I could just time the video and trigger a timed event, but maybe someone here can think of some cool wizardry that would enable me to do it in a more dynamic way than having to time the video manually.

I have a video that I fade in, play for ca. 25 seconds, fade out, wait 30 seconds and then fade in again. I use the following to trigger playback after video has ended:

$('.header-video').get(0).onended = function(e) {
  $(this).fadeOut(200);

  setTimeout(function(){
    playVideo();
  },8000);
}

Problem is that fading don't start until the video has actually stopped playback, so I wondered if there is some clever way I can get an event a few seconds in advance of the video ending? (probably not)

Alternatively I could just time the video and trigger a timed event, but maybe someone here can think of some cool wizardry that would enable me to do it in a more dynamic way than having to time the video manually.

Share Improve this question asked Jul 30, 2014 at 11:28 zkwskzkwsk 2,1366 gold badges31 silver badges35 bronze badges 2
  • Videos have a duration and a currentTime property. You could just use setInterval to check when currentTime > duration - 3000 – CodingIntrigue Commented Jul 30, 2014 at 11:32
  • Of course, should have thought of that. Post it as an answer and I'll accept it. – zkwsk Commented Jul 30, 2014 at 11:33
Add a ment  | 

1 Answer 1

Reset to default 7

You can use the timeupdate event that fires whenever the video's currentTime attribute updates.

Reference: https://developer.mozilla/en-US/docs/Web/Events/timeupdate

Example:

$(document).ready(function(){

    $( '.header-video' ).on(
        'timeupdate', 
        function(event){

            // Save object in case you want to manipulate it more without calling the DOM
            $this = $(this);

            if( this.currentTime > ( this.duration - 3 ) ) {
                $this.fadeOut(200);
            }

        });

});

JSFiddle

发布评论

评论列表(0)

  1. 暂无评论