Skip to content

Instantly share code, notes, and snippets.

@arturmkrtchyan
Created February 23, 2021 08:27
Show Gist options
  • Save arturmkrtchyan/6aa6e2f379c5f7efcadb244bc349f55b to your computer and use it in GitHub Desktop.
Save arturmkrtchyan/6aa6e2f379c5f7efcadb244bc349f55b to your computer and use it in GitHub Desktop.
function loadVimeoThumbnail(url, callback){
$.ajax({
type:'GET',
url: 'https://vimeo.com/api/oembed.json?url=' + encodeURIComponent(url),
dataType: 'json',
success: callback
});
}
function isVimeo(url) {
var match = /vimeo.*\/(\d+)/i.exec(url);
return match;
}
function getVimeoVideoId(url) {
var match = /vimeo.*\/(\d+)/i.exec(url);
if(match && match.length > 1) {
return match[1];
}
return null;
}
function isYoutube(url){
VID_REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
return url.match(VID_REGEX);
}
function getYoutubeVideoId(url){
VID_REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
var match = url.match(VID_REGEX);
if(match && match.length > 1) {
return match[1];
}
return null;
}
function autoGenerateThumbnail() {
const imgSrc = $('#{{hrid}} img').attr('src');
const videoUrl = $('#{{hrid}} a').attr('href');
if(!imgSrc && videoUrl) {
if(isYoutube(videoUrl)) {
var videoId = getYoutubeVideoId(videoUrl);
var imgUrl = 'https://img.youtube.com/vi/' + videoId + '/hqdefault.jpg';
$('#{{hrid}} img').attr('src', imgUrl);
} else if(isVimeo(videoUrl)) {
var videoId = getVimeoVideoId(videoUrl);
if(videoId) {
loadVimeoThumbnail(videoUrl, function(data) {
$('#{{hrid}} img').attr('src', data['thumbnail_url']);
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment