Add random number to script source (Blogger JSON call)

364 Views Asked by At

I not at all familiar with Javascript. I have a script on Blogger for generating a link to a random post, but due to Blogger's restrictions, I can't get more than the latest 100 posts from the JSON call. I want to try to get around this by randomly assigning the starting point. The portion in question is:

<script src='/feeds/posts/summary?alt=json-in-script&amp;callback=rp_results_label&amp;start-index=200'/>

How can I replace that 200 with a randomly generated number?

Thank you

1

There are 1 best solutions below

2
Prayag Verma On

Utilizing the Math.random will help with achieving what you require. Also adding max-results=1 query parameter to the feed URL will limit the results to a single post. As we can't add Javascript variables directly in the script tag's src, we will have to load it via JavaScript.

<script>
var ascript = document.createElement('script');
ascript.src = '/feeds/posts/summary?alt=json-in-script&max-results=1&callback=rp_results_label&start-index=' + Math.floor(Math.random() * Math.floor(201));
ascript.async=true;
var loc = document.getElementsByTagName('script')[0]; loc.parentNode.insertBefore(ascript, loc);
</script>

You can replace 201 with any integer between 1 to (total number of published posts on the blog)+1