Appending HTML+RDFa with JavaScript - javascript

My JavaScript script is not allowing to be marked up semantically. As you can see in my script below, I am using Schema.org and RDFa.
The problem is that when I validate my page, only the part before the append function is validated. This means that only type, headline, publisher and datePublished comes up.
How can I fix it? I suspect the problem here is the append function.
$(document).ready(function(){
$.getJSON(webhose_request, function(results){ //send request to API and store results in "results"
//parse the results' from the JSON response and display them //in a div element for example <div class='webhoseapi'></div>
//we can loop to display all results in a for loop or using the results.posts.lenght; or just display a few.
for (var i = 0; i < 10; i++) {
// you need to read the JSON results to know how to parse them, for example here results.posts[i].text
var articletext = results.posts[i].text;
// we use regular expressions REGEX to replace any new line '\n' and carriage return '\r' with html breaks </br>
articletext = articletext.replace(/(?:\r\n|\r|\n)/g, '</br>');
$(".webhose").append('<div vocab="http://schema.org/" typeOf="Article"><div property="headline" class="whtitel">'+results.posts[i].thread.title_full.substring(0,110)+'</div><div class="source"><b>Source:</b><span property="publisher"> '+results.posts[i].thread.site+'</span></div></div>');
if(results.posts[i].thread.author){
$(".webhose").append('<div class="whpublished"><b>By:</b> <span property ="author">'+results.posts[i].thread.author+'</span></div>');
}
$(".webhose").append('<div class="whpublished"><b>Date published:</b><em><span property="datePublished"> '+results.posts[i].thread.published.substring(0,10)+'</p></span></em> </div>');
//we check if there is an image for this posts then display
if(results.posts[i].thread.main_image){
$(".webhose").append('<div class="whimage"><img property="image" src="'+results.posts[i].thread.main_image+'" height="125" width="200"/></div>');
}
$(".webhose").append('<div property="articleBody" class="wharttext">'+articletext.substr(0,500)+'... <div class="whlink"><a property="url" href= '+results.posts[i].thread.url+'> Read full article »</a></div></div><br>');
}
});
});

I think the issue is that most of the parts of the article aren't in the <div vocab="http://schema.org/" typeOf="Article"> element. This can be shown to be true if one indents HTML from the first append:
<div vocab="http://schema.org/" typeOf="Article">
<div property="headline" class="whtitel">'+results.posts[i].thread.title_full.substring(0,110)+'</div>
<div class="source"><b>Source:</b><span property="publisher"> '+results.posts[i].thread.site+'</span></div>
</div>
In the following I have changed the code to create the article div and then append the contents to it and then append it to the document. The following is untested but I think it might work.
$(document).ready(function() {
$.getJSON(webhose_request, function(results) { //send request to API and store results in "results"
//parse the results' from the JSON response and display them //in a div element for example <div class='webhoseapi'></div>
//we can loop to display all results in a for loop or using the results.posts.lenght; or just display a few.
for (var i = 0; i < 10; i++) {
// you need to read the JSON results to know how to parse them, for example here results.posts[i].text
var articletext = results.posts[i].text;
// we use regular expressions REGEX to replace any new line '\n' and carriage return '\r' with html breaks </br>
articletext = articletext.replace(/(?:\r\n|\r|\n)/g, '</br>');
var article = $('<div vocab="http://schema.org/" typeOf="Article"></div>');
article.append('<div property="headline" class="whtitel">' + results.posts[i].thread.title_full.substring(0, 110) + '</div>')
article.append('<div class="source"><b>Source:</b><span property="publisher"> ' + results.posts[i].thread.site + '</span></div>');)
if (results.posts[i].thread.author) {
article.append('<div class="whpublished"><b>By:</b> <span property ="author">' + results.posts[i].thread.author + '</span></div>');
}
article.append('<div class="whpublished"><b>Date published:</b><em><span property="datePublished"> ' + results.posts[i].thread.published.substring(0, 10) + '</p></span></em> </div>');
//we check if there is an image for this posts then display
if (results.posts[i].thread.main_image) {
article.append('<div class="whimage"><img property="image" src="' + results.posts[i].thread.main_image + '" height="125" width="200"/></div>');
}
article.append('<div property="articleBody" class="wharttext">' + articletext.substr(0, 500) + '... <div class="whlink"><a property="url" href= ' + results.posts[i].thread.url + '> Read full article »</a></div></div><br>');
$(".webhose").append(article);
}
});
});

Related

How can I display my formatted JSON data horizontally, similar to an ecommerce site?

I am working with an API to request specific types of purses from a retailer's website. I then formatted the JSON data so that the purse image and purse name is displayed. However, it is displayed vertically, one purse per row. I would like to display these items next to each other as you see in ecommerce sites. How would I do that/ Below is my code. I did not include my API key though for privacy purposes. Thanks in advance.
$(document).ready(function(){
//make HTTP request
$.get("http://api.vsapi01.com/search/by-url?apikey=[insert key here]0&url=https://product-images4.therealreal.com/BAL31068_2_product.jpg&index=real-bags ", function(data){
data['images'].forEach(function(image,index,images) {
var bagName = image.title;
var clickURL = image.pageUrl;
var pictureURL = image.imageUrl;
var image = "<img src=\""+pictureURL+"\"/>";
var clickableImage = "" + image + "";
var wholeImage = "<div>" + clickableImage + "<br>" + bagName + "<br> " + "<div>";
$( ".display" ).append(wholeImage);
});
});
});
<div class="display"></div>
Like Sam mentioned in his comment, the display property of .display should be set to inline-block:
.display {
display: inline-block
}
Explanation
This is because the div element, which is a block element by default, will always move to the next line after the last block. Setting the element to inline-block will keep all the properties of a block element, but will allow multiple blocks on the same line.
Further Reading
CSS Display Property at MDN

How to hard code text which are coming from javascript messages

Our application is been internationalized and being changed to different languages. For that reason we have to hard code all the messages. How can we do that for messages in javascript ?
This is how we are doing in html messages.
<span th:text="#{listTable.deletedFromTable}">deleted</span>
How do we hard code for javascript messages.(update the table)
$('#TableUpdate-notification').html('<div class="alert"><p>Update the Table.</p></div>');
You will need to put the messages in the DOM from the start, but without displaying them. Put these texts in span tags each with a unique id and the th:text attribute -- you could add them at the end of your document:
<span id="alertUpdateTable" th:text="#{listTable.updateTable}"
style="display:none">Update the Table.</span>
This will ensure that your internationalisation module will do its magic also on this element, and the text will be translated, even though it is not displayed.
Then at the moment you want to use that alert, get that hidden text and inject it where you need it:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + $('#alertUpdateTable').html() + '</p></div>');
You asked for another variant of this, where you currently have:
$successSpan.html(tableItemCount + " item was deleted from the table.", 2000);
You would then add this content again as a non-displayed span with a placeholder for the count:
<span id="alertTableItemDeleted" th:text="#{listTable.itemDeleted}"
style="display:none">{1} item(s) were deleted from the table.</span>
You should make sure that your translations also use the placeholder.
Then use it as follows, replacing the placeholder at run-time:
$successSpan.html($('#alertTableItemDeleted').html().replace('{1}', tableItemCount));
You could make a function to deal with the replacement of such placeholders:
function getMsg(id) {
var txt = $('#' + id).html();
for (var i = 1; i < arguments.length; i++) {
txt = txt.replace('{' + i + '}', arguments[i]);
}
return txt;
}
And then the two examples would be written as follows:
$('#TableUpdate-notification').html(
'<div class="alert"><p>' + getMsg('alertUpdateTable') + '</p></div>');
$successSpan.html(getMsg('alertTableItemDeleted', tableItemCount));

Converting String to HTML - string to " a href" element

Hello I am having some trouble getting some HTML links to add to my HTML page. I have tried searching around but nothing has helped thus far.
My page will initially load a snippet:
<div style="display: inline-block; color: rgb(0, 255, 144)">Roster: </div>
<span id="teamRoster"></span>
<br />
Which appears like Roster: in the View
Right now my snippet has been modified to add names:
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + teamRoster[i] + ", ";
}
$("#teamRoster").text(rosterListings);
Which will update my View to Roster: John, Frank, Susan, ect..
However, I am trying to now add <a href> tag's around each person and turn them all into actual links. My attempt looks like this
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
}
$("#teamRoster").text(rosterListings);
which displays as
Roster: <a href='#'>John</a>, <a href='#'>Frank</a>, ect..
I understand why this occurring since I am setting actual text/strings, but is there a way to convert this string into HTML elements? I have tried a few $.parseHTML code snippets that I found from Googling but I must be implementing them all wrong.. :(
Any help appreciated, Thank you!
Well, solution is quite obvious
Just replace
$("#teamRoster").text(rosterListings);
With:
$("#teamRoster").html(rosterListings);
Because if you use it as a text then it will treat it as the text and if you write html then it will treat it as a html
The problem is that you're using .text(), which will insert only text into the span, as seen here.
You need to use .html() if you want what is inserted to actually render as HTML.
So, try this:
$("#teamRoster").html(rosterListings);
Demo
Also note that the way you've set up your for loop causes an extra comma to be placed at the end of the list; I've fixed that here by checking whether it's the last element:
if (i !== teamRoster.length - 1) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
} else {
rosterListings = rosterListings + " and <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>.";
}
As Just code points out, you want to use the html method, not the text method. html() is jQuery's wrapper for innerHTML, which injects the string as html.
Here is a jsFiddle showing the difference:
http://jsfiddle.net/89nxt/
$("#teamRosterHtml").html("<a href='#'>John</a> <a href='#'>Frank</a>");
$("#teamRosterText").text("<a href='#'>John</a> <a href='#'>Frank</a>");

$.each pass value to function

I don't know how to search this problem in Stackoverflow it gives different solutions and does not relate to my problem. So I'll be needing your help again guys.
Values of variable obj:
item.title = Title1 and Title2
item.description = Description1 and Description2
HTML FILE:
function test_pop() {
var fb_id = "xxxxxxxxxxxx";
var v_id = "xxxxxxxx";
$.post('http://mysite.com/myfile.php', {fb_id: fb_id, v_id: v_id}, function(data) {
var obj = $.parseJSON(data);
$.each(obj,function(index, item){
achievement = "You Obtained " + item.title + " " + item.description;
achievement_pop(achievement);
});
});
}
achievement_pop function:
function achievement_pop(data) {
$("#achievement_popup").html(data).show(); //DIV that should show up
}
So the problem is, when the div shows up, it only outputs:
<div> <!-- Imagine that this content is inside a DIV -->
**You Obtained Title2 Description2**
</div>
But my desire output is:
<div> <!-- Imagine that this content is inside a DIV -->
**You Obtained Title1 Description1**
**You Obtained Title2 Description2**
</div>
Hope you guys help me, thanks.
the html function is replacing the whole content of the div, it's not just adding.
A solution would be to replace
$("#achievement_popup").html(data).show();
with
$("#achievement_popup").html($("#achievement_popup").html()+data).show();
But it's a little heavy. Personally I would first build the html and use the html function only once.
Use append() to add to end of element and not replace the content completely with html()
Or if you want to replace the existing content with all the new content at once:
/* start with empty string*/
var achievement='';
$.each(obj,function(index, item){
/* add to string on each pass of loop - can use any html you want here*/
achievement += "You Obtained " + item.title + " " + item.description +'<br>';
});
/* update element once all data parsed*/
achievement_pop(achievement);
Parsing to string and making one update is the most efficient from processing standpoint

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