Youtube v3 API related videos example using jquery

youtube v3 related videos example

In my previous tutorial, i have discussed the following youtube v3 API articles. In this tutorial, we are going to see how to get Youtube v3 API related videos using youtube v3 API.
1. Youtube v3 API search videos using jQuery
2. 1. Embed youtube video using youtube v3 API

First you need youtube API KEY to start using youtube v3 search videos API. If you don’t know how to get youtube API KEY please go through my article on how to get youtube api key/credentials.

This example will load one youtube video in the page, below to video you can find related video of the embedded video. Click on any related videos it will load the corresponding video and related videos for that.

Once you get the youtube API KEY, create a HTML file and place the below code inside the head tag.

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" type="text/css" />
<link href="css/font-awesome.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">

Everything is same which we used for Youtube v3 API search videos using jQuery. when you click on a particular video we are passing video id in the query string to grab the single video details from youtube API.
Place the below code inside you body tag.

<div id="main-container">
	<div class="video-content">
		<div id="video-player"></div>
		<div class="video-details">
			<div class="video-title"></div>
			<div>
			<div class="video-thumb-clip"></div>
				<div class="subinfo">
					<div class="video-user-info"></div>
					<div class="video-published-on"></div>
				</div>
			</div>
		</div>
	</div>
	
	<div class="main-content">
		
		<div class="pagination">
			<input type="hidden" id="cpage" value="">
			<div>
				<button type="button" id="pagePrev" class="btn-prev">Prev</button>
			</div>
			<div>
				<button type="button" id="pageNext" value="" class="btn-next">Next</button>
			</div>
		</div>
		
		<div>
		<div class="realtedHeader"><h2>Related videos </h2></div>
			<ul id="searchVideos" class="relatedVideos"></ul>
		</div>
	</div>
	
</div>

Below is the jQuery code to load suggestion keyword list and to call youtube API to pull all related videos. Event binding to next and previous pages. Place this code before body close tag.

<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script type="text/javascript">
jQuery(function() {
	var vid = "",API_KEY = 'AIzaSyBtulqn5WEszCH-H9Q5OFNluQPedW9VQp0'; // Replace with your API KEY
 
 function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function truncateString(str){
	var trucateStr = jQuery.trim(str).substring(0, 25).split(" ").slice(0, -1).join(" ") + "...";
	
	return trucateStr;
}
 function callSingleVideAPI(){
	 vid = getParameterByName("vid");
	 
	 if(!vid)
		 vid = "2qwWMAINkAc";
	 
 $.ajax({
	 cache: false,
	 data: $.extend({
		 key: API_KEY,
		 id: vid,
		 part: 'snippet'
	 }, {maxResults:15,pageToken:$("#cpage").val()}),
	 dataType: 'json',
	 type: 'GET',
	 timeout: 5000,
	 url: 'https://www.googleapis.com/youtube/v3/videos'
	 
 })
.done(function(resp) {
	var items = resp.items, videoContent = "";

		var video = items[0];
		$('.video-content').show();
		$("#video-player").html('<iframe width="100%" height="100%" src="https://www.youtube.com/embed/'+video.id+'?rel=1&showinfo=1" frameborder="0" allowfullscreen=""></iframe>');
		
		$(".video-title").text(video.snippet.title);
        $(".video-thumb-clip").html('<img width="48" height="48" src="'+video.snippet.thumbnails.default.url+'" />');
        $(".video-user-info").text("By "+video.snippet.channelTitle);
        $(".video-published-on").text("Published on "+video.snippet.publishedAt);
	
 });
}

function callRelateVideoAPI(){
	$.ajax({
	 cache: false,
	 data: $.extend({
		 key: API_KEY,
		 part: 'snippet',
		 relatedToVideoId: vid,
		 type:'video'
	 }, {maxResults:12,pageToken:$("#cpage").val()}),
	 dataType: 'json',
	 type: 'GET',
	 timeout: 5000,
	 url: 'https://www.googleapis.com/youtube/v3/search',
 })
.done(function(resp) {
	var items = resp.items, videoContent = "";
	console.log(resp);
	$('.main-content').show();
	if (typeof resp.nextPageToken === "undefined") {
		$('#pageNext').attr("disabled",true);
	}
	if (typeof resp.prevPageToken === "undefined") {
		$('#pagePrev').attr("disabled",false);
	}
	$("#pageNext").val(resp.nextPageToken);
	$("#pagePrev").val(resp.prevPageToken);
	$.each(items, function(index,item) {
		
		var strTruncatedTitle = truncateString(item.snippet.title);
		console.log("item ",strTruncatedTitle);
		videoContent += '<li class="list-item"><div class="thumb"><span class="thumb-img"><a href="youtube-related-videos.php?vid='+item.id.videoId+'"><img alt="'+item.snippet.title+'" src="'+item.snippet.thumbnails.default.url+'" width="120" height="90"></a></span></div><div class="video-content-box"><a href="youtube-related-videos.php?vid='+item.id.videoId+'"><span class="title">'+strTruncatedTitle+'</span></a><a><span class="channelTitle">by <span>'+item.snippet.channelTitle+'</span></span></a></div></li>';
	}); 
	$('#searchVideos').html(videoContent); 
 });
	
}

	 $("#pageNext").on( "click", function() {
		 $("#cpage").val($(this).val());
		 callRelateVideoAPI($('#suggesionBox').val());
	 });
	 $("#pagePrev").on( "click", function() {
		 $("#cpage").val($(this).val());
		 callRelateVideoAPI();
	 });
	 
	 //$('.main-content').hide();
	 
	 callSingleVideAPI();
	 callRelateVideoAPI();
	 
});
</script>

Please do comment for any help in the code. Also read my next article All examples related youtube v3 API

Please find below are the download and demo examples of this tutorial.

Download / Demo

You may also like...