Wednesday, January 23, 2008

Add post randomizer for blogger

When your blog post came up to the hundreds or even thousands, one day you'd want to let people click on random post. Or, maybe if your blog is a personal blog, and not a spam blog that aims only to suck traffic, you might one day want to flip thru your blog randomly, just like when you speed read thru your personal diary.

There are many ways to add this capabilities to blogger. One popular way is by adding a random I'm feeling lucky widget to your blog. However, I find that these clickable links are best put near your navigation buttons, not somewhere in your sidebar. In blogger, that is the older post, newer post and home button. Besides, it looks horrible to see a lone navigation button hovering in the middle of those stuff on the right.

So, what other ways can we use to achieve this? The most obvious is a blogger hack. I have sampled several blogger hacks that allowed this, however, some would get deleted if you change some layout and stuff on blogger. This hack has survived several blogger changes.

So, what you do, is, edit your templat HTML, make sure that expand widgets is selected, then add the following right before the </head> tag.

<script type="text/javascript">
//<![CDATA[
var _yourBlogUrl = "http://insertblogurl.blogspot.com";
function randomPost() {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
var theUrl = _yourBlogUrl
+"/feeds/posts/summary?alt=json-in-script&callback=getTotalPostsCallback&start-index=1&max-results=1";
script.setAttribute("src", theUrl);
document.documentElement.firstChild.appendChild(script);
};

function getTotalPostsCallback(json) {
var totalResults = json.feed.openSearch$totalResults.$t;
if (totalResults > 0) {
getRandomPostNumber(totalResults);
}
};

function getRandomPostNumber(totalResults) {
var randomNumber = Math.floor((Math.random() * totalResults)
+ 1);
getRandomUrl(randomNumber);
};

function getRandomUrl(randomNumber) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
var theUrl = _yourBlogUrl
+"/feeds/posts/summary?alt=json-in-script&callback=getTheUrlCallback&start-index="
+ randomNumber + "&max-results=1";
script.setAttribute("src", theUrl);
document.documentElement.firstChild.appendChild(script);
};

function getTheUrlCallback(json) {
var theUrl = json.feed.entry[0].link[0].href;
window.location.href = theUrl;
}
//]]>
</script>
And then, add the following where you'd like the random link to appear in your blog.
<a href="javascript:randomPost();">View Random Post</a>
In my blog, I put it under
<div class='blog-pager' id='blog-pager'>
Please thank Purple Moggy for creating this code. :)


1 comments:

Anonymous said...

Oh so close! This is exactly what I've been looking for but it doesn't seem to work on my blog or yours either.
Truthfully I would love to have this work in the post navigation instead of "older post".
Any ideas?