Display Random Post

Ever wanted a way to display a random post? Well, now you can :D

First, add the following javascript to your page's header (Template -> Edit HTML) -> (above tags </head>)



<script type="text/javascript">
//<![CDATA[
var _yourBlogUrl = "http://purplemoggy.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>



Make sure to replace the _yourBlogUrl variable with your blog's URL.

Then just add the following link anywhere in your page


View Random Post




source:http://purplemoggy.blogspot.com