JQuery, create your own plugin

First of all let’s start with basic rule and it’s also a best practice when you write JQuery Plugins : to make sure that what you are writing doesn’t make conflicts with others libraries use JQuery instead of “$” in the plugin declaration :

(function( $ ){

  $.fn.highlight = function() {
    ..
  };
})( jQuery );

instead of :

$.fn.highlight = function(){ .. }

Okey now we have the minimal code for a JQuery Plugin, let’s continue with some other stuffs

(function( $ ){

  $.fn.highlight = function() {
    //refers the object where plugin was called.
    console.log($(this));
  };
})( jQuery );

If you run this within a html code like this :

<body>
  <script>
    $(document).ready(function(){
                $('#container').click(function(){
                    $(this).highlight();
                });
            });
  </script>
  <div id="container">
    Click, and my color will change !
  </div>
</body>

The result :

Adding some options

Our plugin will need some options to make it more flexible :

(function( $ ){

  $.fn.highlight = function(options) {

    var defaults = {
        color : '#943D20',
        time  : 1000
    }
    //if option exists merge it with defaults
    if ( options ) {
      $.extend( defaults, options );
    }

   $(this).animate({
       backgroundColor:defaults.color
   }, defaults.time);
  };
})( jQuery );

At this point, if highlight get option object it will take options and mege them with defaults. Now if you click on the text the background color will change using defined options or defaults.

Note;  to test this code you need to include jquery-ui library for color animation.

Further reading:

http://docs.jquery.com/Plugins/Authoring

2 Replies to “JQuery, create your own plugin”

Leave a Reply