How to Add Feeling Lucky Widget to Blogger

Posted by Lasantha Bandara on August 3rd, 2017 File Under : post, widget2 Comments

When a visitor click on the Feeling Lucky widget on your blog, he/she will be automatically redirected to a random post on your blog. You can add this widget into your blog in few seconds. Just go to "Layout" page and add the code given below into a "HTML/JavaScript" box and click save.

<style type='text/css'>
#myLuckyPost a{display:block;background:#333 !important;color:#fff !important;text-align:center;padding:6px 10px;text-decoration:none !important;text-transform:uppercase;}
</style>
<div id="myLuckyPost"></div>
<script type="text/javascript">
    function showLucky(root) {
        var feed = root.feed;
        var entries = feed.entry || [];
        var entry = feed.entry[0];
        for (var j = 0; j < entry.link.length; ++j) {
            if (entry.link[j].rel == 'alternate') {
                window.location = entry.link[j].href;
            }
        }
    }

    function fetchLuck(luck) {
        script = document.createElement('script');
        script.src = '/feeds/posts/summary?start-index=' + luck + '&max-results=1&alt=json-in-script&callback=showLucky';
        script.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    function feelingLucky(root) {
        var feed = root.feed;
        var total = parseInt(feed.openSearch$totalResults.$t, 10);
        var luckyNumber = Math.floor(Math.random() * total);
        luckyNumber++;
        a = document.createElement('a');
        a.href = '#random';
        a.rel = luckyNumber;
        a.onclick = function() {
            fetchLuck(this.rel);
        };
        a.innerHTML = 'Are you feeling lucky?';
        document.getElementById('myLuckyPost').appendChild(a);
    }
</script>
<script src="/feeds/posts/summary?max-results=0&alt=json-in-script&callback=feelingLucky"></script>

Refresh your site and click on the widget to see how it works.

File Under : post, widget

2 Responses to “How to Add Feeling Lucky Widget to Blogger”

  1. Rehan Khan says:

    Thanks for sharing this useful script 🙂

  2. GMTreg says:

    Thank you!

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.