JSFiddle - React, Tailwind, and code Playground
HTML
<div id="cc-uploadPhoto-youtubeGet" class="wrapper ccContainer">
<section class="contentAll">
<article id="youtube-headerContainer">
<p class="promptWithMargin2">Search for a youTube video by title, URL, user or keyword</p>
<input id="youtube-headerContainer-searchBox" type="text" class="youtubeSearch" />
<button id="youtube-headerContainer-search">search</button>
</article>
<article id="youtube-resultsContainer" class="youtubeResultContainter"></article>
</section>
<!--this is the template that we are cloning to populate with our youtube Results-->
<div id="youtube-resultsContainer-resultTemplate" class="youtubeResult hidden">
<iframe width="100%" height="195px" src="" frameborder="0" type="text/html"></iframe>
</div>
</div>
JavaScript
//startIndex controls the starting position of the search for the youtubeAPI call
//for example, if user wants the next 5 videos, we increment startIndex to 6 and make the api call again
var startIndex = 1;
// when they click on the search button...
$("#youtube-headerContainer-search").click(function () {
startIndex = 1;
fetchVideos();
});
//allow them start search by hitting enter key:
$("#youtube-headerContainer-searchBox").focus(function () {
$(this).keyup(function (e) {
if (e.which == 13) {
startIndex = 1;
fetchVideos();
console.log('enter key pressed');
}
});
});
//main function. it makes youtube APIcall and populates results container
function fetchVideos() {
//empty the results container
$('#youtube-resultsContainer').empty();
// construct the youtubeAPI search query:
var search_input = $('#youtube-headerContainer-searchBox').val();
var keyword = encodeURIComponent(search_input);
var yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + keyword + '&start-index=' + startIndex + '&format=5&type=video&videoSyndicated=true&videoEmbeddable=true&safeSearch=strict&max-results=5&v=2&alt=jsonc';
//make the API call:
$.ajax({
type: "GET",
url: yt_url,
dataType: "jsonp",
success: function (response) {
console.log(response);
//if we get videos back:
if (response.data.items) {
//loop through each video result and populate the results container
$.each(response.data.items, function (i, data) {
//extract the parts from the results set we are going to use:
var video_id = data.id;
var video_title = data.title;
//var video_frame="<iframe width='100%' height='195px' src='http://www.youtube.com/embed/"+video_id+"?version=3&enablejsapi=1"' frameborder='0' type='text/html'></iframe>";
...