Adrian Esquivel
November 16, 2009

jQuery development: Your own plugins

Often there is a need for functionality that goes above jQuery's core set of methods, there are a host of plugins which can be used to attain this functionality. Such as ColorBox when a modal box is needed or jFlow for a basic gallery. However, sometimes these plugins cannot perform exactly the way we need them to without attacking the plugin's source and in the end causing a fair bit of frustration, confusion, and a plugin that not only doesn't do what you want but doesn't do anything. Solution? Develop your own plugin The benefits of this course are:

  • Extreme familiarization with the code base ( You wrote it! )
  • Makes for identifying the area where bugs are coming from a fair bit easier
  • You don't have to worry about licencing, you wrote it, it's yours.

The above being said, I suppose it's about time to get on to exactly how one goes about developing their own plugin and it's assuming familiarization with their core and some basic JavaScript it can be done rather easily. For the purpose of this blog post we'll be doing a plugin that transforms every YouTube link into a nice embedded video.First, we start off with a basic structure which is necessary to eliminate the possibility of Namespace conflicts ( libraries aside from jQuery make use of the dollar sign $ )(function($){})(jQuery)Now we must define our function, with jQuery however we'll be making use of closures or anonymous functions and than assign it to a variable. This is how:(function($){ $.fn.youtubualize = function(){ }})(jQuery)Now we get to the fun bits! jQuery feeds us a copy of itself ( available though the this supervariable ) ready to be manipulated, seeing as we'll most likely have more than 1 link we'll make use of jQuery's each utility to cycle through all the links.(function($){ $.fn.youtubualize = function(){ this.each(function(){ }); }})(jQuery)Now we must be away that within the callback we're providing to the each utility this is only a string representing the YouTube link so we need to use jQuery's CSS selectors to single out the element and modify it accordingly, this will be the most verbose part(function($){ $.fn.youtubualize = function(){ this.each(function(){ var url = String(this); var flvURL = url.replace('watch?v=','v/'); $('a[href="'+ url +'"]') .before('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" height="340" codebase=",0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="'+ flvURL +'&amp;hl=en&amp;fs=1&amp;" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="560" height="340" src="'+ flvURL +'&amp;hl=en&amp;fs=1&amp;" allowscriptaccess="always" allowfullscreen="true"></embed></object>') .remove(); }); }})(jQuery)