Create a jQuery Plugin For Social Networking
So I was thinking about making a jQuery plugin for a while now, and then the opportunity to guest write here showed up, and I thought I would combine the two and write a tutorial on making a jQuery plugin!
This is a plugin I actually just made, it will take a few input options that are, for the most part, your usernames to various social networking sites. The plugin handles the rest; creating all the links and building a nice list, complete with matching icons to everywhere you are on the web.
I thought this would be helpful to people just starting out with plugins, and make it easy for those who do not want to make sprites and pretty social lists. The icons used in this demo are from the beautiful Social Network Icon Pack by Rogie King of komodomedia.com.
Feel Free To Jump Around From Here
Here is a demo of what we will be making. jSocial Demo
Look cool? Sweet, let’s get started!
The first thing I am going to do is create the canvas where I want the icon list to appear. So in a new HTML file, make an HTML skeleton to include this,
<div> <div class="social"> <h2>Find Me Here Also!</h2> </div> </div> |
Very basic, the only things added are a wrapper to contain it all and the div with a class of ‘social’ that the plugin will latch onto when creating its list. The h2 tag can be there or not, I just wanted a title.
Now we know that we will want some styling, so go ahead and link to a style sheet in the head area, don’t worry we have not made it yet, that is coming up next;
And finally, we need to include the jQuery library of course. I prefer to call it from the Google CDN, a very fast and compressed version, so, still in the head area include this,
And because we will need access to our plugin, right after jQuery is called be sure to include our plugin we are about to build,
That is it for the HTML part, for now. Time to add a tad bit of CSS. So create a new file named “style.css” and drop it in a folder named “css”. We are only adding very basic styles right now to create our skeleton, so feel free to simply paste this in, or use your own.
body { background: #999; font-family: Helvetica Neue,Arial,Helvetica, sans-serif; font-size: 62.5%; } #wrapper { width: 440px; margin: 100px auto; border: 1px solid #555; -moz-border-radius: 10px; -webkit-border-radius: 10px; } :focus { outline: 0; } .social h2, .social_small h2 { text-align: center; font-size: 2.8em; margin: 5px 0; color: #DCDCDC; text-shadow: #919191 0px 0px 0px; font-family: Palatino,Palatino Linotype,Hoefler Text,Times, Times New Roman,serif; } |
This part is what will control the display properties of our list and its various options. You will notice two parts look very similar, this is because I chose to give the option of using either large, (32×32) or small (16×16) pixel icons.
/*========COMMON STYLING==================*/ .social ul, .social_small ul {list-style:none;margin:0 auto;padding:0;} .social ul.inlined, .social_small ul.inlined {float:left;} .social ul li{width:32px;height:32px;margin: 5px; text-indent:-9999px;} .social ul li a, .social_small ul li a{display:block;width:100%;height:100%;opacity: 0.8;-moz-opacity: 0.8;filter:alpha(opacity=80);} .social ul li a:hover, .social_small ul li a:hover{opacity: 1;-moz-opacity: 1;filter:alpha(opacity=1);} .social_small ul li{width:16px;height:16px;margin: 5px; text-indent:-9999px;} /*========SOCIAL LARGE SIZE===============*/ .social ul a.twitter, a.facebook, a.flickr, a.friendfeed, a.delicious, a.digg, a.lastfm, a.youtube, a.feed, a.linked-in{background:url(../images/social_icons.png);} .social ul a.twitter{background-position: 0px 0px;} .social ul a.facebook{background-position: 0px -42px;} .social ul a.flickr{background-position: 0px -84px;} .social ul a.friendfeed{background-position: 0px -126px;} .social ul a.delicious{background-position: 0px -168px;} .social ul a.digg{background-position: 0px -210px;} .social ul a.lastfm{background-position: 0px -252px;} .social ul a.linked-in{background-position: 0px -294px;} .social ul a.youtube{background-position: 0px -336px;} .social ul a.feed{background-position: 0px -378px;} /*========SOCIAL SMALL SIZE===============*/ .social_small ul a.twitter, .social_small ul a.facebook, .social_small ul a.flickr, .social_small ul a.friendfeed, .social_small ul a.delicious, .social_small ul a.digg, .social_small ul a.lastfm, .social_small ul a.youtube, .social_small ul a.feed, .social_small ul a.linked-in{background:url(../images/social_icons_small.png);} .social_small ul a.twitter{background-position: 0px 0px;} .social_small ul a.facebook{background-position: 0px -26px;} .social_small ul a.flickr{background-position: 0px -52px;} .social_small ul a.friendfeed{background-position: 0px -78px;} .social_small ul a.delicious{background-position: 0px -104px;} .social_small ul a.digg{background-position: 0px -130px;} .social_small ul a.lastfm{background-position: 0px -156px;} .social_small ul a.linked-in{background-position: 0px -182px;} .social_small ul a.youtube{background-position: 0px -208px;} .social_small ul a.feed{background-position: 0px -234px;} |
Be sure you create an images folder and download the sprite if you use this code as is.
One more thing, at the bottom of the page paste in this clearfix code. It is the best method I have found to cure those pesky floats.
/* http://sonspring.com/journal/clearing-floats */ html body * span.clear, html body * div.clear, html body * li.clear, html body * dd.clear{background:none;border:0;clear:both;display:block;float:none;font-size:0;list-style:none;margin:0;padding:0;overflow:hidden;visibility:hidden;width:0;height:0;} /* http://www.positioniseverything.net/easyclearing.html */ .clearfix:after{clear:both;content:'.';display:block;visibility:hidden;height:0;} .clearfix{display:inline-block;} * html .clearfix{height:1%;} .clearfix{display:block;} |
Great, now save that and we can move on to the super awesome fun stuff! If you have followed along how I did it, you should be looking at a page like this,

Sweet, now it is time to make some jQuery magic.
Now jQuery plugins for the most part all begin the same, and this is an ‘outline’ I keep handy, so paste this into a new document named jquery.jsocial.js and put the file in a folder named ‘js’.
(function($) { $.fn.jsocial = function(options) { var options = $.extend({ },options); return this.each(function() { }); //end each } //end function })(jQuery); |
Ok it looks funny I know, so let’s walk through it.
First line simply opens the function to extend jQuery, and assigns the ‘$’ alias, which is why we pass jQuery into itself at the bottom of the function. This aids in no-conflict.
Then we declare our function and plugin name, passing in the parameter options which will allow defaults to be overwritten. Inside the function jsocial we get started declaring the variable options and setting it equal to the jquery object extended, this is where we will create the default values that the user will have the ability to alter when calling the plugin itself.
We then return this.each, which is how jquery iterates over each element in the matched set before sending control back to the main page.
Adding Some Options
So let’s start by adding some options that can be edited. Because this plugin is for social site links, I am going to create the following options to begin with,
twitter : null, facebook : null, flickr : null, friendfeed : null, delicious : null, digg : null, lastfm : null, linked : null, youtube : null, feed : null |
You can guess what is happening here, the title of the option is on the left and separated by the colon is the default assigned value. I am setting them to ‘null’ to begin with so that if none are chosen, nothing is displayed.
I would also like to give the users a few more options, just some fun things that some folks hate messing with, or to make it easier. So, go ahead and add this to the list,
Note: The comma must be added to the feed item, and always the last item has no comma.
newPage : null, center : false, inline : false, small : false |
Almost self explanatory eh? The option newPage will cause the links to open up in a new page, some people love this, some do not. Center will cause the resulting list to be automatically centered inside its parent element.
Inline will change the list elements to float to the left, thus displaying in a horizontal fashion. And finally, small will use a mini size icon, 16×16 pixels instead of the default 32×32 pixel. Options are a good thing right?
Making It Work
Time to make all this stuff do something. The first thing I am going to do, because this was the best place I found to put it, is to check if the user wants a new page to open when the link is clicked. So we check for that and if so, set a variable to hold the target attribute.
if ( options.newPage ) { var target = 'target="_blank"'; }; |
We then cache the passed in jQuery object so we can refer to it simply as this. We also will create a variable named ‘list’ that we will build upon to create our list of social links.So inside the each function, create the variables like this,
var $this = $(this), total_links = 0, list = ' <ul class="social_links">';</ul> |
Notice the comma separating the declaration of two variables. The list variable now holds the very beginning of a list for us, which is an unordered list with a class of ‘social_links’ that we can grab later using CSS. The variable ‘total_links’ is a counter we will use to keep track of how many links are selected. More on that later.
After we declare the variables, we need to find out which options the user selected to display in the list, and add them accordingly. Begin with twitter like so,
if( options.twitter ) { list += ' <li><a class="twitter" href="http://twitter.com/' + options.twitter + '">Twitter</a></li> '; total_links ++; }; |
What happens here is we check to see if twitter is selected. The if statement returns true if ‘options.twitter’ has a value. We set it to ‘null’ initially, so unless the user specifies this if statement will return false and will not execute.
Assuming they chose to use twitter, we will add to the list variable a new list item. We set the list to hold a link pointing to twitter, and then grab the name the user passed in with options.twitter. We give it a class and then set the target if they chose the newPage option.
Finally we increment the total_links count and move on to check the next item.
The remaining list items operate the same way, except for the parts of the link that jQuery takes care of. Some links accept a user name, whereas some more detail to get you there.
Not everyone has a Facebook vanity URL, and places like Linked-In have a few different addresses to get to your profile. So insisting on one way would limit the availability of some people. Here is the complete list of social link checking.
if( options.twitter ) {list += ' <li><a class="twitter" href="http://twitter.com/' + options.twitter + '">Twitter</a></li> '; total_links ++;}; if( options.facebook ) {list += ' <li><a class="facebook" href="http://' + options.facebook + '">Facebook</a></li> '; total_links ++;}; if( options.flickr ) {list += ' <li><a class="flickr" href="http://flickr.com/' + options.flickr + '">Flickr</a></li> '; total_links ++;}; if( options.friendfeed ) {list += ' <li><a class="friendfeed" href="http://friendfeed.com/' + options.friendfeed + '">FriendFeed</a></li> '; total_links ++;}; if( options.delicious ) {list += ' <li><a class="delicious" href="http://delicious.com/' + options.delicious + '">Delicious</a></li> '; total_links ++;}; if( options.digg ) {list += ' <li><a class="digg" href="http://digg.com/users/' + options.digg + '">Digg</a></li> '; total_links ++;}; if( options.lastfm ) {list += ' <li><a class="lastfm" href="http://www.last.fm/user/' + options.lastfm + '">Last.FM</a></li> '; total_links ++;}; if( options.linked ) {list += ' <li><a class="linked-in" href="http://' + options.linked + '">Linked-In</a></li> '; total_links ++;}; if( options.youtube ) {list += ' <li><a class="youtube" href="http://' + options.youtube + '">YouTube</a></li> '; total_links ++;}; if( options.feed ) {list += ' <li><a class="feed" href="http://feeds.feedburner.com/' + options.feed + '">Feedburner</a></li> '; total_links ++;}; |
Well we have a complete list, so do not forget to close it! Add one last thing to the list variable and our basic list is complete.
list += ' '; |
Our final step to make this plugin work at its basic level is to actually add what we created to the DOM, handle that by pasting this in,
$this.append(list); |
The line here literally grabs our list variable that we have been building and appends it, meaning inserts it into the parent element at the end. If you wanted it at the top, ie before anything else, you could use prepend.
The reason we do it this way instead of appending each item as we go is that each call to append or prepend alters the browser DOM, and you want to keep that to a minimum to reduce errors and load times. So we build the complete list, then affect the DOM only once.
At this point our plugin should be working! Yay! You can preview it in your browser now, and if you followed what I did, you should see this,

Looks good, and works, but we should take care of the other options we offered here.
Remember we gave the option to display either inline, horizontally or vertically by default? Here we are going to check if the user wants the horizontal option, and if so apply a new CSS property to the list elements.
if ( options.inline ) { $('ul.social_links li').css('float','left'); }; |
Once again we use if to see if it is “true” that they selected the inline option, and then grab the ul with a class of social_links, find its list elements and add a float to it. We are now horizontal!
Small or big? Big or small? Let us see what they chose…
if ( options.small ) { $(this).removeClass('social').addClass('social_small'); }; |
Here we check the size choice and if they do not want the default large size, we remove the standard class and give it a new class for the itty bitty icons.
Our final option was to see if they wanted the plugin to automatically center their link list for them.
if ( options.center ) { if ( options.small) { $('ul.social_links').css('width', total_links*26); } else { $('ul.social_links').css('width', total_links*42); }; }; |
This is where our total_links variable comes into play. Remember the icon sizes are either 32×32 or 16×16 pixels. Each icon has a padding of 10 pixels. So if they chose the small icons, we know each one has a space requirement of 26 pixels, (16 width + 10 padding) and we multiply it by the number of links selected.
This gives us the total width of the completed list, and we set the width of the containing ul to this number, allowing the CSS property margin: 0 auto; to handle the centering. The same thing occurs if the small option was not check, the multiplication number simply changes.
And one last image of what we look like now with the standard size set, displaying inline as horizontal list and the auto center option chosen, we should look like this,

What Do You Think?
I hope this has been helpful not only on how to start making a basic plugin for jQuery, but maybe even use it to make your social lists! I plan on adding more to this actually, support for many more sites and some fun animations maybe. Please comment and let us know what you think and if you use it drop a link I would love to see. Thanks for stopping by!
Oh yeah, You can download the plugin from here.
