Writing a jQuery plugin – (part 2). Sample plugin.

To be breve I’ll write some sample code and quickly describe it afterwards. So what’s a plugin. Lets make a simple logging plugin that overrides the console.log function and prevents MSIE browser to throw an error when this function misses.

The thing I’d like to achieve is something like:

$.log(‘my message’);

when I call it from a pure jQuery code.

function log( msg ) {
   console.log && console.log(msg);
}

That code looks quite correct, but to make all this into a jQuery plugin will need something more.

(function(jquery) {

   var log = function( msg ) {
      console.log && console.log(msg);
   };

   jquery.log = log;

}(jQuery));

After that we can call the $.log function with success and to perform logging of everything we want into the Firebug’s console.

The simple technique used here is a JavaScript closure and simple exportation of the single function log.

Leave a Reply

Your email address will not be published. Required fields are marked *