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.




Top