JSON div style background image link doesn't have slashes? - javascript

I am creating a list of thumbnails with JSON and I have problem with this line of code:
videoHTML += '<div class="user-background" style="background-image: url("' + video.channel.video_banner + '");">';
I can see div element and everything in it except background-image link doesn't have slashes.
This is the code that I see in debugger elements:
<div class="user-background" style="background-image: url(" https:="" static-cdn.jtvnw.net="" jtv_user_pictures="" esl_csgo-channel_offline_image-c9f885982daa1c83-1920x1080.png");"=""><div class="user-background" style="background-image: url(" https:="" static-cdn.jtvnw.net="" jtv_user_pictures="" esl_csgo-channel_offline_image-c9f885982daa1c83-1920x1080.png");"=""><img class="user-logo" src="https://static-cdn.jtvnw.net/jtv_user_pictures/esl_csgo-profile_image-546a0c1883798a41-300x300.jpeg" alt="user image"><p class="user-name">ESL_CSGO</p></div><img class="video-image" src="http://static-cdn.jtvnw.net/previews-ttv/live_user_esl_csgo-320x180.jpg"><h1 class="game-name">Counter-Strike: Global Offensive</h1><br><i></i><span class="views-number">41304</span><p class="short-date-format date0">2012-06-11T13:36:21Z</p></div>
Can You help me by explaining what I am doing wrong with quotation marks?
(I believe that they are causing this problem.)
Here is the code for you to understand it better:
$(document).ready(function(){
$.getJSON( "https://api.twitch.tv/kraken/streams", function( data ) {
var items = [];
var videoHTML ='<ul>';
//Get data and create video grid
$.each(data.streams, function(i, video){
if(i < 9) { //get only first 9 data
var videoDate = $.format.date(video.channel.created_at, "MMM dd yyyy");
videoHTML += '<li class="video-stream ' + video.channel.language + '">';
videoHTML += '<div class="user-background" style="background-image: url("' + video.channel.video_banner + '");">';
videoHTML += '<img class="user-logo" src="' + video.channel.logo + '" alt="user image">';
videoHTML += '<p class="user-name">' + video.channel.display_name + '</p>';
videoHTML += '</div>';
videoHTML += '<a href="#" onclick="popup(\'' + video.channel.name + '\')">';
videoHTML += '<img class="video-image" src="' + video.preview.medium + '"></a>';
videoHTML += '<h1 class="game-name">' + video.game + '</h1><br/>';
videoHTML += '<i></i>';
videoHTML += '<span class="views-number">' + video.viewers + '</span>';
videoHTML += '<p class="short-date-format date' + i + '">' + videoDate + '</p>';
videoHTML += '</li>';
// var userId = "'#userBackground" + i +"'";
alert(userId);
// console.log(video._id);
// console.log(data.streams[i].game);
// console.log(data.streams[i]._links.self);
// console.log(data.streams[i].preview.medium);
} else {
return false;
}
});
videoHTML += '</ul>';
videoHTML += '<div class="clearfix"></div>';
$('#placeholder').html(videoHTML);
}); //getJson
}); //end ready

UPDATE I found your problem. You have to change the " around the style to \'. Like so:
videoHTML += '<div class="user-background" style=\'background-image: url("' + $.trim(video.channel.video_banner) + '");\'>';
See it working with your corrected code here.
I rewrote the whole thing and showed you a few fundamental features of jQuery. Keep in mind, it's not necessarily better, per say, but perhaps more effecient and easier to follow. Within JS alone, there's a dozen different ways to write this. Within jQuery, a million. I could easily have made this a lot shorter, and if for myself, I would do it MUCH different. However, I hope this shows you some of the different uses of jQuery, as well as understanding on why variable control can be so important. I actually didn't see charlietfl's code working. The background still doesn't show up. However, as you'll see in my example, not only did I narrow down to the "problem", I also made it work, but not with anything fancy. I just used basic jQuery!
Keep in mind, jQuery has a well written, easy to follow API. Everything I use here is easily find-able there!
CodeSnippet
function buildList(data) {
if (data) {
var videoHTML = $('<ul />'),
clearFix = $('<div />', { 'class': '' }),
items = [];
$.each(data.streams, function(i, video){
if(i < 9) {
var videoDate = video.channel.created_at, // $.format.date(video.channel.created_at, "MMM dd yyyy"),
li = $('<li />', { 'class': 'video-stream' }).addClass(video.channel.language).appendTo(videoHTML),
div = $('<div />', { 'class': 'user-background' }).appendTo(li),
imgLogo = $('<img />', { alt: 'user image', 'class': 'user-logo' }).attr('src', video.channel.logo).appendTo(div),
pUser = $('<p />', { 'class': 'user-name', html: video.channel.display_name }).appendTo(div),
a = $('<a />', { href: 'javascript:void 0' }).data('vidName', video.channel.name).appendTo(li),
imgPrev = $('<img />', { 'class': 'video-image' }).attr('src', video.preview.medium).appendTo(a),
h1 = $('<h1 />', { 'class': 'game-name' }).appendTo(li),
br = $('<br />').appendTo(li),
ita = $('<i />').appendTo(li),
span = $('<span />', { 'class': 'views-number' }).html(video.viewers).appendTo(li),
pDate = $('<p />', { 'class': 'short-date-format' }).addClass('date' + i).appendTo(li);
// And now we can zero in on your issue with ez, by moveing that one thing here
try {
console.log(video.channel.video_banner);
div.css('backgroundImage', 'url("' + video.channel.video_banner + '")');
}
catch(err) { console.log(err); }
}
else return false;
});
$('#placeholder').append(videoHTML, clearFix);
}
}
$(function() { // jQuery shorthand for $(document).ready(function(){
$.getJSON("https://api.twitch.tv/kraken/streams", buildList);
// the following uses our STATIC element to assign click event to our DYNAMICALLY added anchors
$('#placeholder').on('click', '.video-stream a', function(e) { popup($(this).data('vidName')); });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="placeholder"></div>
jsFiddle for playing!

Related

RSS feed displaying NaN xml jquery

I am coding a simple RSS feed using jquery and a feed from wired. Everything is working great, but for some reason the result is including a NaN after the description. I cannot figure out what it is trying to pull, and since it is not wrapped in any tags, it follows a paragraph as such:
<p></p> NaN </div>
I cannot use css to hide it, and i dont want to limit the description length as some are longer than others and setting an arbitrary character limit may allow it to display anyways on shorter descriptions.
xml feed: http://www.wired.com/category/business/feed/
script:
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
FeedUrl: "http://www.wired.com/category/business/feed/",
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
TitleLinkTarget: "_blank",
}, opt);
var id = $(this).attr("id");
var i;
$("#" + id).empty().append('<img src="loader.gif" />');
$.ajax({
url: "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=" + def.MaxCount + "&output=json&q=" + encodeURIComponent(def.FeedUrl) + "&hl=en&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
var s = "";
$.each(data.responseData.feed.entries, function (e, item) {
s += '<li><div class="itemTitle"><a href="' + item.link + '" target="' + def.TitleLinkTarget + '" >' + item.title + "</a></div>";
if (def.ShowPubDate) {
i = new Date(item.publishedDate);
s += '<div class="itemDate">' + i.toLocaleDateString() + "</div>";
}
if (def.ShowDesc) {
if (def.DescCharacterLimit > 0 && item.content.length > def.DescCharacterLimit) {
var StringStartAfterImage = item.content.indexOf('>',item.content.indexOf('< img')) + 1;
s += '<div class="itemContent">' + item.content.substr(0, def.DescCharacterLimit + StringStartAfterImage) + "..";
}
else {
s += '<div class="itemContent">' + item.content;
}
s += + "</div>";
}
});
$("#" + id).append('<ul class="feedEkList">' + s + "</ul>");
}
});
};
})(jQuery);
$(document).ready(function() {
$('#home-news').FeedEk({
FeedUrl: 'http://www.wired.com/category/business/feed/',
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
});
});
html:
<div class="newsCenter">
<div class="news">
<div id="home-news"> </div>
</div>
</div>
any help is much appreciated! Thank you!
i solved this by removing code after the else statement and closing the div in the else statement, i do not need the data that is not generating so this solution works for me.

Make List Items Clickable in JavaScript

I am developing an Android app using Phonegap. In this app I have integrated Facebook login module. After user gets login into app, he/she can see friend list of his/her. I have done till this. What I have to do is, on clicking the particular friend name, that friend name should be added to another list. But my problem is this friend list is not clickable. How to make dynamic list clickable?Below is my code. What am I missing?
xyz.html
<div class="section">
<h1>Get user's friends</h1>
<div id="user-friends"></div>
<div class="button button-requires-connect" onclick="getUserFriends();hideButton(this);" />Get your friends</div>
<div class="info-requires-connect">You need to login before you can use this functionality.</div>
</div>
pqr.js
function getUserFriends() {
var markup = '<div class="data-header">Friends</div>';
for (var i=0; i < friendsInfo.length && i < 25; i++) {
var profilePictureUrl = '';
if (friendsInfo[i].picture.data) {
profilePictureUrl = friendsInfo[i].picture.data.url;
} else {
profilePictureUrl = friendsInfo[i].picture;
}
markup = markup + '<img src="' + profilePictureUrl + '">' + friendsInfo[i].name + '<br />';
}
document.getElementById('user-friends').innerHTML = markup;
}
You can wrap your 'friend-markup' for example in <li>s like that:
markup = markup + '<li><img src="' + profilePictureUrl + '">' + friendsInfo[i].name + '</li>'
and then use jQuery to bind clicks to the <li>s:
$('#user-friends').on('click', 'li', function() {
... do something
});
function getUserFriends() {
var markup = '<div class="data-header">Friends</div>';
for (var i=0; i < friendsInfo.length && i < 25; i++) {
var profilePictureUrl = '';
if (friendsInfo[i].picture.data) {
profilePictureUrl = friendsInfo[i].picture.data.url;
} else {
profilePictureUrl = friendsInfo[i].picture;
}
var clickableName = '<a href="" onclick="handleClick(this); return false;">'
+ friendsInfo[i].name + '</a>';
markup = markup + '<img src="' + profilePictureUrl + '">' + clickableName + '<br />';
}
document.getElementById('user-friends').innerHTML = markup;
}
Then write handler function
function handleClick(element/*which friend was clicked*/)
{
//do something with your friend
}
Or you can use jQuery to bind click event on element as #MiRaIT told

Fading in appended elements one at a time

I have an array with IDs and I am loading elements with these IDs from another page.
$.each(idArr, function() {
var divline = '<div class="line" id="' + this + '">';
var url = 'allitems.php #' + this + ' div';
$('#the-list').append($(divline).load(url).hide().fadeIn());
});
It works fine but I would like the loaded elements to fade in one at a time, or at least not all att once. I cannot figure out how to use .delay with my code. Or is there maybe another way?
Thank you :)
$.each(idArr, function(i,el) {
var divline = $('<div />', {'class':'line', id: el}),
url = 'allitems.php #' + el + ' div';
$('#the-list').append(divline.load(url).hide().delay(i*1000).fadeIn());
});
A simple solution is to use setTimeout :
$.each(idArr, function(i) {
var divline = '<div class="line" id="' + this + '">';
var url = 'allitems.php #' + this + ' div';
setTimeout(function(){
$('#the-list').append($(divline).load(url).hide().fadeIn());
}, i*1000);
});
Try this way:
$(".elements").each(function(i, e) { $(e).delay(i * 400).fadeIn(400); });

Using HTML template String and Regex'ing dynamic values. Stuck on regex

I am getting stuck. Perhaps there is a better way with the regex (like to hear your thoughts).
AS a ONE-OFF the following works if I am just subbing in one thing, say -link-.
var testHtmlStr = '<tr>' +
'<td class="eve"><div class="pad" style="overflow:hidden;">' +
'<img height="50" width="80" title="{%desc%}" alt="{%desc%}" src="{%image%}">' +
'<div class="sum">{%name%}</div>' +
'{%star_rating_html%}' +
'{%eventC%}' +
'<span class="block">{%evenC%}</span>' +
'</div></td>' +
'<td class="mor"><div class="pad"><a class="mor" href="{%link%}">{%linkName%}</a>' +
'</div></td>' +
'</tr>';
var ss = 'link';
var syntax = new RegExp('(^|.|\r|\n)(\{%\s*(' + ss + ')\s*%\})',"gi");
alert(testHtmlStr.replace(syntax, '$1TESTESTESTESTS'));
The following is my code and it DOES NOT WORK. I can't figure out why. Same regex, same html template pattern. Also, my .each reiterates thru the string, but it seems after every reiteration the string returns to its unmodified state. Basically, whatever is the html string like so {%somehashkey%}, I want it to be replaced with the corresponding hash value.
I figured my code would work, can't figure out what is wrong. Something is out of wack, I know that. I can't hunt it down. Your thoughts?
(function($){
var testHTML2 = '<tr>' +
'<td class="eve"><div class="pad" style="overflow:hidden;">' +
'<img height="50" width="80" title="{%desc%}" alt="{%desc%}" src="{%image%}">' +
'<div class="sum">{%name%}</div>' +
'{%rating%}' +
'{%eventC%}' +
'<span class="block">{%evenC%}</span>' +
'</div></td>' +
'<td class="mor"><div class="pad"><a class="mor" href="{%link%}">{%linkName%}</a>' +
'</div></td>' +
'</tr>';
var type = "yahoo";
var disp = {};
disp.eventC = '5';
disp.rating = "<div>rating here</div>";
switch (type) {
case 'yahoo':
disp.link = 'http://www.yahoo.com';
disp.image = 'SOMe IMAGE' ;
disp.name = "VENICE BEACH";
disp.desc = 'MORE INFO ';
disp.linkName = 'YAHOO';
break;
default:
disp.link = 'http://www.google.com';
disp.image = 'Some IMAGE';
disp.name = "BABY BABY";
disp.desc = 'MORE INFO YOYOYO';
disp.linkName = 'GOOGLE';
}
$.each( disp, function(t, num){
var syntax = new RegExp('(^|.|\r|\n)(\{%\s*(' + t + ')\s*%\})',"gi");
testHTML2.replace(syntax, num)
});
alert(testHTML2);
})(jQuery);
You are not assigning new value to testHTML2.
testHTML2 = testHTML2.replace(syntax, num)

Elements added with appendTo() not immediately available

I'm having a problem with elements added with appendTo() not being immediately available in the DOM.
First, I'm reading some data from a JSON file and then appending some html to a div. Then I'm calling a random shuffler plugin to show one of the added divs at a time.
jsonUrl = "js/performers.json";
$.getJSON(jsonUrl, function(json) {
$.each(json.performers, function(i, performer) {
var html = '<div class="performer_mini">';
html += '<img src="' + performer.thumbnail + '" alt="' + performer.name + '" /><br />';
html += performer.name + '<br /></div>';
$(html).appendTo("div#performer_spotlight");
});
});
$("#performer_spotlight").randomShuffler(".performer_mini", 3000, 3000, 9000);
The random shuffler does the following:
(function($) {
$.fn.randomShuffler = function(shuffledElements, fadeInTime, fadeOutTime, timeout) {
fadeInTime = fadeInTime || 3000;
fadeOutTime = fadeOutTime || 3000;
timeout = timeout || 9000;
$(shuffledElements).hide();
var $old_element;
var $new_element;
var old_index = 0;
var new_index = 0;
function shuffleElement() {
$old_element = $new_element;
old_index = new_index;
while ($(shuffledElements).length > 0 && old_index == new_index) { // don't display the same element twice in a row
new_index = Math.floor(Math.random()*$(shuffledElements).length);
}
$new_element = $(shuffledElements + ":eq(" + new_index + ")");
if ($old_element != undefined) {
$old_element.fadeOut(fadeOutTime, function() {
$new_element.fadeIn(fadeInTime);
});
} else {
$new_element.fadeIn(fadeInTime);
}
setTimeout(shuffleElement, timeout);
}
$(this).show();
shuffleElement();
}
})(jQuery);
The first time the shuffleElement() function is called $(shuffledElements).length equals 0, so no element is displayed. On the next call to shuffleElement(), the elements added with appendTo() are available and one is selected at random as expected. Everything works correctly after that.
Is there some way to refresh the DOM or make these elements available to jQuery immediately after I add them with appendTo()? Any other suggestions for how to accomplish this?
When exactly do you call randomShuffler? You call this function after the AJAX-request succeeds? I have always believed that the element added by appendTo available immediately after the addition.
This code works very well for me:
<script language="javascript">
var test = "<div class=\"test\">1</div>";
$(test).appendTo("div#performer_spotlight");
$("div.test").html("<b>Hello</b>");
</script>
Yes, like #MeF Convi says you need to call the plugin only after the getJSON finishes:
$.getJSON(jsonUrl, function(json) {
$.each(json.performers, function(i, performer) {
var html = '<div class="performer_mini">';
html += '<img src="' + performer.thumbnail + '" alt="' + performer.name + '" /><br />';
html += performer.name + '<br /></div>';
$(html).appendTo("div#performer_spotlight");
});
$("#performer_spotlight").randomShuffler(".performer_mini", 3000, 3000, 9000);
});

Categories

Resources