Retrieve Flickr photo title AND description using jQuery - javascript

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 );
});

Related

Issues with fancybox .iframe

I have issues when trying to display a YouTube file using the fancybox iframe. It displays a small frame with a scroller. I have attached a link to the code. I am using the YouTube API to extract the content.
https://jsfiddle.net/Le98zx1s/
jQuery displaying to html
function getOutput (item)
{
var videoId = item.id.videoId;
var title = item.snippet.title;
var description = item.snippet.description;
var thumb = item.snippet.thumbnails.high.url;
var channelTitle = item.snippet.channelTitle;
var videoDate = item.snippet.publishedAt;
var output = '<li>' +
'<div class = "list-left">' +
'<img src="' + thumb + '">' +
'</div>' +
'<div class ="list-right">' +
'<h3><a class="fancybox fancybox.iframe"' + 'href="http://youtube.com/embed/' + videoId + '">' + title + '</a></h3>' +
'<small>By <span class="cTitle">' + channelTitle + '</span> on ' + videoDate + '</small>' +
'<p>' + description+'</p>' +
'</div>' +
'</li>' +
'<div class ="clearfix"></div>' + ' ';
return output;
}

Left-clicking links doesn't work in Codepen, but 'Open in New Tab' does

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

How to Load Images from a RSS Feed using Google Feed API?

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>');

Creating dynamic html with json taking too much time

I am working on preparing some dynamic html with jquery and json object. but the problem is that when my json object has around 1500 rows it takes ages to load.
is there a way to load the thing faster.
Some code.
$(jQuery.each(jsonObject.AvailableColumns, function (i, l) {
if (type == "manual") {
innerList1 += '<li newText="" valueFormat="' + l.ValueFormat + '" scaleID="' + l.ScaleID + '" scaleType="' + l.ScaleType + '" hasWeights="' + l.HasWeights + '" customColumnType="' + l.CustomColumnType + '" class="" id="li_' + controlId + '"><span id="span_' + controlId + '" title = "' + l.QuestionText + '">' + getDisplayString(l.QuestionText) + '</span><a class="actionLeft"></a></li>';
}
else if (type = "exportall") {
innerList2 += CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat);
}
controlId++;
}));
$("#itemList").html(innerlist1);
EDIT : createliwithspan method
function CreateLiWithSpans(id, html, isLeft, isAddAll, scaleID, scaleType, hasWeights, customColumnType, valueFormat, newText) {
var ancClass = isLeft ? 'actionRight' : 'actionLeft';
var liObject = "";
if (newText == null) {
newText = "";
}
if (isLeft) {
liObject = '<li newtext="' + newText + '" valueFormat="' + valueFormat + '" scaleID="' + scaleID + '" scaleType="' + scaleType + '" hasWeights="' + hasWeights + '" customColumnType="' + customColumnType + '" class="" id="' + id + '"><span id="span_' + id + '" title = "' + html + '">' + getDisplayString(html) + '</span><span style="margin:0 10px 0 20px;pagging:0"><input title = "' + (newText == "" ? html : newText) + '" type="text" id="' + id + 'displayText" value="' + (newText == "" ? html : newText) + '" /><span style="color:Red; width:100%;" id="' + id + 'displayTextError"></span></span><span style="float:left">' + CreateDropDown('ddl_' + id, valueFormat, hasWeights) + '</span><a class="' + ancClass + '"></a></li>';
}
else {
liObject = '<li newtext="' + newText + '" valueFormat="' + valueFormat + '" scaleID="' + scaleID + '" scaleType="' + scaleType + '" hasWeights="' + hasWeights + '" customColumnType="' + customColumnType + '" class="" id="' + id + '"><span id="span_' + id + '" title = "' + html + '">' + getDisplayString(html) + '</span><a class="' + ancClass + '"></a></li>';
}
return liObject;
}
You can use for loop instead of jQuery.each, that will be faster. Store the itemCount before the loop, and use that:
itemCount = jsonData.items.length;
for(var i = 0; i < itemCount; i++ ) {
...
You can also use use an array instead of string concatenation, like so:
var innerList = [];
... // inside the loop
innerList.push(CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat));
... // after the loop
$("#itemList").html(innerList.join(''));
This will be faster in IE, I'm not sure about other js engines.
These two methods will not make a significant difference, so you should try implementing a client side pagination from json. (Not by hiding and showing divs, by rendering only visible page into the DOM).
Instead of waiting for the loop to end to append your data, why not actively append the data as you process it. This will allow the user to get immediate feedback instead of waiting for the whole thing to process. Other than this, I'd stick with my original comment to page the data.
$(jQuery.each(jsonObject.AvailableColumns, function (i, l) {
if (type == "manual") {
$("#itemList").append( '<li newText="" valueFormat="' + l.ValueFormat + '" scaleID="' + l.ScaleID + '" scaleType="' + l.ScaleType + '" hasWeights="' + l.HasWeights + '" customColumnType="' + l.CustomColumnType + '" class="" id="li_' + controlId + '"><span id="span_' + controlId + '" title = "' + l.QuestionText + '">' + getDisplayString(l.QuestionText) + '</span><a class="actionLeft"></a></li>');
}
else if (type = "exportall") {
$("#itemList2").append(CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat));
}
controlId++;
}));
Try replacing jQuery.each with a plain old for...in loop. Using jQuery.each adds overhead that you don't need.
Don't concatenate strings inside your loop. Instead, .push them onto an array variable and use .join('') to build the string all at once at the end.
You may need to eliminate CreateLiWithSpans as a separate function in order to fully implement (2).
Changing from using jQuery.each to a standard javascript for loop should speed it up a bit. Make sure that you save the length to a variable like this though:
for(var i = 0, len = jsonObject.AvailableColumns.length; i < len; i++){
var l = jsonObject.AvailableColumns[i];
// Continue with rest of code
}
Probably won't be a huge increase but every little helps.
Also try lowering the number of function calls you make as these have added overhead (not usually an issue, but in a large loop it can help). Unless the code is shared between functions try doing it inline and see how much that speeds it up.

Filter JQuery list with URL

I need to modify some code already in place. There's a block of code that filters a JQuery list using the URL to populate the search input.
E.g.
http://***/store/mobile/page/productList.page?search=football
Automatically enters "football" in the search bar.
Now I'd need to filter the list, without using the search bar.
So lets say my URL would look something like this :
http://***/store/mobile/page/productList.page?football
This would filter the list with football without using the search bar.
Here's the code I need to change. Please tell me if my question is unclear.
$('div[data-url*="productList"]').live("pageshow", function() {
filterValue = getParameterByName("search", location.search);
if (filterValue) {
$('input[data-type="search"]').val(filterValue);
}
refreshList();
});
and:
$.each(catalog.products,
function(index, value) {
if ((!filterValue )
|| value.name.toUpperCase().indexOf(filterValue.toUpperCase()) != -1
|| value.brand.toUpperCase().indexOf(filterValue.toUpperCase()) != -1)
{
items.push('<li id="' + index + '">' +
'<a data-identity="productId" href="./details.page?productId=' + index + '" >' +
'<img class="ui-li-thumb" src="' + value.thumbnail + '"/>' +
'<p>' + value.brand + '</p>' +
'<h3>' + value.name + '</h3>' +
'<span class="ui-li-count">' + value.price + ' $</span></li>') +
'</a>';
}
});
if there will always be only 1 parameter after ? than you could simply get it from page location in javascript, e.g.
var url = document.location;
var params = url.split("?");
filterValue = params[params.length-1]
if (filterValue) {
$('input[data-type="search"]').val(filterValue);
}
refreshList();
example: http://jsfiddle.net/yPgPc/

Categories

Resources