A Better Way to Display Random Jekyll Posts on Page Load or Refresh Using jQuery and JSON

• Updated March 17, 2019


In a previous post I described how to display random Jekyll posts during each page load or refresh using Javascript. This post will produce the same result but will achieve it with jQuery and JSON.

The JSON File

Because Jekyll is a static-site generator, you do not have a database to query. For this whole thing to work, you need some sort of file to search through. This is where JSON comes in.

Jekyll will generate a JSON file that will contain every post with its associative metadata.

Create file search.json in your root Jekyll directory with the following contents:

---
---
[
    {% for post in site.posts %}
    {
      "title"    : "{{ post.title }}",
      "href"     : "{{ post.url }}",
      "date"     : {
         "day"   : "{{ post.date | date: "%d" }}",
         "month" : "{{ post.date | date: "%B" }}",
         "year"  : "{{ post.date | date: "%Y" }}"
      }
    }
    {% unless forloop.last %},{% endunless %}
    {% endfor %}
]

Each time you run jekyll build, a search.json file will be generated in the Jekyll _site folder containing all your posts and their associative metadata that you can search through using jQuery.

The jQuery Code

First, make sure you have already loaded the jQuery library within the head tags of your website (the missing http: in the URL is not a typo):

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>

Second, put the following jQuery code within the head tags of your website (modify the numberOfPosts variable depending on how many posts you want displayed):

<script type="text/javascript">

    function generateRandomPosts()
    {
        $.getJSON("/search.json", function(data) {
            console.log("[search.json loaded for random posts]");

            var postsCount = data.length;
            var posts = data;

            var randomIndexUsed = [];
            var counter = 0;
            var numberOfPosts = 5;

            var divRandomPosts = $("#random_posts");

            divRandomPosts.append('<h2>other posts</h2><hr />');

            while (counter < numberOfPosts)
            {
                var randomIndex = Math.floor(Math.random() * postsCount);

                if (randomIndexUsed.indexOf(randomIndex) == "-1")
                {
                    var postHREF = posts[randomIndex].href;
                    var postTitle = posts[randomIndex].title;

                    if (counter == (numberOfPosts - 1))
                    {
                        divRandomPosts.append('<p><a href="' + postHREF + '">' + postTitle + '</a></p>');
                    }
                    else
                    {
                        divRandomPosts.append('<p><a href="' + postHREF + '">' + postTitle + '</a></p><hr />');
                    }

                    randomIndexUsed.push(randomIndex);

                    counter++;
                }
            }
        });
    }

    $(document).ready(function() {
        generateRandomPosts();
    });

</script>

On each page load or refresh the generateRandomPosts function will run and append HTML to the random_posts div.

The HTML Markup

Put the following HTML markup within the body tags where you want the randomized list of posts to appear on your website:

<div id="random_posts">
</div>

Once the above Liquid, jQuery, and HTML is in place, run jekyll build, and re-upload the generated website to your webserver. With each page load or refresh, a random list of posts will be displayed.

References

If you found this post useful, you can help support this site and get something for yourself by signing up for any of the services listed below through the provided links.

The following links are part of affiliate programs, and I will receive a referral payment from any of the services you sign-up for.

  • Get Faster Shipping: Perhaps you're about to order some stuff on Amazon but want to get more value out of the money you would normally pay for shipping. Sign-up for a free, 30-day trial of Amazon Prime to get free two-day shipping, access to thousands of movies and TV shows, and more.
  • Start Investing Now: Are you looking to start investing some of your disposable saved income? Get started by opening an account with Webull, where upon sign-up and opening a brokerage account with an initial deposit of at least $100 you will receive 1 stock valued (subject to change based on normal market movement) between $8 and $1600.

Thanks for reading and take care.