Friday, October 23, 2015

Display "Post Titles" using Blogger JSON Feed

Display "Post Titles" using Blogger JSON Feed

Link to My Blogger Tricks

Display "Post Titles" using Blogger JSON Feed

Posted: 23 Oct 2015 07:35 AM PDT

blogger recent posts widgetIn Part#4 we discussed how to extract "Labels List" data from Blogger JSON feed API and print this list with hyperlinks. Today we will extract Post Titles from BlogSpot JSON feed by parsing the data in JavaScript, in other words we are creating the "Recent Posts widget" that will only display titles. Exact same approach and technique will be used. We are trying to make sure we discuss data extraction in simple steps through various tutorials before you could actually build a useful widget like a "recent posts widget" that could display Titles, Labels, Comment count, Thumbnail image and timestamp. Lets get straight to work!

Note: Click the Button below to see full list of topics under discussion.

Topics List

Where is "Title String" and "Title URL" stored?

The Post Title String is stored inside the [ ] entry array followed by { } title object node as shown in the screenshot below.

title string is stored here


To extract the Title string we will follow this path:

json.feed.entry[i].title.$t

Which means:

  • First go to json object
  • then feed object
  • then entry array. For array it is important to mention which element ID are we looking for that's why we expressed it as entry[i].
  • then finally extract the data from the branch $t inside title object

To extract the Title Link or URL we will follow this path:

json.feed.entry[i].link[j].href

Title link stored here

As you can observe the title href attribute is located inside the array [ ] link and on its 4th ID          i.e.{ } 4.

Since it is not important that href value might exist inside the fourth array element always therefore we will make sure to extract href value of only that node which contains the rel: "alternate" name/value pair.  

Since [ ] link node is an array itself that is why we expressed it as link[j] so to make sure which element ID of link are we accessing.

I hope you now know where each data exists. Lets write the script now to display recent post titles.

Retrieving Recent Posts Titles

Following is the complete JavaScript code that will extract recent Post titles from the JSON feed and print the list:

<!-- ######### Writing Callback Function ############# -->

<script type="text/javascript">

//----------------------------Defaults

var ListBlogLink = window.location.hostname;
var ListCount = 5;
var TitleCount = 70;

//----------------------------Function Start
function mbtlist(json) {
document.write('<ul class="mbtlist">');
for (var i = 0; i < ListCount; i++)
{
  
//-----------------------------Variables Declared

var listing= ListUrl = ListTitle =  "";

//----------------------------- Title URL
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
      if (json.feed.entry[i].link[j].rel == 'alternate') {
        break;
      }
    }
ListUrl= "'" + json.feed.entry[i].link[j].href + "'";

//----------------------------------- Title Stirng
if (json.feed.entry[i].title!= null)
{
ListTitle= json.feed.entry[i].title.$t.substr(0, TitleCount);
}

//----------------------------------- Printing List

var listing = "<li><a class='mbttitle' href="
+ListUrl+
"target='_blank'>"
+ListTitle+
"</a></li>";
document.write(listing);
}
document.write("</ul>");
}
</script>

<!-- ######### Invoking the Callback Function ############# -->

<script>
ListBlogLink = "http://www.mybloggertricks.com";
ListCount = 8;
TitleCount = 70;

document.write("<script src='"+ListBlogLink+"/feeds/posts/default?alt=json-in-script&callback=mbtlist'></"+"script>");
</script>

<!-- ######### Styles for Look ############# -->

<link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'/>
<style>
.mbtlist {list-style-type:none;overflow:hidden}
.mbtlist li {margin:0px auto 20px auto; clear:both; color:#666; font-family:Helvetica; font-size:12px; border-bottom:1px dotted #ddd;}
.mbtlist .mbttitle {font-family:oswald; font-size:16px; color:#0080ff; font-weight:normal; text-decoration:none;}
.mbtlist .mbttitle:hover  {color:#00A5FF;}
font-family:georgia; font-size:15px; font-weight:bold}
</style>

 

As you know we have divided the above script in three parts and I will discuss it accordingly

1. Writing the Callback Function

1 Here we first declared some default values to variables. In order

  • ListBlogLink will fetch the Browser address URL if no blog link is mentioned;
  • ListCount will display the 5 latest posts recently published.
  • TitleCount will cut/chop the title if it's length exceeds 70 characters.

Note that the user can customize these options by re-setting them during Invoking. If incase the user does not mention any values the defaults will be used.

2 Next since we are printing the Title list we therefore first printed <ul class="mbtlist"> just before starting the function.

3 We then started a for Loop from 0 till the user assigned List count.

for (var i = 0; i < ListCount; i++)

4 After declaring some variables for printing the list, Title and title URL we started our first loop to fetch the "Title URL"

for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
break;
}
}
ListUrl= "'" + json.feed.entry[i].link[j].href + "'";

  • We first run a loop from 0 till the full length of [ ] link
  • We then run a condition to check if rel has value "alternate". If the value didn't match, the loop will end rendering else it will continue to fetch the href value in that node.
  • the value of href (i.e. Title URL ) fetched is then stored inside ListUrl

5 Next we wrote the script to extract the Title String i.e. Title text.

if (json.feed.entry[i].title!= null)
{
ListTitle= json.feed.entry[i].title.$t.substr(0, TitleCount);
}
  • We first test a condition to see if Title is not empty. This is important because if you publish an article without a title in your blog then the above script will crash and wont work. Therefore this condition will make sure to fetch the Title string only when the title exists for a post.
  • We then extracted the title text and stored it inside ListTitle
  • In order to make sure the title length is not too long, we used a JavaScript String substr() method  to display only the first few characters up to the length mentioned in TitleCount

 

INFO
The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.

6 Later we printed the list inside <li> tags using the variable listing

7 Finally we closed the unordered list outside the first loop using

document.write("</ul>");

Note that the entire data is extracted and printed inside <li> tags. The loop which is fetching and printing the list is this:

<ul> tag is printed here

for (var i = 0; i < ListCount; i++)

{

<li> tags are printed here

}

</ul> tag is printed here

This loop itself is enclosed inside the <ul> and </ul> tag. Thus the Recent Posts are displayed! :)

2. Invoking the callback Function

You might have noticed that this time the invoking section of the code looks a little unfamiliar. Previously:

<script type="text/javascript" src="http://www.mybloggertricks.com/feeds/posts/default?alt=json-in-script&callback=mbtlist">
</script>

Now:

document.write("<script src='"+ListBlogLink+"/feeds/posts/default?alt=json-in-script&callback=mbtlist'></"+"script>");

We simply printed the Inline JavaScript code inside a document.write() function just to give our widget a more dynamic control. This way we can assign variables inside the Invoking section and give more control to the user. This makes the code easy for the user who can then easily assign custom values for ListBlogLink , ListCount and TitleCount .

3. Defining CSS Styles

No one would like a dull and grey list unless you add some custom colors to it.

recent posts with styles

Without the style sheet the widget will look like this:

recent posts without styles


I am sure no one would like it without colors therefore in the last part we added some CSS touch to the list! :)

Have Questions?

I tried my best to make it as simple as possible, if incase you could not understand any step, feel free to ask your question by posting your comment below.

In our next tutorial, we will explain how to display recent posts by specifying a Label. Recent Titles will display based on the category specified by the user. Happy weekend buddies! =>

Share:

0 comments:

Post a Comment