I would like to show random posts to my blogger.
I got a javascript from googling and tried it, but the number of random posts are not correct (should be 10 but sometimes 4, sometimes 2, etc). I tried to check what's happening and found out that json.feed.entry [500] throws error.
Here is the javascript that I used
<script type="text/javascript">
function randomposts(json) {
var randarray = new Array();
var l=0;
var flag;
var numofpost=10;
var total = parseInt(json.feed.openSearch$totalResults.$t,10);
for(var i=0;i < numofpost;) {
flag=0;
randarray.length=numofpost;
l=Math.floor(Math.random()*total);
for(j in randarray){
if(l==randarray[j]){
flag=1;}
}
if(flag==0&&l!=0){
randarray[i++]=l;
}
}
// correct output
// alert(randarray);
document.write('<ul>');
// dummy for testing 500 limit
//for (var x = 0; x < numofpost; x++) {
// randarray[x]= 495 + x;
//}
for(var n in randarray){
var p=randarray[n];
var entry=json.feed.entry[p-1];
var posttitle = entry.title.$t;
for(var k=0; k < entry.link.length; k++){
if(entry.link[k].rel=='alternate'){
document.write('<li> ' + posttitle.link(entry.link[k].href) + '</li>');
}
}
}
document.write('</ul>');
}
</script>
<script src="/feeds/posts/default?alt=json-in-script&start-index=1&max-results=1000&callback=randomposts" type="text/javascript"></script>
Currently I set var total = 500;
so that the random works only for first 500 posts.
How to solve this issue?
UPDATE: I added try catch block and the error is TypeError: Cannot read property 'title' of undefined
UPDATE 2: The following picture is snapshot of console. The json.feed.entry 500 is undefined.