I'm working on a Twitch.tv app as part of the FCC course. I'm near the finish line but I'm struggling to get the logo for each user. To explain, there's two different links for the API where I can get data: Streams & Channels.
If I use the streams link I can only get the logo if the user is online (which isn't really any good), where as with Channel I can get it regardless. To get what's streaming though, I really need to use the Stream link. The outcome then I guess, is I need to use both.
I've tried a variety of ways to make one call to streams and one to channels for the logo with a load of different results and I really can't figure it out. The latest way I've tried (below) gets me logos but not the correct stream/streamer data. I'm guessing the issue is how I'm nesting the calls within one another, but I can't figure out the proper way to do it.
Would appreciate any help anyone can give. Here's my CodePen where you can see the full code.
function apicall(streamer) {
$.getJSON('https://api.twitch.tv/kraken/streams/' + streamer, function(a) {
if (a.stream == null) {
stateclass = 'bg-danger';
game = 'Offline';
status = '';
url = '';
} else {
stateclass = 'bg-success';
game = a.stream.game + ': ';
status = a.stream.channel.status;
url = '<a target="_blank" href="' + a.stream.channel.url + '">';
}
who = streamer;
$.getJSON('https://api.twitch.tv/kraken/channels/' + streamer, function(b) {
logo = b.logo;
console.log(logo);
html += '<div class ="row ' + stateclass + '"><div class="col-xs-2"><img src="' + logo + '"></div><div class="col-xs-4">' + who + '</div>' + '<div class="col-xs-6">' + url + game + status + '</a></div></div>';
$(".options").html(html);
});
});
}
See jQuery.when().
function apicall(streamer) {
var streamsReq = $.getJSON('https://api.twitch.tv/kraken/streams/' + streamer);
var channelsReq = $.getJSON('https://api.twitch.tv/kraken/channels/' + streamer);
return $.when(streamsReq, channelsReq).done(function (streams, channels) {
var stateclass, link, html = '';
if (streams.stream && streams.stream.cannel) {
stateclass = 'bg-success';
link = '<a target="_blank" href="' + streams.stream.channel.url + '">' +
streams.stream.game + ': ' + streams.stream.channel.status + '</a>';
} else {
stateclass = 'bg-danger';
link = 'Offline';
}
html += '<div class ="row ' + stateclass + '">';
html += '<div class="col-xs-2"><img src="' + channels.logo + '"></div>';
html += '<div class="col-xs-4">' + streamer + '</div>';
html += '<div class="col-xs-6">' + link + '</div>';
html += '</div>';
$(".options").html(html);
}).fail(function () {
// add error handling
});
}
Related
I am finishing up a TwitchTV project but have been struggling to figure out how to append some code with jQuery. This code needs to check the API to see if a user is streaming or not, then, depending on if he or she is or not, append information to an already dynamic, jQuery produced html.
Take a look at my JavaScript code. Right now, under the “status” row, you will see each user has info. If the user is offline, I would simply like to have the html read “offline.” If the user is online, I would like it to read "Online: " plus a short description of what the channel is about (the stream information is stored in a variable called “stream,” and the short description is stored in a variable called “statusWhat”).
I’m sorry if that is a bit confusing. I think seeing the code will make things clear: https://codepen.io/JayDevelopment/pen/bMKrLK 1
$(function() {
var twitchers = [
"ESL_SC2",
"OgamingSC2",
"cretetion",
"storbeck",
"habathcx",
"RobotCaleb",
"noobs2ninjas"
];
//FREECODECAMP STREAM INFO AND API CALL
var url =
"https://api.twitch.tv/kraken/streams/freecodecamp?client_id=jjqkn1xu4g4rx7d3e1o5refrmw5bhd";
$.getJSON(url, function(data) {
if (data.stream === null) {
$("#fccStatus").html("OFFLINE");
} else {
$("#fccStatus").html("FreeCodeCamp is ONLINE");
}
$('#fccGame').html()
});
for (var i = 0; i < twitchers.length; i++) {
$.ajax({
type: "GET",
url: "https://api.twitch.tv/kraken/channels/" +
twitchers[i] +
"?client_id=jjqkn1xu4g4rx7d3e1o5refrmw5bhd",
success: function(dataFor) {
$.getJSON(
"https://api.twitch.tv/kraken/streams/" +
dataFor.name +
"?client_id=jjqkn1xu4g4rx7d3e1o5refrmw5bhd").done(function(data2) {
var name = dataFor.name;
var logo = dataFor.logo;
var statusWhat = dataFor.status;
var stream = data2.stream;
$('#info').append('<div class="row block">' +
'<div class="col-sm">' +
'<h1>' + '<img src=' + logo + '>' + '</h1>' +
'</div>' +
'<div class="col-sm">' +
'<h1>' + name + '</h1>' +
'</div>' +
'<div class="col-sm" id="change">' +
'<a href="https://www.twitch.tv/' + name + '"' + ' target="blank">' +
'<h1 id="status">' + stream + ': ' + statusWhat + '</h1>' +
'</a></div></div></div>')
/* if (stream === null) {
$("#status").append('OFFLINE');
} else {
$("#status").append('ONLINE: ' + statusWhat);
} */
}
);
},
error: function(error) {
$("#logo").append('<img src=' + '#' + '>' + "<br>");
$("#name").append('Invalid' + "<br>");
$('#status').append('Not found');
}
});
}
});
You can do it when you assign to the stream variable:
if (data2.stream) {
stream = data2.stream + " ONLINE: " + statusWhat;
} else {
stream = "OFFLINE";
}
I am new to javascript and I am creating a bookstore using the google API. I have a small issue which I couldn't figure out. In the below piece of code that I saw from example code of google api bookstore function, I am trying to create href for the title of the book and pass its selfLink to the destination page i.e book-description.html.
When I put alert(this.id) on onclick It works, but for a normal method get(this) it does not work. I do not need an alertbox I want to take the id of the link clicked in href and pass it to another html.
handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
var a = item.volumeInfo.title;
var selfL = item.selfLink;
//var b = a.link("book-description.html");
var image = item.volumeInfo.imageLinks.smallThumbnail;
document.getElementById("content").innerHTML += "</br>" + "</br>" + "<br>" + "<img src =" + "'" + image + "'" + " class='im'/>";
document.getElementById("content").innerHTML += "<h4 class='right'>" + "<a href = 'book-description.html'id = " + "'" + selfL + "'" +
"onclick ='get(this);'>" + a + "</a></h4>";
function get(e) {
var link = e.id;
localStorage.setItem("Link", link);
}
document.getElementById("content").innerHTML += "<h4 class='right'>" + "AUTHOR:" + item.volumeInfo.authors + "</h4>";
document.getElementById("content").innerHTML += "<h5 class='right'>" + "PUBLISHER:" + item.volumeInfo.publisher + "</h5>";
var rating = item.volumeInfo.averageRating;
if (rating) {
document.getElementById("content").innerHTML += "<h5 class='right' id='rating'>" + rating + "</h5>";
} else {
document.getElementById("content").innerHTML += "<h5 class = 'right' id ='rating'>Not Rated Yet</h5>";
}
//document.getElementById("content").innerHTML += "<br>" + "<br>" + "<br>" + item.volumeInfo.publisheddate;
}
}
There are a number of problems with your code, but specifically in answer to your question; your function get is scoped so it is only available within the function handleResponse. For it to be accessible from an onclick it must be in page scope.
Simply move this
function get(e) {
var link = e.id;
localStorage.setItem("Link", link);
}
Into the head of your page
In programming there is the concept of DRY (Don't repeat yourself). So store a reference to document.getElementById("content") and reuse that variable.
var content = document.getElementById("content");
content.innerHTML = ...
You're missing some spaces in your output html. This may work in some browsers, others will struggle
<a href = 'book-description.html'id=
Should have a space between the end of one attribute and the start of another
<a href='book-description.html' id=
And for heaven sake, sort out the concatenation of your strings. You dont need a + if its just a simple string
document.getElementById("content").innerHTML += "</br>" + "</br>";
should be
document.getElementById("content").innerHTML += "</br></br>";
When I look in the Firefox Network tab, it looks like the GET request goes through, but the page is not getting an HTML response. I am using jQuery to add a list item that contains a logo, a name, and a link where the user needs to be directed if either the logo or the name is clicked. The code is located here: http://codepen.io/veronikabenkeser/pen/PqxYvb
Relevant JS code:
if (logo === null) {
logo = '<img class = "brownI" src= "http://i358.photobucket.com/albums/oo27/picturesqueworlds/rss_circle_webtreatsetc_zpsfouqr1gj.png" >';
} else {
logo = '<img src="' + logo + '">';
}
if (stream !== null) {
streamingIcon = '<img class = "streamIcon" src= "http://i358.photobucket.com/albums/oo27/picturesqueworlds/button_green_play_zpsgnkih0jo.png" >';
item = '<li>' + '<a href="http://www.twitch.tv/' + streamer + '"' + '>' + logo + '</a>' + '<a href="http://www.twitch.tv/' + streamer + '"' + '>' + name + '</a>' + streamingIcon + '</li>';
} else {
item = '<li>' +
'<a href="http://www.twitch.tv/' + streamer + '"' + '>' + logo + '</a>' + '<a href="http://www.twitch.tv/' + streamer + '"' + '>' + name + '</a>' + '</li>';
}
$(".content ul").append(item);
You can use a delegated event handler since the link was appended.
Something like:
$(".content").on('click','a',function(){
var theSource = $(this).attr('href');
window.open(theSource , '_blank');
});
The reason the link doesn't work when you click on it is because the content is on a different domain from codepen.io and violates the SAMEORIGIN policy
Refused to display 'http://www.twitch.tv/freecodecamp' in a frame
because it set 'X-Frame-Options' to 'SAMEORIGIN'.
One workaround is to add target="_blank" to your href
Demo
Annoyingly, the FlickrAPI provides the title and description of a photo in two separate methods. I'm having trouble getting the description of an image from Flickr and was wondering if you could highlight the error in my script.
for (var i = 0; i < photos.photo.length; i++) {
var descPhoto = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key="+API_KEY+"&photo_id="+photos.photo[i].id+"&format=json&nojsoncallback=1";
var descArr = [];
$.getJSON(descPhoto, function(data) {
var value = data.photo.description._content;
descArr.push(value);
});
link = 'https://farm' + photos.photo[i].farm + '.static.flickr.com/' + photos.photo[i].server + '/' + photos.photo[i].id + '_' + photos.photo[i].secret + '_';
title = this._htmlEscape( photos.photo[i].title );
var lightbox = "lightbox";
listItems +=
'<li ' + 'class="' + liClassNoDots + '">' +
'<a href="' + link + self.options.imageSize + '.jpg" title="' + title + '" class="' + aClassNoDots + '" target="_blank" data-lightbox="' + lightbox + '">' +
<img alt="' + title + '" src="' + link + self.options.thumbnailSize +'.jpg"/>' +
'<div class="hover-box">' +
'<p>' + descArr[i] + '</p>' +
'<button class="box-button view">View larger</button>' +
'<button class="box-button request">Request</button>' +
'</div>';
'</a>' +
'</li>';
}
Getting the title is fine and I've checked by API string calls and they work in the address bar of my browser.
I've used console.log() and the array is printed out correctly and I'm getting the descriptions. However, in each <p> tag the script is returning undefined in each instance.
However, if I run the script through the debugger the parapgraph tags are populated with the descriptions. Can somebody help?!
i think the problem is in following code::
..
$.getJSON(description, function(desc) {
value = desc.photo[ i ].description._content;
});
the service url returns photo object whereas you are using photo array, change to:
..
$.getJSON(description, function(desc) {
value = desc.photo.description._content;
console.log( value );
});
I'm not able to load the images using Google Feed API, I'm using the mediaGroup to load images.
This is the javascript code I've written for fetching the feed
<script type="text/javascript">
google.load("feeds", "1");
function initialize()
{
var feed = new google.feeds.Feed("http://techzei.com/feed");
feed.setNumEntries(14);
feed.load(function (result) {
if (!result.error)
{
result.feed.entries.forEach(function(entry)
{
$('#feed').append('<div class="card">' + entry.title + '<p>' + entry.contentSnippet + '</p><br><p>'+entry.publishedDate+'"<img src="'+ entry.mediaGroups+'"/></div>');
});
}
});
}
google.setOnLoadCallback(initialize);
The html
<article id="feed"></article>
All the images I get right now are "undefined". Should I be doing something else? The Google Feed API dev didn't throw much light on this
That feed doesn't seem to have any mediaGroup entries, that is the reason you get undefined in your result, but you can extract the images from the entry.content using jQuery.
Puts image urls to an array and shows first found image (or none):
var content = document.createElement("content");
content.innerHTML = entry.content;
var images = $(content).find('img').map(function(){
return $(this).attr('src')
}).get();
$('#feed').append('<div class="card"><a href="' + entry.link + '">' +
entry.title + '</a><p>' + entry.contentSnippet + '</p><br><p>'+
entry.publishedDate +'</p>' +
(images.length == 0 ? '' :'<img src="'+ images[0] +'"/>') + '</div>');
Shows all images, by appending the img tags to a variable:
var content = document.createElement("content");
content.innerHTML = entry.content;
var images = "";
$(content).find('img').each(function() {
images += this.outerHTML;
});
$('#feed').append('<div class="card"><a href="' + entry.link + '">' +
entry.title + '</a><p>' + entry.contentSnippet + '</p><br><p>' +
entry.publishedDate + '</p>' + images +'</div>');