I'm trying to display RSS using the following JS code. But when I execute this, both the RSS feeds are changed to same content (the one that is execute later) and all the feeds are appended to the same div. I think rss = this is causing the problem. Any workaround ?
HTML:
<div id="rss1" class="rss-widget">
<ul></ul>
</div>
<div id="rss2" class="rss-widget">
<ul></ul>
</div>
<div id="rss3" class="rss-widget">
<ul></ul>
</div>
JS:
function RSSWidget(id, url) {
rss = this;
rss.FEED_URL = url;
rss.JSON = new Array();
rss.widgetHolder = $('#' + id + ' ul ');
rss.storiesLimit = 15;
rss.renderBlogItem = function (object) {
var item = '<li class="blog-item">';
item += '<a href="' + object.link + '">';
item += '<div class="blog-item-title">' + object.title + '</div>';
item += '<div class="blog-item-author">' + object.author + '</div>';
// item += '<div class="blog-item-content">' + object.content + '</div>';
item += '</a>'
item += '</li>';
rss.widgetHolder.append(item);
}
return $.ajax({
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(rss.FEED_URL),
dataType: 'json',
success: function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
rss.JSON.push({ //add objects to the array
title: e.title,
author: e.author,
content: e.content || "",
link: e.link
});
});
if (rss.storiesLimit > rss.JSON.length)
rss.storiesLimit = rss.JSON.length;
for (var i = 0; i < rss.storiesLimit; i++) {
rss.renderBlogItem(rss.JSON[i]);
}
$('#' + id + ' li ').each(function () {
var delay = ($(this).index() / rss.storiesLimit) + 's';
$(this).css({
webkitAnimationDelay: delay,
mozAnimationDelay: delay,
animationDelay: delay
});
});
}
}
});
}
$.when(RSSWidget('rss1', "http://rss.cnn.com/rss/money_markets.rss"))
.then(function () {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
.then(function () {
RSSWidget('rss3', "http://finance.yahoo.com/rss/topfinstories")
});
.then(RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews"));
is immediately invoked. Try calling second RSSWidget within .then() anonymous function
.then(function() {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
Also, no promise is returned from RSSWidget; you can include return $.ajax(/* settings */) from RSSWidget to return the jQuery promise object from RSSWidget.
Related
I added a delete function to a todo list app that i built. The delete function works; however, when I refresh the page all the items that i deleted come back. How can I remove the items permanently from the database?
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
//////this section works
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
///////this does not want to remove the item from the database
$.destroy("/tasks/" + itemId, {
_method: "destroy",
task: {
done: doneValue
}
});
});
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
// still dont understand this
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
var li_to_delete = $('.todo-list li.completed');
$.ajax({
type: 'DELETE',
url: "/tasks" + li_to_delete,
success: function(){
li_to_delete.remove();
}
});
});
});
i changed the code but im not sure how to properly extract the url.
on line 30 i am facing an issue with $.each(data.menu, function (). I am being told by the console that "data is null". can anyone explain whats going on? thanks
function getFoodMenuData () {
var url = 'http://localhost:8888/Tom_Carp_Final_Project/Chorizios/foodMenu.json';
$.getJSON(url, function (data) {
window.localStorage.setItem('choriziosMenu333', JSON.stringify(data));
});
}
function showFoodMenuData () {
var data = JSON.parse(window.localStorage.getItem('choriziosMenu333'));
var images = "";
$.each(data.menu, function () {
images += '<li class="list-group-item"><img style="width: 100%;" src= "' + this.url + '"></li>';
images += '<li class="list-group-item">' + this.description + '</li>';
});
$('#foodMenu').append(images);
}
showFoodMenuData();
You have to call getFoodMenuData(), and then inside the callback for the asynchronous $.getJSON, call showFoodMenuData().
function getFoodMenuData() {
var url = 'http://localhost:8888/Tom_Carp_Final_Project/Chorizios/foodMenu.json';
$.getJSON(url, function(data) {
window.localStorage.setItem('choriziosMenu333', JSON.stringify(data));
showFoodMenuData(); // <--- call this inside the callback
});
}
function showFoodMenuData() {
var data = JSON.parse(window.localStorage.getItem('choriziosMenu333'));
var images = "";
$.each(data.menu, function() {
images += '<li class="list-group-item"><img style="width: 100%;" src= "' + this.url + '"></li>';
images += '<li class="list-group-item">' + this.description + '</li>';
});
$('#foodMenu').append(images);
}
getFoodMenuData(); // <--- call this first
I wouldn't use $ for the loop. I am not sure of the structure of the data you are receiving but you will probably need a nested loop to get all the data either way this should do the trick.
As a point the for in loop works great for objects. One reason is that the iterator is the key in the object. In this example if you console.log( ii ) inside the second loop you will see either name or url.
HTML
<ul></ul>
Javascript
var menu = {
item1 : {
name : "Food1",
url : "https://s-media-cache-ak0.pinimg.com/736x/79/82/de/7982dec0cc2537665a5395ac18c2accb.jpg"
},
item2 : {
name : "Food2",
url : "http://i.huffpost.com/gen/1040796/images/o-CANADIAN-FOODS-facebook.jpg"
}
};
$( document ).ready( function () {
for ( var i in menu ) {
for ( var ii in menu[ i ] ) {
var elem = ii === "name" ? "<p>" + menu[ i ][ ii ] + "</p>" : "<img src=" + menu[ i ][ ii ] + " height='100px'/>"
$( "ul" ).append( "<li>" + elem + "</li>" );
}
}
});
https://jsfiddle.net/dh3ozpxk/
HTML:-
In the body tag I have used onload="variable2.init() ; variable1.init();".
JavaScript:-
var variable1 = {
rssUrl: 'http://feeds.feedburner.com/football-italia/pAjS',
init: function() {
this.getRSS();
},
getRSS: function() {
jQuery.getFeed({
url: variable1.rssUrl,
success: function showFeed(feed) {
variable1.parseRSS(feed);
}
});
},
parseRSS: function(feed) {
var main = '';
var posts = '';
var className = 'even';
var pst = {};
for (i = 0; i < feed.items.length; i++) {
pst = variable1.parsefootballitaliaRSS(feed.items[i]);
if (className == 'odd') {
className = 'even';
}
else {
className = 'odd';
}
var shorter = pst.story.replace(/<(?:.|\n)*?>/gm, '');
item_date = new Date(feed.items[i].updated);
main += '<div id="content1" class="post-main ' + className + '" onclick="mwl.setGroupTarget(\'#screens1\', \'#blog_posts1\', \'ui-show\', \'ui-hide\');mwl.setGroupTarget(\'#blog_posts1\', \'#post' + (i+1) + '\', \'ui-show\', \'ui-hide\');">';
main += '<b>' + pst.title.trunc(55, true) + '</b><br />' + shorter.trunc(30, true);
main += '<div class="datetime">' + item_date.getDateTime() + '</div></div>';
posts += '<div class="post-wrapper ui-hide" id="post' + (i+1) + '">';
posts += '<div class="post-title"><b>' + pst.title + '</b></div>';
posts += feed.items[i].description;
posts += '</div>';
}
jQuery('#main_screen1').html(main);
jQuery('#blog_posts1').html(posts);
},
parsefootballitaliaRSS: function(item) {
var match = item.description.match('src="([^"]+)"');
var part = item.description.split('<font size="-1">');
var arr = {
title: item.title,
link: item.link,
image: match,
site_title: item.title,
story: item.description
};
return arr;
}
};
var variable2 = {
weatherRSS: 'http://feeds.feedburner.com/go/ELkW',
init: function() {
this.getWeatherRSS();
},
getWeatherRSS: function() {
jQuery.getFeed({
url: variable2.weatherRSS,
success: function showFeed(feed) {
variable2.parseWeather(feed);
}
});
},
parseWeather: function(feed) {
var main = '';
var posts = '';
var className = 'even';
var pst = {};
for (i = 0; i < feed.items.length; i++) {
pst = variable2.parsegoRSS(feed.items[i]);
if (className == 'odd') {
className = 'even';
}
else {
className = 'odd';
}
var shorter = pst.story.replace(/<(?:.|\n)*?>/gm, '');
item_date = new Date(feed.items[i].updated);
main += '<div id="content2" class="post-main ' + className + '" onclick="mwl.setGroupTarget(\'#screens2\', \'#blog_posts2\', \'ui-show\', \'ui-hide\');mwl.setGroupTarget(\'#blog_posts2\', \'#post' + (i+1) + '\', \'ui-show\', \'ui-hide\');">';
main += '<b>' + pst.title.trunc(55, true) + '</b><br />' + shorter.trunc(30, true);
main += '<div class="datetime">' + item_date.getDateTime() + '</div></div>';
posts += '<div class="post-wrapper ui-hide" id="post' + (i+1) + '">';
posts += '<div class="post-title"><b>' + pst.title + '</b></div>';
posts += feed.items[i].description;
posts += '</div>';
}
jQuery('#main_screen2').html(main);
jQuery('#blog_posts2').html(posts);
},
parsegoRSS: function(item) {
var match = item.description.match('src="([^"]+)"');
var part = item.description.split('<font size="-1">');
var arr = {
title: item.title,
link: item.link,
image: match,
site_title: item.title,
story: item.description
};
return arr;
}
};
When I run the program it only reads one of the variables i.e. either 1 or 2.
How can I correct them to read both the variables?
Use this.
<script type="text/javascript">
window.onload = function() {
variable1.init();
variable2.init();
}
</script>
Try this
<body onload="callFunctions()">
JS-
function callFunctions()
{
variable1.init();
variable2.init();
}
Update-
Also
there are other different ways to call multiple functions on page load
Hope it hepls you.
I have a website which includes this RSS JavaScript. When I click feed, it opens same page, but I don't want to do that. How can I open with blank page? I have my current HTML and JavaScript below.
HTML CODE
<tr>
<td style="background-color: #808285" class="style23" >
<script type="text/javascript">
$(document).ready(function () {
$('#ticker1').rssfeed('http://www.demircelik.com.tr/map.asp').ajaxStop(function () {
$('#ticker1 div.rssBody').vTicker({ showItems: 3 });
});
});
</script>
<div id="ticker1" >
<br />
</div>
</td>
</tr>
JAVASCRIPT CODE
(function ($) {
var current = null;
$.fn.rssfeed = function (url, options) {
// Set pluign defaults
var defaults = {
limit: 10,
header: true,
titletag: 'h4',
date: true,
content: true,
snippet: true,
showerror: true,
errormsg: '',
key: null
};
var options = $.extend(defaults, options);
// Functions
return this.each(function (i, e) {
var $e = $(e);
// Add feed class to user div
if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
// Check for valid url
if (url == null) return false;
// Create Google Feed API address
var api = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;
if (options.limit != null) api += "&num=" + options.limit;
if (options.key != null) api += "&key=" + options.key;
// Send request
$.getJSON(api, function (data) {
// Check for error
if (data.responseStatus == 200) {
// Process the feeds
_callback(e, data.responseData.feed, options);
}
else {
// Handle error if required
if (options.showerror) if (options.errormsg != '') {
var msg = options.errormsg;
}
else {
var msg = data.responseDetails;
};
$(e).html('<div class="rssError"><p>' + msg + '</p></div>');
};
});
});
};
// Callback function to create HTML result
var _callback = function (e, feeds, options) {
if (!feeds) {
return false;
}
var html = '';
var row = 'odd';
// Add header if required
if (options.header) html += '<div class="rssHeader">' + '' + feeds.title + '' + '</div>';
// Add body
html += '<div class="rssBody">' + '<ul>';
// Add feeds
for (var i = 0; i < feeds.entries.length; i++) {
// Get individual feed
var entry = feeds.entries[i];
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
// Add feed row
html += '<li class="rssRow ' + row + '">' + '<' + options.titletag + '>' + entry.title + '</' + options.titletag + '>'
if (options.date) html += '<div>' + pubDate + '</div>'
if (options.content) {
// Use feed snippet if available and optioned
if (options.snippet && entry.contentSnippet != '') {
var content = entry.contentSnippet;
}
else {
var content = entry.content;
}
html += '<p>' + content + '</p>'
}
html += '</li>';
// Alternate row classes
if (row == 'odd') {
row = 'even';
}
else {
row = 'odd';
}
}
html += '</ul>' + '</div>'
$(e).html(html);
};
})(jQuery);
try change this:
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'
to
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'
Buildgames returns rows:
<a>....</a>
<a>....</a>
When I click on each a the Buildcar_s function returns all the data inside an alert.
Instead of this alert I want to put all the results in a div under each a, so it would look like:
<a>.....clicked ...</a>
<div>....
...
</div>
<a>....not clicked...</a>
<a>....not clicked...</a>
<a>....not clicked...</a>
How can we put a div only under the a which was clicked?
function Buildcar_s(items) {
var div = $('<div/>');
$.each(items, function() {
var car_ = this.car_;
$('<a>' + this.car_ + '----' + this.Names + '---' + '</a>').click(function() {
_Services.invoke({
method: 'GetgamesRows',
data: {
car_Number: car_
},
success: function(car_s) {
var div = Buildgames(car_s);
$(div).insertAfter($a);
}
});
}).appendTo(div);
$('<br/>').appendTo(div);
});
$("#leftRows").append(div);
}
function Buildgames(items) {
var place = '<div>';
$.each(items, function() {
place += 'mmmmmm<br/>';
});
place += '</div>';
return place;
}
Try this, relevant changes have been commented:
function Buildcar_s(items) {
var div = $('<div/>');
$.each(items, function() {
var car_ = this.car_;
$('<a>' + this.car_ + '----' + this.Names + '---' + '</a>').click(function() {
var $a = this;
_Services.invoke({
method: 'GetgamesRows',
data: {
car_Number: car_
},
success: function(car_s) {
var div = Buildgames(car_s);
// this inserts the HTML generated from the function,
// under the A element which was clicked on.
$(div).insertAfter($a);
}
});
}).appendTo(div);
$('<br/>').appendTo(div);
});
$("#leftRows").append(div);
}
function Buildgames(items) {
var place = '<div>';
$.each(items, function() {
place += '<div style="float: right;"> ' + this.CITY + ' ' + '</div><BR />' + +'<br/><br/>';
});
place += '</div>';
return place; // returns the string created, as opposed to alerting it.
}