Dynamic jQuery Dialog passing JSON object from within loop - javascript

I'm wondering if there is a better (cleaner?) method than my current implementation. I'm currently encoding a PHP SimpleXMLObject (USPS Tracking API) to JSON and looping through said JSON object via Javascript to operate the front-end.
Examples from my current implementation below:
Function to display dialog implemented anonymously outside of .ready() :
var moreInfo_popup = function(i) {
$('#moreinfo'+i).dialog({
modal:false,
autoOpen:false,
height:555,
title: 'Detailed View',
width:500,
draggable:false,
buttons: {
Ok: function(){
$(this).dialog("close");
}
}
});
$('#moreinfo'+i).dialog('open');
}
Main loop for displaying Tracking ID, Most Recent Event, and Mail Class for each API response- I'm currently generating a content div appended to #modal_container, then calling moreInfo_popup() inline via <input onClick="">:
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
if(key % 2 === 0) {
$('#page-nav').append("<div id=\"results_table\"><table class=\"data_table\"id=\"data_table_id\"border=\"0\"width=\"60%\"align=\"center\"><tr><td align=center width=20%>"+obj[key].TrackInfo.Attributes.ID+"</td><td align=\"center\"width=\"35%\">"+obj[key].TrackInfo.StatusSummary+"</td><td align=\"center\"width=\"20%\">"+obj[key].TrackInfo.Class+"</td><td align=\"center\"><input type=\"button\"class=\"moreInfo\"value=\"Detail\"id=\"_buttonMoreInfo\"onClick=\"moreInfo_popup("+key+")\"></td></tr></table></div>");
$('#modal_container').append("<div id=\"moreinfo" + key + "\"><table><tr><td>" + obj[key].TrackInfo.Attributes.ID +"</td></tr></table>").hide();
}
else {
$('#page-nav').append("<div id=\"results_table\"><table class=\"data_table_even\" id=\"data_table_id\" border=0 width=60% align=center><tr><td align=center width=20%>"
+ obj[key].TrackInfo.Attributes.ID + "</td><td align=center width=35%>" + obj[key].TrackInfo.StatusSummary + "</td><td align=center width=20%>"
+ obj[key].TrackInfo.Class + "</td><td align=\"center\"><input type=\"button\" value=\"Detail\" class=\"moreInfo\" id=\"_buttonMoreInfo\"onClick=\"moreInfo_popup("+key+")\"></td></tr></table></div>");
$('#modal_container').append("<div id=\"moreinfo" + key + "\"><table><tr><td>" + obj[key].TrackInfo.Attributes.ID +"</td></tr><tr><td> <button>OK</button></td></tr></table>");
}
}
$("#page-nav td:contains('undefined')").html("Invalid");
}
As I'm sure you can see, this feels like an incredibly tedious way of accomplishing the desired outcome, to which there is surely a better alternative. As a newcomer to JavaScript/jQuery, I've done plenty of searching on this subject, but haven't really understood much of what I found- If indeed I was asking the right questions in the first place.

I think you can use angular and data bind:
So you can just use a directive and automatically bind your JSON object from the server side easily to the html elements.
However you should start studying angular.
you can start looking for your elegant way of doing stuffs here:
https://docs.angularjs.org/tutorial/step_04
I hope it was useful.

Related

How to pass a value from a Javascript generated button to a controller?

My code generates a table with a button at the end of each row. When the user clicks a button how can I pass a property u.userEmail to the controller via the button? Will the value being sent to the controller be a string?
My (non-working) attempt:
<script>
$(document.body).append("waiting on async table to load<br>");
$(document).ready(function () {
$.getJSON("/Account/LoadClaimsTable", function (crewResponse) {
//returns a List<UserClaims>
$(document.body).append("<table>")
crewResponse.forEach(function (u) {
var s = "";
s+="<tr><td>" + u.userEmail + "</td>";
u.userClaims.forEach(function (k) {
console.log("added claim"+k.value);
s += ("<td>" + k.type + "</td><td>" + k.value + "</td><td>" +
"<input type=\"hidden\" name=\"userEmail\" value=\"`${u.userEmail}`\" />"+
"<input type=\"button\" value=\"Create\" onclick=\"location.href='#Url.Action("EditClaims", "Account")'" />
+"</td>");
});
s += "</tr>";
$(document.body).append(s);
s = "";
});
$(document.body).append("</table>")
});
});
</script>
AccountController.cs contains:
public ActionResult EditClaims(string userEmail)
{
return View("StringView", userEmail);
}
You have to pass it on the url of the action. Not sure if you want to pass u.userEmail, but it could looks like this:
crewResponse.forEach(function (u) {
var s = "<tr><td>" + u.userEmail + "</td>";
u.userClaims.forEach(function (k) {
console.log("added claim"+k.value);
s += ("<td>" + k.type + "</td><td>" + k.value + "</td><td>" +
"<input type=\"hidden\" name=\"userEmail\" value=\"`${u.userEmail}`\" />"+
"<input type=\"button\" value=\"Create\" onclick=\"location.href='#Url.Action("EditClaims", "Account")?userEmail=" + u.userEmail + "'\"/></td>");
});
s += "</tr>";
$(document.body).append(s);
});
There are multiple ways to do it. One is mentioned in the answer above by Felipe. Here is another alternate approach using unobtrusive js
Add the email as html5 data attributes to the button along with another attribute which we will use bind the click behavior.
u.userClaims.forEach(function (k) {
// Add quotes as needed if you want multiline ( i just removed those)
s += "<td>" + k.type + "</td><td>" + k.value + "</td><td>
<input type='button'
clickablebutton data-email='" + u.email + "' value='Create'/></td>";
});
Now, in your document ready, bind a click event handler to those elements (with our custom attribute) and read the data attribute and build the url you need.
$(document).on("click", "input[clickablebutton]", function (e){
var url = '#Url.Action("EditClaims", "Accounts")?useremail=' + $(this).data("email");
window.location.href = url;
});
Some other suggestions
Use the appropriate element. Button is better than input (Consider accessibility)
If it is for navigation, Use an anchor tag instead of a button.
Inline javascript is not great. Let the browser parses your markup without any interruptions and you can add the behavior scripts later (that is the whole point of uobutrisive js approach)
The approach you appear to be taking would be Ajax, response, render a template. With that being said, you may want to rethink your approach.
Step 1.
Build a template
<template id="...">
<button type="button" value="[action]" onclick="[url]">[text]</button>
</template>
Step 2.
Create your request.
axios.get('...').then((response) => {
// Retrieve template.
// Replace bracket with response object model data.
html += template.replace('[action]', response.action);
});
Step 3.
Have the JavaScript render your template.
The above can create a clear concise codebase that is easier to maintain and scale as the scope changes, rather than an individual request performing a change with embedded markup. This approach has worked quite well for me, also I feel it'll make you troubleshooting and definition easier, as the controller is handing an object back to your JavaScript instead of a markup / view data. Which will be a better finite control for the frontend and clear modifications in future.

I can't manage to put this JSON data inside DataTables

So, the situation is this. There is a HTML page with a table in it, that is using the DataTables plugin. I have to show data that I'm receiving from a jQuery POST call in the table, but I always seem to get errors and am lost in how to go about doing that.
This is what the response from the POST call looks like:
[{"idoperatore":10,"nome_cognome":"Daniele Torrini","tariffa_esterno":"50.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":11,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"DT"},{"idoperatore":12,"nome_cognome":"Irene Cavalletto","tariffa_esterno":"75.00","tariffa_interno":"45.00","tariffa_viaggio":"30.00","idtariffa_esterno":9,"idtariffa_interno":15,"idtariffa_viaggio":13,"attivo":1,"rs":1,"iniziali":"IC"},{"idoperatore":14,"nome_cognome":"Sandra Moschetti","tariffa_esterno":"50.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":11,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"SM"},{"idoperatore":15,"nome_cognome":"Federica Coucourde","tariffa_esterno":"90.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":8,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"FC"},{"idoperatore":16,"nome_cognome":"Matteo Belgero","tariffa_esterno":"75.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":9,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"MB"},{"idoperatore":17,"nome_cognome":"Luca Belgero","tariffa_esterno":"90.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":8,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"LB"},{"idoperatore":18,"nome_cognome":"Federico Bottoni","tariffa_esterno":"50.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":11,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"FB"},{"idoperatore":19,"nome_cognome":"Giuseppe Pantaleo","tariffa_esterno":"60.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":10,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"GP"},{"idoperatore":20,"nome_cognome":"Matteo Ferrario","tariffa_esterno":"90.00","tariffa_interno":"75.00","tariffa_viaggio":"30.00","idtariffa_esterno":8,"idtariffa_interno":9,"idtariffa_viaggio":13,"attivo":1,"rs":1,"iniziali":"MF"},{"idoperatore":21,"nome_cognome":"Alessandro Mazzeranghi","tariffa_esterno":"100.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":7,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"AM"}]
I have no way of modifying the call, I have to work with that. I just have access to the variable that contains that response from the callback, but I can however transform or modify that data if needed.
This is what the HTML table looks like:
<table class="display nowrap" id="table_operatori">
<thead>
<tr>
<th>
<span></span>
</th>
<th class="mdl-data-table__cell--non-numeric">Nome e Cognome</th>
<th>Tariffa Esterno</th>
<th>Tariffa Interno</th>
<th>Tariffa Viaggio</th>
<th>Attivo?</th>
<th>RS?</th>
<th class="mdl-data-table__cell--non-numeric">Iniziali</th>
</tr>
</thead>
<tbody id="table_operatori_tbody">
</tbody>
</table>
There are not the same number of columns in the table as fields in the JSON because the fields in JSON starting with "id" have to be hidden values, and were used before as attributes of the HTML elements, to use them in later moments. It's also the reason for the empty header: the table was actually filled with pure HTML before, and had a checkbox in front to select the row, like this:
data.forEach(function (element) {
element["attivo"] == "1" ? element["attivo"] = "Si" : element["attivo"] = "No";
element["rs"] == "1" ? element["rs"] = "Si" : element["rs"] = "No";
var i = element['idoperatore'];
var tableRow = '<tr><td><label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" for="table_operatori_checkbox_row[' + i + ']"><input type="checkbox" id="table_operatori_checkbox_row[' + i + ']" class="mdl-checkbox__input" onClick="fOperatore_Checkbox_SelectUnique(' + i + ')" /></label></td>'
tableRow += '<td class="mdl-data-table__cell--non-numeric" id="table_operatori_nomecognome_row[' + i + ']">' + element['nome_cognome'] + '</td>';
tableRow += '<td id="table_operatori_tariffaesterno_row[' + i + ']" idtariffa="' + element["idtariffa_esterno"] + '">' + element['tariffa_esterno'] + '</td>';
tableRow += '<td id="table_operatori_tariffainterno_row[' + i + ']" idtariffa="' + element["idtariffa_interno"] + '">' + element['tariffa_interno'] + '</td>';
tableRow += '<td id="table_operatori_tariffaviaggio_row[' + i + ']" idtariffa="' + element["idtariffa_viaggio"] + '">' + element['tariffa_viaggio'] + '</td>';
tableRow += '<td id="table_operatori_attivo_row[' + i + ']">' + element['attivo'] + '</td>';
tableRow += '<td id="table_operatori_rs_row[' + i + ']">' + element['rs'] + '</td>';
tableRow += '<td class="mdl-data-table__cell--non-numeric" id="table_operatori_iniziali_row[' + i + ']">' + element['iniziali'] + '</td></tr>';
$("#table_operatori_tbody").append(tableRow);
This worked, in a sense, (apart from being extremely ugly) meaning that the table formed and you could select rows like we wanted and act on those later. But you couldn't sort, or filter with search, any of the rows in the table.
Still, I was willing to maintain the ugly HTML building if it meant getting the DataTable to work, since with .row.add() you can add a element, I tried that as well, changing the .append(tableRow) with:
.DataTable().row.add($.parseHTML(tableRow));
This didn't work either, and gave the same error. Also displayed this on the table though: Displays object picture
At the moment of initialization, I don't have the data to put inside the table. The table has to be initialized empty, and rows from the response added at a later time. I tried (with "data" being the variable containing the response from the server):
$("#table_operatori").DataTable().rows.add(data);
Which would remove a lot of the ugly HTML building, but it gives error:
DataTables warning: table id=table_operatori - Requested unknown parameter '1' for row 0, column 1. For more information about this error, please see http://datatables.net/tn/4
So, by looking at that tech-notes link, it says that it may be that you have more columns in the table head than in the table body, so I matched exactly the fields that I get, when defining the table, thinking that I may eventually be able to hide the columns that I don't need if that works.
$("#table_offerte").DataTable({
paging: false,
info: false,
columns: [
{ title: "idoperatore" },
{ title: "nome_cognome" },
{ title: "tariffa_esterno" },
{ title: "tariffa_interno" },
{ title: "tariffa_viaggio" },
{ title: "idtariffa_esterno" },
{ title: "idtariffa_interno" },
{ title: "idtariffa_viaggio" },
{ title: "attivo" },
{ title: "rs" },
{ title: "iniziali" }
]
});
But it still gives the same error. It also does if I match the table structure with the DataTable initialization :
columns: [
{ title: "idoperatore" },
{ title: "nome_cognome" },
{ title: "tariffa_esterno" },
{ title: "tariffa_interno" },
{ title: "tariffa_viaggio" },
{ title: "attivo" },
{ title: "rs" },
{ title: "iniziali" }
]
Documentation from DataTables also says that it looks inside a data: property when looking at JSON data, and you have to specify if it is not an object but an array by setting an empty string in the dataSrc property:
DataTable({ ajax: { url: "something.json", dataSrc: "" } });
The problem is that it requires the data being requested by the url: property, and I cannot do that, because I only have the "data" variable which contains the JSON.
I should also mention that by maintaining the old HTML building and appending it inside the table body, makes the table work and display stuff right, like this, but of course as soon as you try to sort or filter anything, it all disappears because the DataTable doesn't ACTUALLY have the rows inside it, just the HTML does.
I have no idea how to get this data in there. I hope I explained everything clearly, otherwise feel free to ask anything and I will try my best to clarify.
Thanks in advance for any help.
The doc is a bit confusing, because there are so many different ways to set up a table, and it's pretty much one guy (Allan Jardine) both writing the plugin and documenting it.
First, you don't need any table headers. Change your HTML to this:
<table class="display nowrap" id="table_operatori"></table>
If you want to add ids or classes to tbody tags, then you'll need to add them in as well. But to start, this is all the HTML you need.
What's confusing here is that a lot of Allan's examples include the data hard-coded into the HTML, with no JSON or AJAX or anything involved. When you do that, then you do need to set up the HTML headers, and all the cells, and everything else. Take a look at the HTML in one of his examples (this one, for example) and see this for yourself. And then, when he moves on to JSON examples, he pulls the data but he leaves the headers in. And again, you can put them in, but don't have to.
Rather, if you're pulling your data from JSON, you can either specify your headers with HTML th tags or you can do it with the columns (or colDefs) option. You don't need to do both. This isn't as clear from the doc as it might be, since in most of the examples Allan does do both.
Whichever way you specify the headers, they have to match the column count of the JSON feed. If they don't, you'll get some form of the error you're getting. Furthermore, if you use both column and th, they both have to match your JSON field count or you'll get that error. That's why you're getting your error. You matched your columns definition correctly, but you've left some th tags out in your table definition. The solution is to remove the th tags entirely.
I'm going to presume that the reason that you left out some th tags is that you are under the impression that that's the way to make the column invisible. It isn't, for the reasons I've described above. The easiest way to define whether a column is visible or not (as well as define a lot of other possible attributes, listed here) is in your columns array: just set the column's visible option to false. (You could also use th tags with a class and set visibility:none in CSS, but this is simpler. Less to keep track of.)
Also, the title value on a column is the value for title in your columns array for that column. So, you need to make it look the way you want it, not put the name of your JSON field there.
Finally, with the data option, you're reading the wrong part of the documentation, which is about how to pull JSON from a URL using AJAX at the time you run dataTable(). You have the data already in your POST data, so you don't need to do that. So, read this instead. Have a look at the second example, which shows an array of objects as a data source. From what I see of your JSON string, you should just have to add an option like this:
data: myPOSTResponse,
Putting all that together:
$("#table_offerte").DataTable({
paging: false,
info: false,
data: myPOSTResponse,
columns: [
{ visible: false }, //this is the ID you don't want to see, no need to give it a title
{ title: "Nome e Cognome", className: "mdl-data-table__cell--non-numeric" },
{ title: "Tariffa Esterno" },
{ title: "Tariffa Interno" },
{ title: "Tariffa Viaggio" },
{ visible: false },
{ visible: false },
{ visible: false },
{ title: "Attivo?" },
{ title: "RS?" },
{ title: "Iniziali", className: "mdl-data-table__cell--non-numeric" }
]
});
That should get you running, if you haven't done something else interesting. :)
Edit: as DocCobra mentions in the comments, you also have to specify the data: option at the field level here, since the array elements are objects. If they are themselves arrays, you do not.

How do I set an attribute to a dynamically created button?

First and foremost, hello. I'm a college student and not a very experienced coder, so forgive me if I end up saying something really dumb.
Either way, I have a school project in which I have to create a functional website using Node.js, where people are able to log in and buy stuff.
Most of the stuff already works, but I am having trouble with a very specific thing which I simply cannot get to work, yet is essential to the project itself.
I import data from a mySql database into the website using AJAX, that data contains products that people can buy. Then, those products are appended to the HTML page itself, and dynamically create two buttons for each product that is appended, one which says "Buy Now" and the other which says "Learn More".
Now, those buttons are supposed to be somehow associated to the values of the database, but I have no idea how to do this.
$(document).ready(function () {
$(function () {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/getPacotes',
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
var pacoteSet1 = "<div class='col-md-4 pacotes'>";
var pacoteSet2 = "<input id=btnPac"+
i + " type='button' name='comprar' value='Comprar Pacote'>";
var pacoteSet3 = "</div>";
var idPacote = data[i].idPacote;
var nomePacote = data[i].Nome_Pacote;
$("#pacotes").append(pacoteSet1 +
"<h1>" + nomePacote + "</h1>" +
"<h1>" + nomePacote + "</h1>" +
"<h3>" + precoPacote + "euros/mes </h3>" +
pacoteSet2 +
pacoteSet3);
}
}
});
});
});
My teacher told me to give an attr to the buttons I create, and that's what I was pretty much trying to do now, but I dont know how to do that, I mean, if the buttons were static it would be pretty easy, but since the buttons are not there when the document is created, I dont know if this will work
$("#btnPac" + i).attr({"id": idPacote,
"nome": nomePacote,
"preco": precoPacote,
});
Anyway, Hopefully, I didn't sound too dumb and thanks in advance
TL:DR how do I give an attribute to a dynamically created button
You just need to change your jquery function like below:
$(document).find("#btnPac" + i).attr({"id": idPacote,
"nome": nomePacote,
"preco": precoPacote
});
This should be your solution.
You can do that while creating the html for button element. By using string concatenation, which you are already using while setting the ID:
var pacoteSet2 = "<input id=btnPac"+ i + " nome='" + nomePacote + "' preco='" + precoPacote + "' type='button' name='comprar' value='Comprar Pacote'>";
Overloading the HTML with attributes is a bad idea in my opinion. You could create the Elements in JS, bind the data to it, and then append the button to the dom. Thats quite easy with jquery:
var button=$("<button>Show More</button>");//create
button.on("click",showMore.bind({name:"test"}));//add listener
$(document.body).append(button);//append
function showMore(){
alert(this.name);
}
You can create a new input tag and set these attributes then append to your div with this code:
$('<input/>', {
id: 'btnPac' + i,
nome: nomePacote ,
preco: precoPacote ,
type: 'button'
}).appendTo("#pacotes");
You can do the same for your others (h1, h3)

How much knowledge of the DOM should javascript code have?

I'm implementing OpenID and OAuth on my site, in C# and ASP.NET MVC 3. I'm basing off of DotNetOpenAuth for the back-end and openid-selector for the front-end.
I liked openid-selector but it doesn't have OAuth support out of the box so I started adapting it (with help of StackOverflow's implementation and jsbeautifier).
I found a lot of code that handles the DOM like this:
function highlight(boxId) {
// remove previous highlight.
var highlight = $('#openid_highlight');
if (highlight) {
highlight.replaceWith($('#openid_highlight a')[0]);
}
// add new highlight.
$('.' + boxId).wrap('<div id="openid_highlight"></div>');
};
or
function useInputBox(provider) {
var area = $('#openid_input_area');
var id = 'openid_username';
var html = '';
var value = '';
var style = '';
var label = provider.label;
if (label) {
html = '<p>' + label + '</p>';
}
if (provider.name == 'OpenID') {
id = this.input_id;
value = 'http://';
style = 'background: #FFF url(' + spritePath + ') no-repeat scroll 0 50%; padding-left:18px;';
}
html += '<input id="' + id + '" type="text" style="' + style + '" name="' + id + '" value="' + value + '" />'
+ '<input id="openid_submit" type="submit" value="' + this.signin_text + '"/>';
area.empty();
area.append(html);
$('#' + id).focus();
};
Which both sound to me like they're assuming too much about the DOM (too many ids, or the current state of the DOM).
Is it ok to have javascript so tightly coupled to the DOM? What's the best way to avoid code like this and follow a less intrusive approach?
I guess what perplexes me is the call:
openid.init('openid_identifier', '', 'http://cdn.sstatic.net/Img/openid/openid-logos.png?v=8', true);
When there's so much assuming already in the script file.
I'd argue, as you suspect that this is a bad thing.
There's a huge lack of, well, design patterns in Javascript UI development. I'm guessing a lot of people came straight from html, to learning some jQuery, to writing web applications.
A simple system (I find) that does handle this better, is backbone.js. The sourcecode is legible, and it separates view-concerns from business logic concerns quite nicely.
http://documentcloud.github.com/backbone/
http://martinfowler.com/eaaDev/uiArchs.html
Also for a more MVVM approach ( aka data binding ) knockoutjs is an option. They also have a nice interactive tutorial to get you started.

jquery: "Exception thrown and not caught" in IE8, but works in other browsers

My code works fine in other browsers, but in IE8 I get "error on page" - and when I click that it says:
"Exception thrown and not caught Line: 16 Char: 15120 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"
I tried linking to jquery.js (rather than jquery.min.js) and to 1.5.1/jquery.min.js,
but problem still remains.
Can someone correct/improve my code for me, or guide me as to where to look. Thanks
<script type="text/javascript">
function fbFetch()
{
var token = "<<tag_removed>>&expires_in=0";
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/<<ID_REMOVED>>?&callback=?&access_token=" + token;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url, function(json)
{
json.data = json.data.reverse(); // need to reverse it as FB outputs it as earliest last!
var html = "<div class='facebook'>";
//loop through and within data array's retrieve the message variable.
$.each(json.data, function(i, fb)
{
html += "<div class='n' >" + fb.name;
html += "<div class='t'>" + (dateFormat(fb.start_time, "ddd, mmm dS, yyyy")) + " at " + (dateFormat(fb.start_time, "h:MMtt")) + "</div >";
html += "<div class='l'>" + fb.location + "</div >";
html += '<div class="i"><a target="_blank" title="opens in NEW window" href="https://www.facebook.com/pages/<<id_removed>>#!/event.php?eid=' + fb.id + '" >more info...</a></div>';
html += "</div >";
}
);
html += "</div>";
//A little animation once fetched
$('.facebookfeed').animate({opacity: 0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity: 1}, 500);
});
};
Does the code do the job in IE8 or does it break? The reason I ask is because if it works as expected you could just wrap it in a try{ } catch{ \\do nothing } block and put it down to another thing IE is rubbish at.
You may be better off creating an object for the creation of the facebook div. Something like...
var html = $('<div />');
html.attr('class', 'facebook');
Then in your each loop you can do this...
$('<div />').attr('class', 'n').append(fb.name).appendTo(html);
$('<div />').attr('class', 't').append etc...
Then append html to the facebookfeed object
Doing this may remove the scope for error when using single quotes and double quotes when joining strings together, which in turn may solve your issue in IE8
$('.facebookfeed').fadeOut(500, function(){
$(this).append(html).fadeIn(500);
});
Hope this helps!
UPDATE
The append method is used to add stuff to a jquery object. For more info see here
So to surround the div's as you mentioned in the comments you would do something like this...
var nDiv = $('<div />').attr('class', 'n').append(fb.name);
$('<div />').attr('class', 't').append(fb.somethingElse).appendTo(nDiv);
// etc
And then you would need to append that to the html div like so...
html.append(nDiv);
So that would give you
<div class="facebook">
<div class="n">
value of fb.name
<div class="t">
value of fb.somethingElse
</div>
</div>
</div>
So what you have done is created a new jquery object and appended to that, then appended that to the html object which you have then appended to the facebookfeed div. Confusing huh?!

Categories

Resources