My Brain on Code

Tumblr Recent Posts With Javascript

I recently moved the entirety of my site (save this blog) to using jekyll. I have to admit, it’s really nice and eases maintenance tenfold. One thing I wanted to do was have a recent posts feed on my front page. Luckily, tumblr has an API I took advantage of. With a little bit of jquery, I was able to write out the top 5 recent posts on this blog.

First, you must include your blogs tumblr api javascript. For this blog, I had to include the following:

<script type=text/javascript src=http://blog.mybrainoncode.com/api/read/json></script>

This will populate a variable called tumblr_api_read that we can use in the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script type=text/javascript>
    const recent_posts_count = 5;
    var tumblr_api_read = tumblr_api_read || null;
    if (tumblr_api_read != null) {
            var recentPostsHtml = "<ul>";
            for (var i = 0; i < recent_posts_count; i++) {
                    var url = tumblr_api_read.posts[i].url;
                    var title = tumblr_api_read.posts[i]["regular-title"];
                    recentPostsHtml += "<li><a href=" + url + ">" + title + "</a></li>";
            }
            recentPostsHtml += "</ul>";
            $("#recentPosts").append(recentPostsHtml);
    }
</script>

Then we can just put:

1
<div id="recentPosts"></div>

in our html and it’ll be populated with recent posts. There you have it! Quick and easy way to add a recent tumblr posts to your site.