Apply Masonry on content from Facebook API - javascript

I have been trying to implement Masonry into this project for ages now, and I would be totally happy to have someone who can help me out. The internet is full of similar problems with masonry, but none of the given solutions could help me fix this.
Basically, I am pulling reviews from my Facebook page via the Open Graph API with the following code. The Facebook response data is converted from json to an array and then stored in the fb_reviews variable for later use. This one works as desired:
[...]
function (response) {
if (response && !response.error) {
//convert to array
fb_reviews = Object.keys(response).map(function (_) {
return response[_];
});
//only store needed data of fb_reviews[0]
fb_reviews = fb_reviews[0];
reviews();
}
;
});
[...]
This works perfectly. As you can see, the following reviews() function is called next to display the Facebook data, and this is where I would like masonry to kick in:
// DISPLAY REVIEWS
var print2 = "";
var reviews = function() {
var z = fb_reviews.length - 1;
var print2 = "";
for (i = 0; i < z; i++) {
//put together div container for every review object
print2 += '<div class="review" id="review-' + i + '"><div class="meta">' + fb_reviews[i].reviewer.name + ' rated ' + fb_reviews[i].rating + '/5</div><blockquote>' + fb_reviews[i].review_text + '</blockquote></div>';
}
print2 = $(print2);
// still works!!!
$("#reviews").append(print2);
//until here, everything still works, but the following does no longer work:
$("#reviews").masonry({
itemSelector: '.review'
});
}
;
The content is appended as desired etc., but I have literally tried any possible way to initialize masonry, including using all snippets I could find for appended content, e. g.:
$("#reviews").append( print2).masonry( 'appended', print2 );
There are many more, including reload and layout etc, but this does not make much sense to me, because there is no content in the #reviews-div-container until all Facebook reviews are loaded and appended.
Masonry ALWAYS seems to be called BEFORE the Facebook reviews are appended, no matter where I would position and spread the masonry code snippets.
So what is the best way to get Masonry initialized AFTER the Facebook data is stored and appended?
Thank you so much in advance for your help! Really appreciate your support
Simon

Related

Why is the table data being added to the heading and the body?

I have been working on a todo list web applicaton for an assignment and have been using this code up until now:
const db = new Database();
document.addEventListener("DOMContentLoaded", function(event) {
setTimeout(function() {
db.getAllTodos(function(records) {
records.forEach(function() {
console.log(records.length);
var cols = ['taskName','taskDesc', 'taskDate','taskTime','taskPriority','taskLocation','taskImage'];
for (var i = 0; i <= records.length; i++){
$('table').append('<tr></tr>' );
for (var j = 0; j < cols.length; j++) {
var lastCell = $('table tr:last-child');
lastCell.append ('<td>' + records[i][cols[j]] + '</td>' );
}
lastCell.append("<td class=\"delete\"><button onclick=\"deleteTask()\">Delete</button><button onclick=\"editTask()\">Edit</button></td>");
}
})
});
}, 1000);
});
Up until now this has worked fine but now that I am trying to use DataTables to add the ability to sort the data, the data is getting added to the heading as well as the body of the table and I can't figure out why. If I remove the code being used to initialise the DataTable the issue is persisting.
Image showing the table with datatable being used
Image showing the table without datatable being used
Since yesterday I've been working on this and looking at the chrome debugging tools but I'm getting nowhere, the code is exactly the same as before, I even copy pasted it from a previous save I have and the same issue persists. I thought instead that it might be to do with using a JQuery import link from the DataTables website so I tested again with standard JQuery and it was exactly the same. Any advice is greatly appreciated, thanks!
The problem was with the tags. I am not sure why, but removing them has solved the issue of the data appending. In the end I also decided not to use datatables at all as its compatibility with the code I have already written is not great.

DOM elements are only sporadically created despite being loaded by ajax

This is a very specific problem and one that makes me particularly confused. The project in short: I'm working on a counseling website that gets data from an API and is loaded with AJAX. I'm now trying to get old, archived chats to be be preloaded and displayed with css on click in a menu.
Here's the problem: It works... but only about 1 in 3 times or after reload of the page. I don't understand how that can be, either it should work or it doesn't.
I checked and the data is always loaded (it has to because the current chat is opened first and always works)
So how can that be?
$.ajax({
type: 'POST',
url: '/vsbt/counselling/archive/',
data: {},
}).done(function(data) {
console.log('ajax /vsbt/counselling/archive/');
console.log(data);
//menu is created
$('#counselling_status').append('<ul class="archivedCounsellings"></ul>');
$('.archivedCounsellings').append('<h2>Archivierte Chats</h2>')
for (var i = 0; i < data.length; i++) {
//menu items are added
var that = data[i].messages[0].title;
$('.archivedCounsellings').append('<li class="' + that + '"><a>' + that + '</a></li>')
$('#vbst_communication_container').prepend($('<div class="counselling inactive ' + that + '" />')
.append($('<h2>' + that + '<h2>')));
//the messages are added with to classes for styling
data[i].messages.forEach(function(message) {
$("div." + that)
.append($('<div />')
.addClass(message.type)
.append($('<p />')
.text(message.message)))
});
//this doesn't work either, you can maybe tell me why, but that's not the issue
$('.counselling').data("status", [i]);
}
$(".archivedCounsellings").append('<li class="aktuell"><a><br>Zur aktuellen Beratung</a></li>');
//click event to toggle the displayed counseling
$('.archivedCounsellings li').click(function() {
$('.counselling').addClass('inactive');
$('div .' + $(this).attr('class')).removeClass('inactive');
//workaround which works, but isn't really acceptable
// no load workaround
// if($('.openCounselling').siblings().length == 0){
// window.location.reload();
// }
// $('.statusDisplay').text($('#job_status_' + $(this).attr('class')).data("status"));
// console.log($('div .' + $(this).attr('data-status')));
});
PS. I'm aware of the typo in 'counselling'
PPS. if you find a mistake that obviously makes it fail that probably happend while copying since, remember, it does work sometimes.
Ok so if anyone ever encounters this problem: I was just explained AJAX a little bit closer and basically AJAX sends out all the requests more or less simultaneously. Whatever happens in the done function happens after that, hence the successful data request.
What I did, was initiate the container for said elements in a different function. So occasionally that one was a little bit slower and there was no place to append my elements to --> no error, just nothing happened.
It's unlikely that anyone will see this, since it's very specific, but maybe this'll help someone, at least i know better now

Why is this jQuery load()-command repeated?

I have gone through many stackoverflow posts and other websites to find a solution to this problem, but none of the solutions i could find either fit my problem or just straight up didn't work.
Im using javascript and jQuery (and some Java for background work) to build a page on a website. The page contains a table with data (the data is handled by Java) and i want to have that table refresh every 10 seconds. That works.
But now i also want to highlight all the cells that have changed values in them. For that, as you see in my code snippet, i just simply turn the background of those cells black. That works too.
My problem is that the color only changes for a split second before changing back to standard white. Using the console and playing around a bit i was able to find out that the table is actually reloaded twice, which to me must mean the load-command is executed twice.
window.setInterval(function () {
if (frozen == false) {
$('table').load(document.URL + ' table');
var elem = document.getElementById("freezebtn"); //This is a button generated by Java Code
elem.style.background = getRandomColor();
var tab = document.getElementsByTagName('table').item(1);
var l = tab.rows.length;
for (var i = 0; i<l; i++) {
var tr = tab.rows[i];
var cll = tr.cells[1];
var check = tr.cells[0];
if(check.innerText === "getAsk") {
var valAsk = cll.innerText;
var ask = Number(valAsk);
if (ask != loadPreviousAsk()) {
console.log("TELEFONMAST!");
cll.style.backgroundColor = "#000000";
}
}
//Do this for every other Updateable Cell
...
}
cachePreviousValues(someValues,thatINeed,To,BeCached);
}
My Question is, what is/could be causing the repeat of the load command (or why won't the cells stay black at all)?
Is there a better way of achieving what im trying to do?
Could my code sample be optimized in any other way?
$.fn.load() is async (by default). To handle any logic regarding loaded data, you can use the complete callback:
$('table').load(document.URL + ' table', function(){/* your logic regarding loaded data here*/);

JavaScript Behavior difference: IE11/Edge vrs Chrome/Firefox

function displayInfo(nKey) {
var i, xdata, xfilm, xprop;
if(!nKey) return false;
var objFilm;
var imgRef;
//iterate through all object properties; display their attributes
var jqxhr = $.getJSON('dbMovies.json', function(data) {
$.each(data.disc, function(i, xdata) {
if(xdata.key == nKey) {
objFilm = xdata.film;
imgRef = xdata.img;
if(xdata.doc) bkDoc = true;
return false;
}
}); // $.each
})
.done(function() {
// objFilm has either a single film object or else an array of film objects
var arInfo = [];
if(!$.isArray(objFilm)) {
var arProps = Object.keys(objFilm);....//absolutely
arProps.forEach(function(item) {
if(item != "ref") {
arInfo.push(item + ": " + objFilm[item] + "<br>");
} else {
arInfo.push(item + ": <a href=" + objFilm[item] + " target=_blank>Wikipedia</a>");
}
});
var w = window.open('', '', 'width = 650, height = 500, resizable');
$(w.document.body).html(arInfo.join(""));
}) // .done
I have what we'll call a kiosk app that contains the contents of my film library as stored in a JSON file. One can access the contents in several ways, but each yields a display of all relevant titles. For example, searching for films with Sophia Loren, one would see this result:
All browsers work to this point.
You can see that each film has a link that leads to certain information about the film.
Although one browser (Mac Safari) reportedly does not display the Wikipedia link, all other browsers do. But only the Microsoft browsers (Edge, IE11) show the associated thumbnail. Therefore(?), only the Microsoft browsers respond to a click by invoking my display engine on the full version of the image. All browsers respond well and equally on more direct invocations of the display engine. For example, see [http://www.michaelbroschat.com/LongviewChristmas/LongviewChristmas.html].
The information window is created dynamically upon clicking the index number link shown in the first illustration.
All browsers successfully create the new window and most of the information data items. In fact, Chrome and Firefox appear to create the image display code but don't act upon it.
The entire app can be seen at http://www.michaelbroschat.com/film/disccatalog.html
I would love to know why Chrome and Firefox don't allow what the Microsoft browsers allow.
You left out of your question a critical part of the code, that being the code that creates the <a> tag around the image reference.
The problem you're having is that you're stuffing the assembled HTML for the list of films into that popup window, which is opened with no URL reference. Your <img> tags are built with relative URLs (like "liners/i0001.jpg"), but since there's no base URL for the browser to reference the image can't be loaded.
Internet Explorer may be making some inference that the popup window has the same base URL as the parent, but other browsers apparently don't do that.
I have some theories on this portion of your code:
............arProps.forEach(function(item) {
................if(item != "ref") {
....................arInfo.push(item + ": " + objFilm[item] + "<br>");
................} else {
....................arInfo.push(item + ": <a href=" + objFilm[item] + " target=_blank>Wikipedia</a>");
................}
............});
ONE: Be sure the anchor tag is using single quotes or double quotes depending on your preference when you output the source such as:
Wikipedia
My guess is that being only your version of safari is having an issue with the Wikipedia link it is sensitive to the quotes.
As far as the image goes, where is the img tag to output an image path?

Auto-refresh Javascript For RSS Using Google Feed API

I apologize if the title is trash. What I'd like to do is rather simple in concept... but I'm having a bit of trouble.
I would like to automatically refresh an RSS feed that is displayed using Google Feed API. I haven't worked with the Google Feed API before, but it seemed like a quick option for getting this rolled out. Technically, it only needs to be the content part that is reloaded.
The purpose: This is displaying the results of a poll, refreshing them every 3 seconds (it will be displayed in a presentation.) The actual result is in the 'content', whereas the item being voted on is the 'title'.
The unstyled basics of the code:
<script type="text/javascript">
var feedcontainer=document.getElementById("feeddiv");
var feedurl="http://theurl.com";
var feedlimit=100;
var rssoutput="<b>Latest Results:</b><br /><ul>";
function rssfeedsetup(){
var feedpointer=new google.feeds.Feed(feedurl) //Google Feed API method
feedpointer.setNumEntries(feedlimit) //Google Feed API method
feedpointer.load(displayfeed) //Google Feed API method
}
function displayfeed(result){
if (!result.error){
var thefeeds=result.feed.entries
for (var i=0; i<thefeeds.length; i++)
rssoutput+="<li>" + thefeeds[i].title + "<br />" + thefeeds[i].content + "</li>"
rssoutput+="</ul>"
feedcontainer.innerHTML=rssoutput
}
else
alert("Error fetching feeds!")
}
window.onload=function(){
rssfeedsetup()
}
</script>
I'm not sure how to go about making the results refresh every 3 seconds. I've tried a few things, like "How to autorefresh XML in Javascript" but wound up printing the results multiple times on the page.
Major bonus points for anyone that can point me towards turning it into an auto refreshing bar graph. That will be my next search or question on here.
I think you should call rssfeedsetup() in a setInterval function. Something like
window.onload = function() {
var delay = 3000;
rssfeedsetup();
setInterval(rssfeedsetup, delay);
}

Categories

Resources