Embed youtube video using youtube v3 API

youtube grab single video embed

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.

Once you get the youtube API KEY, create an 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="search-container">
		<input type="text" name="suggesionBox" id="suggesionBox" class="search" autocomplete="off" /> 
		<button class="btn-icon-search"><i class="fa fa-search" aria-hidden="true"></i></button>
	</div>
	
	<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>
			<ul id="searchVideos"></ul>
		</div>
	</div>
	
</div>

Below is the jQuery code to load suggestion keyword list and to call youtube API to pull the videos. 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() {
 jQuery("#suggesionBox").autocomplete({
	source: function(req, rsp) {
		var formattedResponsealue = [];
		jQuery.ajax({
			type: "POST",
			url: "http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1&q="+req.term,
			dataType: 'jsonp',
			success: function(data) {
				jQuery.each(data[1], function(key, value) {
					if(value[0]){
						formattedResponsealue.push(value[0]);
					}
				});
				rsp(formattedResponsealue);
		 }
	 });
	},
	select:function(evt,obj){
		callAPI(obj.item.value);
	}
 });
 
 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 callAPI(searchTerm){
	 var vid = getParameterByName("vid"),extparam,URL = "";
	 if(!vid)
		 vid = "4QHwTwglmO4";
	 
	 if(searchTerm){
	 extparam = $.extend({
		 key: 'AIzaSyBtulqn5WEszCH-H9Q5OFNluQPedW9VQp0', // Replace with your API KEY
		 q: searchTerm,
		 part: 'snippet',
		 chart: 'mostPopular'
	 }, {maxResults:15,pageToken:$("#cpage").val()});
	 URL = 'https://www.googleapis.com/youtube/v3/search';
	 }else{
		extparam = $.extend({
		 key: 'AIzaSyBtulqn5WEszCH-H9Q5OFNluQPedW9VQp0', // Replace with your API KEY
		 id: vid,
		 part: 'snippet'
	 }, {maxResults:15,pageToken:$("#cpage").val()});
	 URL = 'https://www.googleapis.com/youtube/v3/videos'
	 }
	 
	 
 $.ajax({
	 cache: false,
	 data: extparam,
	 dataType: 'json',
	 type: 'GET',
	 timeout: 5000,
	 url: URL
	 
 })
.done(function(resp) {
	var items = resp.items, videoContent = "";
	
	
	
	if(searchTerm){
		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) {
			if(item.id.videoId)
			videoContent += '<li class="list-item"><div class="thumb"><span class="thumb-img"><a href="youtube-single-video.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-single-video.php?vid='+item.id.videoId+'"><span class="title">'+item.snippet.title+'</span></a><a><span class="channelTitle">by <span>'+item.snippet.channelTitle+'</span></span></a></div></li>';
		});
		$("#video-player").hide();
		$('.video-content').hide();
		$('#searchVideos').html(videoContent).show(); 

	}else{
		var video = items[0];
		$('#searchVideos').hide();
		$('.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);

	}
 });
}

	$("#pageNext").on( "click", function() {
		 $("#cpage").val($(this).val());
		 callAPI($('#suggesionBox').val());
	 });
	 $("#pagePrev").on( "click", function() {
		 $("#cpage").val($(this).val());
		 callAPI($('#suggesionBox').val());
	 });
	 $(".btn-icon-search").on( "click", function() {
		 callAPI($('#suggesionBox').val());
		 return false;
	 });
	 
	 $('.main-content').hide();
	 
	 callAPI();
	 
});
</script>

Please do comment for any help in the code. Also read my next article on Youtube v3 API related videos example using jquery

Download / Demo

You may also like...