Skip to content

Instantly share code, notes, and snippets.

@karmaniverous
Last active July 21, 2021 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karmaniverous/df3fad0522c20bcf671b8710ad65ad5f to your computer and use it in GitHub Desktop.
Save karmaniverous/df3fad0522c20bcf671b8710ad65ad5f to your computer and use it in GitHub Desktop.
Make a YouTube deep link scroll to the embedded video, skip to the time code, and start playing.
/*****
- Embed a YouTube video on a page.
- Put a deep link to the same video (https://youtu.be/1a2b3c4d5e6?t=123) into a container with class .tribify-video-control.
- When you click the link, the page will smooth-scroll to the embedded video, skip to the designated time code, and begin playing.
This example assumes you are running WordPress with jQuery and are using a standard YouTube embed iframe.
*****/
// Set up event handler. Only applies to a tags inside a container of class .tribify-video-control.
jQuery(document).on('ready', function() {
jQuery('.tribify-video-control a').on('click', tribifyVideoControlClick);
});
// Handle the click event. Only fires for standard YouTube sharing links.
// Will scroll to the first Youtube embed iframe placed ABOVE the link.
// Applies scroll offset for WordPress #wpadminbar) & #masthead containers.
function tribifyVideoControlClick() {
try {
const a = jQuery(this);
const href = a.attr('href');
const hrefVideoId = getYouTubeVideoId(href);
if (!hrefVideoId) return true;
const hrefUrl = new URL(href);
const t = parseInt(hrefUrl.searchParams.get('t')) || 0;
const tvc = a.closest('.tribify-video-control');
const iframe = tvc.find('iframe').first();
if (!iframe) return true;
const iframeId = iframe.attr('id');
if (!iframeId) return true;
const player = YT.get(iframeId);
if (!player) return true;
const playerVideoUrl = player.getVideoUrl();
const playerVideoId = getYouTubeVideoId(playerVideoUrl);
if (playerVideoId !== hrefVideoId) return true;
const offset = (jQuery('#wpadminbar').height() || 0) + (jQuery('#masthead').height() || 0);
jQuery('html, body').animate({scrollTop: tvc.offset().top - offset - 10}, 400, 'easeInQuint');
player.seekTo(t, true);
player.playVideo();
return false;
}
catch(e) {
console.log(e);
return false;
}
}
// Extract video id from YouTube link.
function getYouTubeVideoId(url) {
url = url.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
return (url[2] !== undefined) ? url[2].split(/[^0-9a-z_\-]/i)[0] : url[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment