Skip to content

Instantly share code, notes, and snippets.

@acanza
Last active October 7, 2022 06:52
Show Gist options
  • Save acanza/4c46a8bcb3737016f63da61f74a0ca9f to your computer and use it in GitHub Desktop.
Save acanza/4c46a8bcb3737016f63da61f74a0ca9f to your computer and use it in GitHub Desktop.
[TCY] JWPlayer script
window.onload = function () {
//Create player instance
var player = jwplayer(yt_lessons_scripts_params.video_id);
var videoDuration = 0;
var totalTimeWatched = 0;
var previousPosition = 0;
var percentageWatched = 0;
var isDoneToday = yt_lessons_scripts_params.is_done_today === 'true';
var doneAjaxCallRuning = false;
const urlParameters = new URLSearchParams(window.location.search);
// Get the total duration of the video
player.on('play', (e) => {
videoDuration = player.getDuration();
});
// Calculating the percentage watched
player.on('time', (e) => {
if ((!isDoneToday && !doneAjaxCallRuning) || (Object.keys(ajaxDoneCalendarEvent).length > 0 && ajaxDoneCalendarEvent.event.status !== 'done' && !doneAjaxCallRuning)) {
const { position } = e;
totalTimeWatched += (position - previousPosition);
percentageWatched = (totalTimeWatched / videoDuration) * 100;
// Reset the seek position
previousPosition = position;
// Set the lesson as "done" on the calendar and in the user profile
if (percentageWatched >= parseFloat(yt_lessons_scripts_params.minimum_viewing_time)) {
let ajaxData = {
action: yt_lessons_scripts_params.update_done_lesson_status_action,
nonce: yt_lessons_scripts_params.nonce,
post_id: yt_lessons_scripts_params.post_id,
done: isDoneToday,
call_origin: 'video_playback'
};
if (Object.keys(ajaxDoneCalendarEvent).length > 0) {
ajaxData = Object.assign(ajaxData, ajaxDoneCalendarEvent);
}
// Avoid the call will be repeated
doneAjaxCallRuning = true;
updateDoneList(ajaxData);
} else if (percentageWatched >= parseFloat(yt_lessons_scripts_params.pending_status_threshold)) {
if (!startedLessonAjaxCallRunning && !isStartedLessonRegistered && urlParameters.get('referer') === 'yt_program') {
registerStartedLesson(yt_lessons_scripts_params.post_id, yt_lessons_scripts_params.user_id);
}
}
}
});
// Update the previous position of the seek when it change
player.on('seek', (e) => {
previousPosition = e.offset;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment