Because Jekyll is a static site generator it can be difficult to have various parts of your website be dynamic. For example, I wanted a side bar element to show a list of randomized posts. I found two methods here and here to go to a random Jekyll post by clicking a link, but nothing that displayed a randomized list of Jekyll posts. So, I adapted the Javascript code from the links into what I was looking for.
First, since there is not a database to query for the post titles and URLs, two Javascript arrays will be created to store and retrieve post titles and URLs.
Add the following Javascript and Liquid code within the head tags of your website’s default Jekyll template:
<script type="text/javascript">
var postsHREF = [{% for post in site.posts %}"{{ post.url }}"{% unless forloop.last %},{% endunless %}{% endfor %}];
var postsTitle = [{% for post in site.posts %}"{{ post.title }}"{% unless forloop.last %},{% endunless %}{% endfor %}];
</script>
Second, put the following Javascript code within the body tags where you want the randomized list of posts to appear on your website (modify the numberOfPosts variable depending on how many posts you want displayed):
<script type="text/javascript">
var randomIndexUsed = [];
var counter = 0;
var numberOfPosts = 5;
while (counter < numberOfPosts)
{
var randomIndex;
var postHREF;
var postTitle;
randomIndex = Math.floor(Math.random() * postsHREF.length);
if (randomIndexUsed.indexOf(randomIndex) == "-1")
{
postHREF = postsHREF[randomIndex];
postTitle = postsTitle[randomIndex];
if (counter == (numberOfPosts - 1))
{
document.write('<p><a href="' + postHREF + '">' + postTitle + '</a></p>');
}
else
{
document.write('<p><a href="' + postHREF + '">' + postTitle + '</a></p><hr />');
}
randomIndexUsed.push(randomIndex);
counter++;
}
}
</script>
Once the above Javascript and Liquid code 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.