<script>
// inject the youtube api script
$('<script src="https://www.youtube.com/iframe_api">').insertBefore($('script')[0]);
// setup the onYouTubeIframeAPIReady function
// this is the function called by the youtube api once it's ready
function onYouTubeIframeAPIReady() {
// loop through all the iframes on the page
$('iframe').each((i, frame) => { // for each iframe
// get the src
let src = $(frame).attr('src');
// skip the iframe if it's not a youtube video
if (!src.includes('youtube')) return;
// check if there's a pre-existing query string in the src
// to determine how to embed the enablejsapi=1 param
let enablejsapi = src.includes('?') ? '&enablejsapi=1' : '?enablejsapi=1';
// embed the enablejsapi=1 param
src = `${src + enablejsapi}`;
// set the new src as the iframe's src
$(frame).attr('src', src);
// create a unique id for the iframe
$(frame).attr('id', 'dynamic' + i);
// call the createPlayer function with the iframe's id
createPlayer(frame.id);
});
}
// setup the createPlayer function
function createPlayer(iframe) {
// initialize YT.player with the specified iframe's id
let player = new YT.Player(iframe, {
// setup the event function to be called when YT.player is ready
events: {
onReady: onPlayerReady
}
});
// setup the onPlayerReady function
function onPlayerReady(event) {
// when each timestamp is clicked
$(`#${iframe}`).closest('.container').find('.hacks-rich-text a').click(function (e) {
// stop default browser action
e.preventDefault();
// get the timestamp's text & split at the ':'
// this will result in an array with hours (optional), minutes, and seconds
let timestamp = $(this).text().trim().split(':');
// declare & initialize seconds at 0
let seconds = 0;
// process hours, minutes, and seconds
if (timestamp.length === 3) {
// format: HH:MM:SS
seconds += Number(timestamp[0]) * 3600; // hours to seconds
seconds += Number(timestamp[1]) * 60; // minutes to seconds
seconds += Number(timestamp[2]); // seconds
} else if (timestamp.length === 2) {
// format: MM:SS
seconds += Number(timestamp[0]) * 60; // minutes to seconds
seconds += Number(timestamp[1]); // seconds
} else if (timestamp.length === 1) {
// format: SS
seconds += Number(timestamp[0]); // seconds
}
// play the video at the specified seconds
player.seekTo(seconds);
});
}
}
</script>