DEV Community

Yordi Verkroost
Yordi Verkroost

Posted on

Step-by-Step Guide: Random Post in Bear Blog

You might know the feeling. You've been writing for a while and have accumulated quite a few posts on your Bear blog. Then someone asks you which post they should read first. Of course, you know that you only write quality stuff, so the post you choose doesn't really matter.

In comes the Bear blog Random Post plugin!

Here is a step-by-step guide to implement this plugin on your own Bear blog:

  1. Add the following HTML code to the page where you want to show the link to a random blog post:

    <div id="random-post-all" style="display: none;">
      {{ posts }}
    </div>
    
    <span id="random-post" class="blurred">Random post: the post will show here when it's loaded.</span>
    
  2. Add the following script code to the footer directive (Settings > Header and footer directives):

    <script src="https://cdn.jsdelivr.net/gh/froodooo/bear-plugins@0.0.20/bear/random-post.js" data-prefix="" data-text=""></script>
    

    Options:

    • data-prefix: If set, this text is printed before the random blog post link. Otherwise, there is no prefix.
    • data-text: If set, this text is printed as the link text. Otherwise, the blog post title is used as the link text.

... and you're done!

Read on if you want to know how this works or if you want to host the JavaScript directly on your Bear blog instead of via my GitHub.

The Code

The script that powers this random post plugin is the following:

if (document.querySelector("body").classList.contains("home")) {
  const randomBlogPost = document
    .querySelector(".blog-posts")
    .children[Math.floor(Math.random() * document.querySelector(".blog-posts").children.length)];
  document.querySelector('#random-post-all').remove();
  document.querySelector('#random-post').innerHTML = `${document.currentScript.getAttribute("data-prefix") ?? ""}<a href='${randomBlogPost.children[1].href}'>${document.currentScript.getAttribute("data-text") ?? randomBlogPost.children[1].text}</a>`;
  document.querySelector('#random-post').classList.remove("blurred");
}
Enter fullscreen mode Exit fullscreen mode

The if statement ensures that this script only runs on your home page, and not anywhere else. When you put this entire script into your footer directive (in between <script></script> tags) and remove the if statement, the script will run on every page of your blog.

Inside the if statement, I use the embedded {{ post }} within an invisible div to retrieve all blog posts. Then a blog post is retrieved by randomly picking one from the full list. Finally, all blog posts are removed from the page and the element with the id #random-post is populated, using the data- attributes if they're set.

Top comments (0)