• RSS
  • Print this article!
  • Digg
  • del.icio.us
  • DZone
  • Facebook
  • Mixx
  • Google Bookmarks
  • Design Float
  • Reddit
  • StumbleUpon
  • Technorati
  • Live
  • TwitThis
Home > Front End Development, How to, Javascript > How To Create A Twitter jQuery Plugin

How To Create A Twitter jQuery Plugin

June 13th, 2009

Have you ever wanted to create a jQuery plugin? Or put your Twitter feed on your website?  If so this is the tutorial for you.

Sure there are already plugins out there that can put a Twitter feed on your homepage, but where is the fun in that.  This tutorial will help you build one for your own, and show you the ropes of creating a jQuery plugin.

Starting Off

First thing is first, to make a jQuery plugin, you need jQuery.  You can just visit jQuery’s website and download the latest version. Personally I like linking straight to the latest version which lives on their site.

HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>

    <head>
        <!-- Import Jquery -->
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    </head>
   
   
    <body>
        <div id="tweets"></div>
    </body>
   
</html>

You’ll notice that in the body of the HTML I have a div with the id of “tweets”.  This will be where your tweets will show up.  You don’t have to necessarily use a div with this id, you can use whatever you like as long as you adjust your jQuery accordingly.

Basic jQuery Plugin

Lets build a basic jQuery plugin.  There really isn’t that much too it.

jQuery:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// This is a self invoking function.
// The $ parameter allows you to reference the jQuery item.
(function($){

    // fn is essentially the same as prototype.
    // so this will be used like $('#jqueryItem').twitterize(username)
    $.fn.twitterize = function(username,options){
       
        //Return itself
        return this;
   
    };
   

// We pass "jQuery" to the self invoking function
// so we can use whatever alias of jQeury that we like.
// So instead of "$" you could also use any other
// valid JavaScript variable name.
})(jQuery);

If you don’t fully understand why you need this code, not to worry, just take it at face value.  Just know this is what you need at least to make a plugin.  If you don’t want to use the name twitterize feel free to change it to whatever you like. Whatever you change it to that is how you will access it.

Default Settings

This is a very simple plugin, so we won’t need many settings.  The main ones will be the username, and how many tweets you want to get.  You can add a bunch more if you like (photo, callback…etc), for purposes of keeping it simple I’ll just keep to the basics.

jQuery:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
(function($){

    $.fn.twitterize = function(username,options){
       
        //check to see if the username has been set.
        if (username){
           
           
            //create an object full of your default settings.
            var defaultSettings = {
                count:'1'
            }
           
           
            // Finds which default settings have been overwritten by the options object
            // and creates a new object with all the new and untouched settings.
            var settings = $.extend(defaultSettings, options);
       
           
        }else{
            //Username paramater has not been set.
            console.debug("jquery plugin twitterize requires a username! Check your parameters");
   
        }
   
       
        return this;
   
    };

})(jQuery);

Contacting Twitter

Now the magic happens.  This is where you will contact Twitter via JSON and get back your latest tweet.

jQuery:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
(function($){  
$.fn.twitterize = function(username,options){
       
       
        if (username){
           
           
            var defaultSettings = {
                count:'1'
            }
           
            var settings = $.extend(defaultSettings, options);
       
            // The URL for the Twitter JSON API.
            var url = "http://twitter.com/status/user_timeline/"+username+".json?count="+settings.count+"&callback=?";
           
            //Variable to get around scope problem in callback function.
            var holder = this;
           
            //Contact Twitter
            $.getJSON(url,
           
            //This function is called when twitter responds with the appropriate information.
            function(data){
               
                //Step through each tweet.
                $.each(data, function(i, item) {
                   
                    //place the tweet within a paragraph tag within the main div.
                    holder.append("<p>"+item.text.makeLinks()+"</p>");
       
                });
            });
           
        }else{
           
            console.debug("jquery plugin twitterize requires a username! Check your parameters");
   
        }
       
       
        //Changes urls within the tweet into links.
        String.prototype.makeLinks = function() {
            return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(str) {
            return str.link(str);
            });
        };
   
       
   
    return this;
   
    };

})(jQuery);

You might have noticed the makeLinks function.  This simply changes any urls in your tweets into links.  It uses regular expressions to find the link, then uses the link method to change it into an anchor tag.

Call Your jQuery Plugin

All the hard work is done.  Now you just have to import the plugin and call it in your HTML file.

HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<html>
    <head>
       
    <!-- Import Jquery -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
   
    <!-- Import Plugin -->
    <script src="twitterize.jquery.js" type="text/javascript" charset="utf-8"></script>
   
    <script type="text/javascript" charset="utf-8">
   
        $(document).ready(function() {
           
            //This is how we call the plugin
            $('#tweets').twitterize('Devirtuoso');
           
        });
   
    </script>  
    </head>
   
    <body>
        <div id="tweets"></div>
    </body>

</html>

Here is the final plugin:

jQuery:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
(function($){

$.fn.twitterize = function(username,options){
   
    if (username){

        var defaultSettings = {
            count:'1'
        }
        var settings = $.extend(defaultSettings, options);

        var url = "http://twitter.com/status/user_timeline/"+username+".json?count="+settings.count+"&callback=?";

        var holder = this;
       
        $.getJSON(url,
        function(data){

            $.each(data, function(i, item) {

                holder.append("<p>"+item.text.makeLinks()+"</p>");
   
            });
        });
       
    }else{

        console.debug("jquery plugin twitterize requires a username! Check your parameters");

    }
   
    String.prototype.makeLinks = function() {
        return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(str) {
        return str.link(str);
        });
    };

   
return this;

};

})(jQuery);

Here is a working example of my twitter page : Simple Example

That’s it. All that is left is to dress up it up however you like it. Happy Twittering.

  • RSS
  • Print this article!
  • Digg
  • del.icio.us
  • DZone
  • Facebook
  • Mixx
  • Google Bookmarks
  • Design Float
  • Reddit
  • StumbleUpon
  • Technorati
  • Live
  • TwitThis
  1. EllisGL
    June 14th, 2009 at 01:49 | #1

    I tend to use Google for my jQuery link. Also could we see an example?

  2. June 14th, 2009 at 10:07 | #2

    Good Call. I’ll throw one up.

  3. June 15th, 2009 at 09:13 | #3

    Fantastic tutorial! I really will have to get off my butt and make some slick posts like this – maybe a tutorial on how to make a Twitter library for CodeIgniter that does a similar thing to your jQuery plugin here :)

  4. June 15th, 2009 at 11:45 | #4

    Do it up. I’d read an article on CodeIgniter. Drop a line here if and when you do it so we can check it out.

  5. June 16th, 2009 at 12:40 | #5

    I’m getting a Javascript error from Firebug in the last line of the plugin? “Incorrect syntax”? Any ideas?

  6. June 16th, 2009 at 12:55 | #6

    @Gabe
    I’m guessing it was something in the code in the post, when I get the plugin from the demo page, it works. Thanks for the post!

  7. June 16th, 2009 at 12:57 | #7

    Probably a typo. I’ll look into this. Thanks Gabe.

  8. June 16th, 2009 at 13:05 | #8

    Sure enough. I forgot the “(function($){” at the top of the jQuery. It’s all fixed now.

  9. Grouchy Smurf
    June 16th, 2009 at 17:09 | #9

    This script won’t work for a long time, Twitter limits its API usage : http://apiwiki.twitter.com/Rate-limiting
    It’s far better to do this on server-side with some cache.

  10. June 16th, 2009 at 17:40 | #10

    True, Twitter gives you 100 hits per hour. If you need more you can fill out there white-listing form which gives you 20000 hits per hour. If you’re past that you definitely need to cache.

  11. eheh
    October 8th, 2009 at 17:53 | #11

    admin :
    Probably a typo. I’ll look into this. Thanks Gabe.

    Scott – Beyond Coding :
    Fantastic tutorial! I really will have to get off my butt and make some slick posts like this – maybe a tutorial on how to make a Twitter library for CodeIgniter that does a similar thing to your jQuery plugin here

Comments are closed.