dungey_140
dungey_140

Reputation: 2792

How can I detect when the user is X seconds from the end of a video?

I need to detect when a video is 30 seconds from the end of the total. For example, if my video is 1m35s in length, I want to trigger an event when it reaches 1m05s.

UPDATE

I have worked out how to trigger an event at any point over 30 seconds from the end, i.e 30s, 29s, 28s and so on. The problem is, the code below trigger repeatedly each second, but I only want this event to occur once, wether it happens at -30s, -22s or -15s.

var video = $('#video');

function func() {
    if ( video[0].currentTime > video[0].duration-30 ) {
        console.log('You are less than 30 seconds from the end!');
    }
}

video.on('timeupdate', function() {
    func();
});

Upvotes: 2

Views: 1162

Answers (2)

mail2subhajit
mail2subhajit

Reputation: 1150

You can use a end of file event boolean variable - eofevent.

Logic : reset this variable when ever you start your playback. Use it as a flag , once triggered , don't call the func() again.

var video = $('#video');
var eofevent = false; 


function func() {
    if ( video[0].currentTime > video[0].duration-30 ) {
        console.log('You are less than 30 seconds from the end!');
        eofevent = true;
    }
}

video.on('timeupdate', function() {
    if( eofevent == false )
       func();
});

video.on('play', function() {
     if ( video[0].currentTime < video[0].duration ) {
        console.log('on Playing Reset!');
        eofevent = false;
    }
});

video.on('playing', function() {
    if ( video[0].currentTime < video[0].duration ) {
        console.log('on Playing Reset!');
        eofevent = false;
    }
});

Note: I am not a jquery /javascript coder , any syntax mistake please excuse.

Upvotes: 2

vqf
vqf

Reputation: 2628

I would say you need to unbind the timeupdate event once you reach your goal:

var video = $('#video');

function func() {
    if ( video[0].currentTime > video[0].duration-30 ) {
        console.log('You are less than 30 seconds from the end!');
        video.off('timeupdate'); // <--
    }
}

video.on('timeupdate', function() {
    func();
});

(I have not tested the code)

Upvotes: 0

Related Questions