I'm having a problem with the asynchronous methods that prints and returns all vidDuration values then viewCount values were placed for each videoId, but vidDuration repeated only the last value that was received and assigned it to all of the videoIds which is clearly wrong.
I tried setting up a temporary array called tempArray within the loop that store each of the vidDuration values which it did, then to print them to each vidDuration, but then again, it looped through the output however many values are in the array and duplicated the videos, which I don't want. I commented out lines involving tempArray and reverted back to the working problem.
From what I understand, the async methods printed all of the duration values without going to the output as if it got stuck there until it was done and resolved and then it looped the viewCount and output perfectly fine. I'm wondering how do I fix this in a programmatically logical way?
Script:
var channelName = 'ExampleChannel';
var vidWidth = 500;
var vidHeight = 400;
var vidResults = 15; /* # of videos to show at once - max 50 */
var vidDuration = "";
var viewCount = 0;
var videoId = "";
$(document).ready(function() {
$.get( // get channel name and load data
"https://www.googleapis.com/youtube/v3/channels",
{
part: 'contentDetails',
forUsername: channelName,
key: 'XXXXXXXX'
},
function(data)
{
$.each(data.items,
function(i, item) {
console.log(item); // log all items to console
var playlistId = item.contentDetails.relatedPlaylists.uploads;
getPlaylists(playlistId);
})
}
);
// function that gets the playlists
function getPlaylists(playlistId)
{
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",
{
part: 'snippet',
maxResults: vidResults,
playlistId: playlistId,
key: 'XXXXXXXX'
},
// print the results
function(data)
{
var output;
/*var tempArray = new Array();*/ // temporary array for storing video duration values
$.each(data.items,
function(i, item) {
console.log(item);
var vidTitle = item.snippet.title; // video title
var vidDesc = item.snippet.description; // video description
var videoId = item.snippet.resourceId.videoId; // video id
// check if description is empty
if(vidDesc == null || vidDesc == "")
{
vidDesc = "No description was written."; // FIX: test msg to see where it still shows up
$('#desc').remove(); // remove video description
}
else vidDesc = item.snippet.description;
getVideoDuration(videoId).done(function(r){
vidDuration = r;
console.log(r);
/*tempArray[i] = r;*/ // store value into each array index
/*console.log("Array:", tempArray[i], tempArray);*/ // log to console
/*i++;*/ // increment
getViewCount(videoId).done(function(r){
viewCount = r;
console.log(r);
//vidDuration = getVideoDuration(videoId);
//viewCount = getViewCount(videoId);
// temp array index to loop thru array
/*$.each(tempArray, function(i){
vidDuration = tempArray[i]; // assign index value to vidDuration
console.log("In Each vidDuration: ", vidDuration);
i++;
});*/
console.log("id: " + videoId + " duration: " + vidDuration + " viewCount: " + viewCount); // return value in console
output = '<li><iframe height="' + vidHeight + '" width="' + vidWidth + '" src=\"//www.youtube.com/embed/' + videoId + '\"></iframe></li><div id="title">' + vidTitle + '</div><div id="desc">' + vidDesc + '</div><div id="duration">Length: ' + vidDuration + '</div><div id="stats">View Count: ' + viewCount + '</div>';
// Append results to list tag
$('#results').append(output);
}); // end of getVideoDuration(videoId).done
}); // end of getViewCount(videoId).done
});
/*console.log("TEMPARRAY[]",tempArray);*/ // print entire array
}
);
}
// return video duration
function getVideoDuration(videoId)
{
var defer1 = $.Deferred();
var r = '';
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails',
id: videoId,
key: 'XXXXXXXX',
},
function(data)
{
$.each(data.items,
function(i, item) {
r = item.contentDetails.duration;
defer1.resolve(r);
console.log("in vidDuration func", r);
});
}
);
return defer1.promise();
}
// return video view count
function getViewCount(videoId)
{
var defer2 = $.Deferred();
var r = '';
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails, statistics',
id: videoId,
key: 'XXXXXXXX',
},
function(data)
{
$.each(data.items,
function(i, item) {
r = item.statistics.viewCount;
defer2.resolve(r);
console.log("in viewCount func", r);
});
}
);
return defer2.promise();
}
});
Screenshot results (normal refresh):
Screenshot results (using debugger):
Here's a screenshot of the results when stepping through with the debugger console. (Why are the results different from when the page normally loads? Is this typical action of the async methods? How do I fix this?)
In fact the second promise is misplaced, the second promise is resolved AFTER that all the promises from the first promise have been resolved, so the last value is save. logical
Now if you resolve the first promise WHEN second is resolved one by one you are able to correct the problem.
var view = 0;
r = item.contentDetails.duration; // video duration
getViewCount(videoId).done(function(t){
view = t;
dfrd1.resolve(r, view);
});
Check the screenshot:
I change a bit the code to solve the problem.
var channelName = 'example';
var vidWidth = 500;
var vidHeight = 400;
var vidResults = 15; /* # of videos to show at once - max 50 */
var vidDuration = "";
var viewCount = 0;
var videoId = "";
$(document).ready(function() {
$.get( // get channel name and load data
"https://www.googleapis.com/youtube/v3/channels",
{
part: 'contentDetails',
forUsername: channelName,
key: 'xxx'
},
function(data)
{
$.each(data.items,
function(i, item) {
//console.log(item); // log all items to console
var playlistId = item.contentDetails.relatedPlaylists.uploads;
//var viewCount = console.log(item.statistics.viewCount);
getPlaylists(playlistId);
});
}
);
// function that gets the playlists
function getPlaylists(playlistId)
{
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems",
{
part: 'snippet',
maxResults: vidResults,
playlistId: playlistId,
key: 'xxx'
},
// print the results
function(data)
{
var output;
$.each(data.items,
function(i, item) {
console.log(item);
var vidTitle = item.snippet.title; // video title
var vidDesc = item.snippet.description; // video description
var videoId = item.snippet.resourceId.videoId; // video id
// check if description is empty
if(vidDesc == null || vidDesc == "")
{
vidDesc = "No description was written."; // FIX: test msg to see where it still shows up
$('#desc').remove(); // remove video description
}
else vidDesc = item.snippet.description;
getVideoDuration(videoId).done(function(d, v){
vidDuration = d;
//console.log(r);
viewCount = v;
document.write("id: " + videoId + " duration: " + vidDuration + " viewCount: " + viewCount); // return value in console
document.write("<br>");
output = '<li><iframe height="' + vidHeight + '" width="' + vidWidth + '" src=\"//www.youtube.com/embed/' + videoId + '\"></iframe></li><div id="title">' + vidTitle + '</div><div id="desc">' + vidDesc + '</div><div id="duration">Length: ' + vidDuration + '</div><div id="stats">View Count: ' + viewCount + '</div>';
// Append results to list tag
$('#results').append(output);
});
});
}
);
}
// return video duration
function getVideoDuration(videoId)
{
var dfrd1 = $.Deferred();
var r = '';
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails',
id: videoId,
key: 'xxx',
},
function(data)
{
$.each(data.items,
function(i, item) {
//videoId = item.snippet.resourceId.videoId;
var view = 0;
r = item.contentDetails.duration; // video duration
getViewCount(videoId).done(function(t){
view = t;
dfrd1.resolve(r, view);
});
//alert(videoId);
});
}
);
return dfrd1.promise();
}
// return video view count
function getViewCount(videoId)
{
var dfrd2 = $.Deferred();
var r = '';
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails, statistics',
id: videoId,
key: 'xxx',
},
function(data)
{
$.each(data.items,
function(i, item) {
//videoId = item.snippet.resourceId.videoId;
r = item.statistics.viewCount; // view count
//alert(videoId);
dfrd2.resolve(r);
// console.log("in", r);
});
}
);
return dfrd2.promise();
}
});
Related
I have a YouTube API working for fetching and listing to video, when user clicks on thumbnail they get the video autoplay perfectly, but I would like when the first video is finished, the next video from my list autoplays also.
I've looked on Stack Overflow but haven't found one that fits my needs. Here is the code:
// Searchbar Handler
$(function () {
var searchField = $('#query');
var icon = $('#search-btn');
// Focus Event Handler
$(searchField).on('focus', function () {
$(this).animate({
width: '100%' },
400);
$(icon).animate({
right: '10px' },
400);
});
// Blur Event Handler
$(searchField).on('blur', function () {
if (searchField.val() == '') {
$(searchField).animate({
width: '45%' },
400, function () {});
$(icon).animate({
right: '360px' },
400, function () {});
}
});
$('#search-form').submit(function (e) {
e.preventDefault();
});
});
function search() {
// Clear Results
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API********************************
$.get(
"https://www.googleapis.com/youtube/v3/search?maxResults=**", {
part: 'snippet, id',
q: q+'********',
fs:1,
hd:1,
type: 'video',
videoCategoryId :'***',
key: 'your api key' },
function (data) {
var nextPageToken = data.nextPageToken;
var prevPageToken = data.prevPageToken;
// Log Data
console.log(data);
$.each(data.items, function (i, item) {
// Get Output****
var output = getOutput(item);
// Display Results*****
$('#results').append(output);
});
var buttons = getButtons(prevPageToken, nextPageToken);
// Display Buttons
$('#buttons').append(buttons);
});
}
///////////////////////////////////////////////////////////////
// Next Page Function
function nextPage() {
var token = $('#next-button').data('token');
var q = $('#next-button').data('query');
// Clear Results
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API
$.get(
"https://www.googleapis.com/youtube/v3/search?maxResults=***", {
part: 'snippet, id',
q: '***********',
fs:1,
hd:1,
pageToken: token,
type: 'video',
videoCategoryId : '*****',
key: 'your api key' },
function (data) {
var nextPageToken = data.nextPageToken;
var prevPageToken = data.prevPageToken;
// Log Data
console.log(data);
$.each(data.items, function (i, item) {
// Get Output
var output = getOutput(item);
// Display Results
$('#results').append(output);
});
var buttons = getButtons(prevPageToken, nextPageToken);
// Display Buttons
$('#buttons').append(buttons);
});
}
// Prev Page Function
function prevPage() {
var token = $('#prev-button').data('token');
var q = $('#prev-button').data('query');
// Clear Results
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API
$.get(
"https://www.googleapis.com/youtube/v3/search?maxResults=***", {
part: 'snippet, id',
q: **********,
fs:1,
hd:1,
pageToken: token,
type: 'video',
videoCategoryId : '*****',
key: 'your api key' },
function (data) {
var nextPageToken = data.nextPageToken;
var prevPageToken = data.prevPageToken;
// Log Data
console.log(data);
$.each(data.items, function (i, item) {
// Get Output
var output = getOutput(item);
// Display Results
$('#results').append(output);
});
var buttons = getButtons(prevPageToken, nextPageToken);
// Display Buttons
$('#buttons').append(buttons);
});
}
// Build Output**********************************************
function getOutput(item) {
var videoId = item.id.videoId;
var title = item.snippet.title.substring(0, 33);
/*var description = item.snippet.description.substring(0, 20);*/
var thumb = item.snippet.thumbnails.high.url;
var channelTitle = item.snippet.channelTitle;
var videoDate = item.snippet.publishedAt;
// Build Output String**************************************
var output = '<li>' +
'<a target="mainVid" href="https://www.youtube.com/embed/' + videoId + '/?autoplay=1&modestbranding=1&rel=0"><img src="' + thumb + '"></a>' +
'<h3><a target="mainVid" href="https://www.youtube.com/embed/' + videoId + '/?autoplay=1&modestbranding=1&rel=0">' + title + '</a></h3>' +
'<p>' + '</p>' +
'</li>' +
'<div class="clearfix"></div>' +
'';
return output;
}
// Build the buttons
function getButtons(prevPageToken, nextPageToken) {
if (!prevPageToken) {
var btnoutput = '<div class="button-container">' + '<button id="next-button" class="btn btn-primary" data-token="' + nextPageToken + '" data-query="' + q + '"' +
'onclick="nextPage();">Page Suiv</button></div>';
} else {
var btnoutput = '<div class="button-container">' +
'<button id="prev-button" class="btn btn-primary" data-token="' + prevPageToken + '" data-query="' + q + '"' +
'onclick="prevPage();">Page Préc</button>' +
'<button id="next-button" class="btn btn-primary" data-token="' + nextPageToken + '" data-query="' + q + '"' +
'onclick="nextPage();">Page Suiv</button></div>';
}
return btnoutput;
}
I know I need a function on an event but I don't know which one and where to place it.
have a look at this post Play next youtube src when the other one is finished Here is explained that you will need to use the youtube iFrame API (shared earlier) to be able to access the player events. This post also mentions in the post How to detect when a youtube video finishes playing? Here is a working example shared from 2012.
I don't write Javascript or have ever written something with the youtube API so I cannot give you a working example. But I'm sure with these posts and API docs you can find the answer you are seeking.
ok hi everyone !!!
here the solution with fancy box : add data-fancybox="video" on link to open
and give some instructions :
$('[data-fancybox]').fancybox({
infobar: false,
buttons: false,
afterLoad: function (instance, current) {
if (instance.group.length > 1 && current.$content) {
current.$content.append('<a data-fancybox-next class="button-next" href="javascript:;">→</a><a data-fancybox-previous class="button-previous" href="javascript:;">←</a>');
}
current.$content.append('<a data-fancybox-close class="button-close" href="javascript:;">×</a>');
} });
});
work very fine !!!!
thank for your help ...
I'm trying to create a list of Youtube playlists and each list item to contain the playlist's videos as well.
Something like this (this would be a playlist section):
The issue I'm having is when calling the requestVideoPlaylist function inside the renderPlaylistSection I get undefined. However, if I call the requestVideoPlaylist with a given playlistId outside of the render... function the result gets returned correctly.
Please find my code on the following lines.
I've also made a reproduction on JSFiddle
// Retrieve the list of playlists
function requestPlaylists(channelId) {
playlistsContainer.html('');
var requestOptions = {
channelId: channelId,
part: 'snippet,contentDetails',
maxResults: 4
}
var request = gapi.client.youtube.playlists.list(requestOptions);
request.execute(function(response) {
var playlists = response.result.items;
if (playlists) {
$.each(playlists, function(index, item) {
renderPlaylistSection(playlistsContainer, item.id, item.snippet);
});
} else {
playlistsContainer.html('Sorry, you have no uploaded videos');
}
});
}
// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
var requestOptions = {
playlistId: playlistId,
part: 'snippet,contentDetails',
maxResults: 5
};
if (pageToken) {
requestOptions.pageToken = pageToken;
}
var request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(function(response) {
// Only show pagination buttons if there is a pagination token for the
// next or previous page of results.
nextPageToken = response.result.nextPageToken;
var nextVis = nextPageToken ? 'visible' : 'hidden';
$('.js-next-videos').css('visibility', nextVis);
prevPageToken = response.result.prevPageToken
var prevVis = prevPageToken ? 'visible' : 'hidden';
$('.js-prev-videos').css('visibility', prevVis);
var playlistItems = response.result.items;
if (playlistItems) {
$.each(playlistItems, function(index, item) {
if (this.snippet.thumbnails) {
renderVideoItem(item.snippet);
}
});
}
});
}
// Render playlist section
function renderPlaylistSection(container, playlistId, playlistSnippet) {
var title = playlistSnippet.title;
container.append(
'<div class="playlist"><h3>Playlist Title: ' + title + '</h3>' +
'<div class="row playlist-videos">' + requestVideoPlaylist(playlistId) + '</div></div>'
);
}
function renderVideoItem(videoSnippet) {
var title = videoSnippet.title;
var thumbnail = videoSnippet.thumbnails.medium.url;
return (
'<div class="thumb" style="overflow: hidden;">' +
'<img src="' + thumbnail + '">' +
'</div>'
);
}
I'm having a problem with retrieving related videos as thumbnails towards a specific video. In my code, I have the search->list set up correctly and returns the different titles and thumbnail URLs for the related videos. However, since search->list doesn't have parameter contentDetails or statistics, I found another question related to my exact same problem here and used a secondary call for getting videos->list since it supports those parameters to be able to retrieve the duration and view count. But the problem is that both values (vidDuration & viewCount) are not being passed anything and marked as undefined as the item is passed through it and halted. How can I make the item's duration and viewCount values based on search->list's item?
script.js:
function relatedVids(videoId)
{
debugger;
$.get( // get related videos related to videoId - relatedToVideoId
"https://www.googleapis.com/youtube/v3/search",
{
part: 'snippet',
maxResults: vidResults,
relatedToVideoId: videoId, // $.cookie("id"); from single-video.html
type: 'video',
key: 'XXXXXXXXX'
},
function(data)
{
$.each(data.items,
function(i, item)
{
console.log(item);
var vidTitle = item.snippet.title; // video title
//var videoId = item.snippet.resourceId.videoId; // video id
//var vidDuration = item.contentDetails.duration;
//var viewCount = item.statistics.viewCount;
var vidThumbUrl = item.snippet.thumbnails.default.url; // video thumbnail url
var extractVideoId = null; // var to extract video id string from vidThumbUrl
// check if vidThumbUrl is not null, empty string, or undefined
if(vidThumbUrl)
{
//console.log("vidThumbUrl: ", vidThumbUrl);
var split = vidThumbUrl.split("/"); // split string when '/' seen
extractVideoId = split[4]; // retrieve the fourth index on the fourth '/'
//console.log("extractVideoId: ", extractVideoId); // YE7VzlLtp-4
//console.log("split array: ", split);
}
else console.error("vidThumbUrl is either undefined or null or empty string.");
// if video title is longer than 25 characters, insert the three-dotted ellipse
if(vidTitle.length > 25)
{
var strNewVidTitle = vidTitle.substr(0, 25) + "...";
vidTitle = strNewVidTitle;
}
// search->list only takes snippet, so to get duration and view count; have to call this function that has the recognized param structure
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails, statistics',
id: extractVideoId, //item.snippet.resourceId.videoId,
key: 'XXXXXXXXX',
},
// return search->list item's duration and view count
function(item)
{
vidDuration = item.contentDetails.duration; // pass item's duration
return vidDuration;
},
function(item)
{
viewCount = item.statistics.viewCount; // pass item's view count
return viewCount;
}
);
try
{
var vidThumbnail = '<div class="video-thumbnail"><a class="thumb-link" href="single-video.html"><div class="video-overlay"><img src="imgs/video-play-button.png"/></div><img src="' + vidThumbUrl + '" alt="No Image Available." style="width:204px;height:128px"/></a><p><a class="thumb-link" href="single-video.html">' + vidTitle + '</a><br/>' + convert_time(vidDuration) + ' / Views: ' + viewCount + '</p></div>';
// print results
$('.thumb-related').append(vidThumbnail);
}
catch(err)
{
console.error(err.message); // log error but continue operation
}
}
);
}
);
}
single-video.html script:
$(document).ready(function()
{
var videoId;
$(function()
{
if($.cookie("title") != null && $.cookie("id") != null)
{
var data = '<div class="video"><iframe height="' + vidHeight + '" width="' + vidWidth + '" src=\"//www.youtube.com/embed/' + $.cookie("id") + '\"></iframe></div><div class="title">' + $.cookie("title") + '</div><div class="desc">' + $.cookie("desc") + '</div><div class="duration">Length: ' + $.cookie("dur") + '</div><div class="stats">View Count: ' + $.cookie("views") + '</div>';
$("#video-display").html(data);
$("#tab1").html($.cookie("desc"));
videoId = $.cookie("id");
//vidDuration = $.cookie("dur"); works but prints out the same value for each
//viewCount = $.cookie("views"); works but prints out the same value for each
debugger;
relatedVids(videoId); // called here
console.log("from single-vid.html globalPlaylistId: ", $.cookie("playlistId"));
// remove cookies after transferring it to this page for display
$.removeCookie("title");
$.removeCookie("id");
$.removeCookie("desc");
$.removeCookie("views");
$.removeCookie("dur");
$.removeCookie("tags");
$.removeCookie("playlistId");
}
});
});
You're referring the item in the search results.
When you issued a get request to videos, you will get a response of video contentDetails and statistics. Apparently, you didn't capture the returned response.
$.get(
"https://www.googleapis.com/youtube/v3/videos",
{
part: 'contentDetails, statistics',
id: videoId, //item.snippet.resourceId.videoId,
key: 'XXXXXXXXX',
},
function(videoItem)
{
vidDuration = videoItem.contentDetails.duration; // pass item's duration
viewCount = videoItem.statistics.viewCount; // pass item's view count
}
);
NOTE: You can pass a string of video IDs delimited by a comma to fetch multiple video contentDetails/statistics in one request.
So I'm working on this Zipline for my free code camp and am pretty much done, i'm just trying to implement a search. I have it working ok but have a couple of bugs.
What i'm doing for the search is that i'm creating a new array then i'm filtering it and comparing it to the text input of the user and if its equal then i will push that value onto a new array then display it on the screen.
is there a better way to do this? so that as the user types it is comparing with the list of arrays I have.
Thanks
Here is the jsfiddle http://jsfiddle.net/wtj7s6c6/2/
$(document).ready(function () {
var img, user, status, channel,
url = "https://api.twitch.tv/kraken/",
/* cb = '?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?',*/
cb = '?callback=?',
//create new array from filtered array
newArray = [],
userList = ["freecodecamp", "maximilian_dood", "UltraChenTV", "habathcx", "TeamSpooky", "Nuckledu", "medrybw"];
/*function updateLog(message) {
$("#log").html($("#log").html() + "<p>" + message + "</p>");
};*/
function addOnlineUser(image, username, status) {
$(".people")
.append('<li><img class="picture" src="' + image + '"/><span class="username">' + username + '</span><span class="isOnline">✔</span><p class="status">' + status + '</p></li>');
};
function addOfflineUser(image, username) {
if (image != null) $(".people")
.append('<li><img class="picture" src="' + image + '"/> <span class="username">' + username + '</span><span class="isOffline">!</span></li>');
else $(".people")
.append('<li><img class="picture emptypic"/><span class="username">' + username + '</span><span class="isOffline">!</span></li>');
};
function clickOnline() {
userList.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data) {
if (data.stream !== null) {
img = data.stream.channel.logo;
user = data.stream.channel.display_name;
status = data.stream.channel.status;
channel = data._links.channel;
addOnlineUser(img, user, status);
}
});
});
};
function clickOffline() {
userList.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data) {
if (data.stream === null) {
$.getJSON(url + 'users/' + name + cb)
.success(function (data2) {
img = data2.logo;
user = data2.display_name;
channel = data2._links.self;
addOfflineUser(img, user);
});
}
});
});
};
function clickSearchOff(array) {
array.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data) {
if (data.stream === null) {
$.getJSON(url + 'users/' + name + cb)
.success(function (data3) {
img = data3.logo;
user = data3.display_name;
channel = data3._links.self;
addOfflineUser(img, user);
});
}
});
});
};
function clickSearchOn(array) {
array.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data4) {
if (data4.stream !== null) {
img = data4.stream.channel.logo;
user = data4.stream.channel.display_name;
status = data4.stream.channel.status;
channel = data4._links.channel;
addOnlineUser(img, user, status);
}
});
});
};
$(".online").on('click', function () {
$(".people").empty();
clickOnline();
});
$(".offline").on('click', function () {
$(".people").empty();
clickOffline();
});
$(".all").on('click', function () {
$(".people").empty();
clickOnline();
clickOffline();
});
$(".all").click();
$('input[type="text"]').keyup(function () {
var searchTerm = $(this).val();
searchTerm = searchTerm.toLowerCase();
console.log("Search term:" + searchTerm);
//empty screen//
$(".people").empty();
var newArray = [];
for (var i = 0; i < userList.length; i++) {
if (userList[i].indexOf(searchTerm) != -1) {
newArray.push(userList[i]);
}
}
console.log("New array: " + newArray);
clickSearchOff(newArray);
clickSearchOn(newArray);
});
})
I suggest (as I may do) implement some kind of buffer on the keyup event in order to not always trigger the comparison, only after one or two seconds pass after the last keyup trigger:
var compareTimeout;
$('input[type="text"]').keyup(function () {
clearTimeout(compareTimeout);
compareTimeout = setTimeout(function () {
var searchTerm = $(this).val();
searchTerm = searchTerm.toLowerCase();
console.log("Search term:" + searchTerm);
//empty screen//
$(".people").empty();
var newArray = [];
for (var i = 0; i < userList.length; i++) {
if (userList[i].indexOf(searchTerm) != -1) {
newArray.push(userList[i]);
}
}
console.log("New array: " + newArray);
clickSearchOff(newArray);
clickSearchOn(newArray);
}, 2000);
});
This would make the function run only after 2 seconds after the last keyup event, and not every time the user types a letter in the input.
I'm trying to create a youtube social feed that includes the video, title, description, date, and view count. I've got everything to work except for the last one, view count. I've been able to get the view counts to show up but they are always out of order and I'm lost on how to make them match up to their respective videos. I used this video as an initial tutorial: [https://www.youtube.com/watch?v=jdqsiFw74Jk][1] It got me this far, but now I'm lost again. Here is my code via code pen: [http://codepen.io/ThatsMyJams/pen/EjZWex][2]
here is my html:
<div id="container">
<h2>Results:</h2>
<ul id="results"></ul>
</div>
and here is my javascript:
var yourApiKey = 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE';
var channelName = 'GoogleDevelopers';
var vidCount = 5;
var vidHeight = 275;
var vidWidth = 400;
$(document).ready(function(){
$.get(
"https://www.googleapis.com/youtube/v3/channels", {
part: 'contentDetails',
forUsername: channelName,
key: yourApiKey},
function(data){
$.each(data.items, function(i, item){
console.log(item);
playerID = item.contentDetails.relatedPlaylists.uploads;
getVids(playerID);
})
}
);
function getVids() {
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", {
part: 'snippet',
maxResults: vidCount,
playlistId: playerID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'},
function(data){
var output;
$.each(data.items, function(i, item){
console.log(item);
vidTitle = item.snippet.title;
videoID = item.snippet.resourceId.videoId;
vidDate = item.snippet.publishedAt;
vidDesc = item.snippet.description;
output = '<li>'+vidTitle+'<span class="date">'+vidDate+'</span><p class="description">'+vidDesc+'</p><iframe height="'+vidHeight+'" width ="'+vidWidth+'" src=\"//www.youtube.com/embed/'+videoID+'\"></iframe></li>';
//append to results list
$('#results').append(output);
getViews(videoID[i]);
})
}
);
}
function getViews() {
$.get(
"https://www.googleapis.com/youtube/v3/videos", {
part: 'statistics',
id: videoID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'},
function(data){
var output2;
$.each(data.items, function(i, item){
vidViews = item.statistics.viewCount;
output2 = '<span class="views">'+vidViews+'</span>'
//append to results list
$('#results li').each(function() {
$(this).append(output2);
});
})
}
);
}
});
I just want to get the viewCount for each video and insert it into the html much like I did for the title, date, etc. Any help would be greatly appreciated :)
Here's your modified code. this will display views at the end of each video:
var yourApiKey = 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE';
var channelName = 'GoogleDevelopers';
var vidCount = 5;
var vidHeight = 275;
var vidWidth = 400;
$(document).ready(function () {
$.get(
"https://www.googleapis.com/youtube/v3/channels", {
part: 'contentDetails',
forUsername: channelName,
key: yourApiKey
},
function (data) {
$.each(data.items, function (i, item) {
console.log(item);
playerID = item.contentDetails.relatedPlaylists.uploads;
getVids(playerID);
})
}
);
function getVids() {
$.get(
"https://www.googleapis.com/youtube/v3/playlistItems", {
part: 'snippet',
maxResults: vidCount,
playlistId: playerID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'
},
function (data) {
var output;
$.each(data.items, function (i, item) {
console.log(item);
vidTitle = item.snippet.title;
videoID = item.snippet.resourceId.videoId;
vidDate = item.snippet.publishedAt;
vidDesc = item.snippet.description;
var viewCountId = "viewCount" + i;
output = '<li>' + vidTitle + '<span class="date">' + vidDate + '</span><p class="description">' + vidDesc + '</p><iframe height="' + vidHeight + '" width ="' + vidWidth
+ '" src=\"//www.youtube.com/embed/' + videoID + '\"></iframe>"<span id="' + viewCountId + '"></span></li>';
//append to results list
$('#results').append(output);
getViews(viewCountId);
})
}
);
}
function getViews(viewCountId) {
$.get(
"https://www.googleapis.com/youtube/v3/videos", {
part: 'statistics',
id: videoID,
key: 'AIzaSyDpY9FHgp7EvnDr5mGrxWwKgUBtfM8l5PE'
},
function (data) {
var output2;
$.each(data.items, function (i, item) {
$('#'+viewCountId).text("views=" + item.statistics.viewCount);
})
}
);
}
});