Search code examples
javascriptjqueryjsonbloggerfeed

Identify the first and last two posts


I am using the script below to show the latest 5 posts on my Blogger blog. How can I wrap the first and last 2 posts in different div containers? Currently all the 5 posts are inside a wrapper container stored in the item variable:

<script type='text/javascript'>
  function mycallback(json) {
    for (var i = 0; i < json.feed.entry.length; i++) {
      for (var j = 0; j < json.feed.entry[i].link.length; j++) {
        if (json.feed.entry[i].link[j].rel == 'alternate') {
          var postUrl = json.feed.entry[i].link[j].href;
          break;
        }
      }
      var postTitle = json.feed.entry[i].title.$t;
      var postAuthor = json.feed.entry[i].author[0].name.$t;
      var postSummary = json.feed.entry[i].summary.$t;
      var entryShort = postSummary.substring(0,400);
      var entryEnd = entryShort.lastIndexOf(" ");
      var postContent = entryShort.substring(0, entryEnd) + '...';
      var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s1600/');
      var item = '<div class="wrapper"><img src="' + postImage + '"/><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><span>'+ postAuthor + '</span><p>' + postContent + '</p></div>';
      document.write(item);
    }
  }
</script>
<script src="/feeds/posts/summary?orderby=published&max-results=5&alt=json-in-script&callback=mycallback"></script>


Solution

  • More generic solution would not check for last and previous to last elements checking for 3 or 4 but should be based on total length of your posts (it can be 3 it can be 10000).

    Checks below should be place in your loop.

    if(i === 0 || i === 1)

    Always use === operator as it is typesafe. Also group your checks in a way that is easy to understand (check for first and second in one if and for last and previous to last in another if:

    if(i === json.feed.entry.length || i === json.feed.entry.length - 1) - this check is based on length of your entries, not some fixed value like 3 or 4.

    This way if your displayed entries value will change in future (to ex. 10), you don't need to adjust your code here. All code you write should strive to work without such adjustments when code it uses changes.