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.

Related posts:

  1. Writing a jQuery plugin – (part 1). Good practices!
  2. jQuery debug plugin
  3. jQuery CSS functions. Part 1 – offset()
This entry was posted in javascript, micro tutorial and tagged , , , , , . Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">