How to Add a Random Post Button in Blogger

Posted by Lasantha Bandara File Under : post, widget

How to Add a Random Post Button in Blogger

Adding a Random Post button to your Blogger site is a fun and effective way to keep visitors engaged with your content. When clicked, this button sends users to a randomly selected blog post, encouraging them to discover articles they might have missed. In this tutorial, you'll learn how to easily add this feature to your blog using a simple copy-and-paste code.

Go to the "Layout" page of your Blogger blog, add the following code into an "HTML/JavaScript" gadget, and click Save.

<style>
#myLuckyPost {
  margin-bottom: 10px;
}
#myLuckyPost a {
  display: block;
  background: #333;
  color: #fff;
  text-shadow: none !important;
  text-align: center;
  padding: 6px 10px;
  text-decoration: none;
  text-transform: uppercase;
}
</style>

<div id="myLuckyPost">Loading random post...</div>

<script>
(function () {
  const container = document.getElementById("myLuckyPost");
  const FEED_URL = "/feeds/posts/summary";

  // === JSONP fallback logic ===
  window.showLucky = function (root) {
    const entry = (root.feed.entry || [])[0];
    if (!entry) {
      container.textContent = "No post found.";
      return;
    }
    const link = entry.link.find(l => l.rel === "alternate");
    if (link && link.href) {
      window.location.href = link.href;
    } else {
      container.textContent = "Post link not found.";
    }
  };

  window.feelingLucky = function (root) {
    const total = parseInt(root.feed.openSearch$totalResults.$t, 10);
    if (!total) {
      container.textContent = "No posts available.";
      return;
    }

    const luckyIndex = Math.floor(Math.random() * total) + 1;
    const a = document.createElement("a");
    a.href = "#";
    a.onclick = function () {
      const s = document.createElement("script");
      s.src = `${FEED_URL}?start-index=${luckyIndex}&max-results=1&alt=json-in-script&callback=showLucky`;
      document.head.appendChild(s);
      return false;
    };
    a.textContent = "Are you feeling lucky?";
    container.innerHTML = "";
    container.appendChild(a);
  };

  // === Try modern fetch to get total post count ===
  (async function tryFetch() {
    try {
      const res = await fetch(`${FEED_URL}?alt=json&max-results=0`);
      if (!res.ok) throw new Error("HTTP error " + res.status);
      const data = await res.json();
      const total = parseInt(data.feed.openSearch$totalResults.$t, 10);

      if (!total) {
        container.textContent = "No posts found.";
        return;
      }

      const luckyIndex = Math.floor(Math.random() * total) + 1;
      const postRes = await fetch(`${FEED_URL}?alt=json&start-index=${luckyIndex}&max-results=1`);
      if (!postRes.ok) throw new Error("Post fetch failed");

      const postData = await postRes.json();
      const entry = (postData.feed.entry || [])[0];
      if (!entry) {
        container.textContent = "Random post not found.";
        return;
      }

      const link = entry.link.find(l => l.rel === "alternate");
      if (!link || !link.href) {
        container.textContent = "Post URL missing.";
        return;
      }

      const a = document.createElement("a");
      a.href = link.href;
      a.textContent = "Are you feeling lucky?";
      container.innerHTML = "";
      container.appendChild(a);

    } catch (err) {
      console.warn("Fetch failed, using JSONP fallback:", err);
      const s = document.createElement("script");
      s.src = `${FEED_URL}?max-results=0&alt=json-in-script&callback=feelingLucky`;
      document.head.appendChild(s);
    }
  })();
})();
</script>

Refresh your site and click the "Are you feeling lucky?" button to see it in action.

2 thoughts on “How to Add a Random Post Button in Blogger

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.