How to Make a Tumblr-powered News Ticker

Demo Download

Tumblr is a blogging service with an elegant interface for creating and publishing content. In this tutorial, we are going to use it as the foundation of a news publishing system. We are going to develop a simple widget which cycles through the most recent posts on a Tumblr blog, and presents them as news items to your users. Adding news will be done by creating new blog posts in your Tumblr dashboard.

Update: It looks like Tumblr has blocked the blog used in this tutorial. This is probably due to the large number of requests to the API. This should be resolved soon. In the mean time, you can try the example with your own blog by changing the blog parameter when calling the plugin.

The HTML

The code we are writing will be organized as a jQuery plugin, which will make it portable and easy to embed in an existing website. When the plugin is run, it will request the latest posts from your blog with AJAX, and will generate the following markup:

Generated Code

  <div class="tn-container">
    <h2 class="tn-header">Tumblr News Ticker</h2>

    <div class="tn-data">
      <ul>
        <li class="tn-post"><a href=
        "http://tzinenewsdemo.tumblr.com/post/41782608890" target="_blank">HTML5 Showcase
        for Web Developers: The Wow and the How</a> <span>about 20 hours ago</span></li>

        <li class="tn-post" style="display: list-item;"><a href=
        "http://tzinenewsdemo.tumblr.com/post/41782593600" target="_blank">The New jQuery
        Plugins Site is Live!</a> <span>about 20 hours ago</span></li>

        <li class="tn-post" style="display: list-item;"><a href=
        "http://tzinenewsdemo.tumblr.com/post/41782522976" target="_blank">Parsley.js - A
        Small JavaScript Forms Validation Library</a> <span>about 20 hours
        ago</span></li>

        <!-- More news items here -->

      </ul>
    </div>

    <div class="tn-footer"></div>
  </div>

The unordered list hosts the news items, but only 5 are shown at a time. The elements with the tn classes are styled by the plugin's stylesheet and you can customize them to match the design of your site.

tumblr-news-ticker-jquery.jpg

The JavaScript/jQuery Code

First, let's take a look at the response that we get from Tumblr, so you get a better idea of what data is made available to us.

Every Tumblr blog comes with a public JSON API. You simply have to add /api/read/json after the end of your blog URL to get a JSON object with your recent posts. This is a breath of fresh air compared to the direction Facebook and Twitter have taken their APIs, which require access tokens and registrations for even the simplest of use cases.

Example Response

{
    "tumblelog": {
        "title": "A web development news site",
        "description": "",
        "name": "tzinenewsdemo",
        "timezone": "US\/Eastern",
        "cname": false,
        "feeds": []
    },
    "posts-start": 0,
    "posts-total": 11,
    "posts-type": "regular",
    "posts": [{
        "id": "41782723088",
        "url": "http:\/\/tzinenewsdemo.tumblr.com\/post\/41782723088",
        "url-with-slug": "http:\/\/tzinenewsdemo.tumblr.com\/ ..",
        "type": "regular",
        "date-gmt": "2013-01-29 13:49:36 GMT",
        "date": "Tue, 29 Jan 2013 08:49:36",
        "bookmarklet": 0,
        "mobile": 0,
        "feed-item": "",
        "from-feed-id": 0,
        "unix-timestamp": 1359467376,
        "format": "html",
        "reblog-key": "zEQ0b5OB",
        "slug": "image-picker-jquery-plugin-that-turns-a-select",
        "regular-title": "Image Picker - jQuery plugin that turns a ..",
        "regular-body": "<p><a href=\"http:\/\/rvera.github.com\/image-picke .."
    }

    // More posts here

    ]
});

You get ids, dates, the title and the body, tags, photos and more. We will only use the title and the date in this example, but you can enhance it by adding more data.

And here is the plugin that will handle the AJAX requests, generate the markup, and cycle through the responses:

assets/js/jquery.tumblrNewsTicker.js

(function($) {

    var defaults = {
        time:   5000,
        title:  'Tumblr News Ticker',
        blog:   'http://tzinenewsdemo.tumblr.com'
    };

    $.fn.tumblrNewsTicker = function(options) {

        // Handle the default settings
        var settings = $.extend({}, defaults, options);

        // Remove trailing slashes and assemble the Tumblr API URL
        var url = settings.blog.replace(/\/$/,'') +
                  "/api/read/json?num=20&type=text&callback=?";

        this.append('<div class="tn-container">\
                        <h2 class="tn-header">'+ settings.title +'</h2>\
                        <div class="tn-data"><ul></ul></div>\
                        <div class="tn-footer"></div>\
                    </div>');

        var postList = this.find('.tn-data ul');

        //Get the posts as json
        $.getJSON(url, function(data) {
            $.each(data.posts, function(i,posts){ 

                // Remove any HTML tags
                var title = posts['regular-title'].replace(/<\/?[^>]+>/gi, '');

                // Calculate the human-readable relative time
                var time = $.timeago( new Date( posts['unix-timestamp'] * 1000 ) );

                postList.append('<li class="tn-post">\
                                    <a href="' + posts.url + '" target="_blank">'+title+' </a>\
                                    <span>' + time + '</span>\
                                </li>');
            });

            // Show the first 5 news items

            postList.find('li')
                    .slice(0,5)
                    .show()
                    .last()
                    .addClass('no-border');

            // Rotate posts every settings.time ms
            // (only if they are more than the limit)

            if(data.posts.length > 5) {

                setInterval(function() {

                    var posts =  postList.find('li');

                    posts.first().slideUp('slow', function() {
                        $(this).appendTo(postList);
                    })

                    posts.eq(4).removeClass('no-border');
                    posts.eq(5).slideDown('slow').addClass('no-border');

                }, settings.time);

            }

        });

        return this;

    };
})(jQuery);

First is generating the API URL. Notice that I am only selecting text posts. If you have published photos, videos or other types of content, they will not show. However you are free to change this line and remove the type=text parameter to select everything. Some content types do not return a title, so you should test it thoroughly.

To calculate the relative time string, I am using the timeago plugin. It returns a human-readable form of the passed time since the post was published. To construct the date object, I multiply the returned unix timestamp with 1000 to get the number of milliseconds (as required by the date object).

And here is how to call the plugin:

assets/js/script.js

$(function() {

    // Call the plugin

    $('#main').tumblrNewsTicker({
        time: 5000,
        title:  'Tumblr News Ticker',
        blog: 'http://tzinenewsdemo.tumblr.com/'
    }); 

});

All these arguments are optional, but you would most certainly want to pass a different blog url.

I am not going to present the CSS here, but you can find it in the assets/css/ folder.

Done!

With this, our news ticker is complete! You can modify this widget and embed it in you admin panel or blog sidebar. With some more coding you could combine it with the mini help system tutorial from last month, and get a fully functional and easy to update help system with real-time search.

Bootstrap Studio

The revolutionary web design tool for creating responsive websites and apps.

Learn more

Related Articles

Harrisson

It's amazing !
Always surprising my friend, thank you so much!

SMBaghdadRaza

Very Helpful, Thanks!

Well done man , thanks

Anh Saker

Awesome! thank martin

Hariharakumar

thanks for the tutorial, i will try this one

Thank for this one! Was looking for something like this :)

Mukesh Mali

thanks for the tutorial, i will try this one on my WordPress powered site .... i think this is working on my site....