How to Create a Plugin to Add and Remove using Jquery?

by Vickram H 2012-09-04 16:14:19

How to Create a Plugin to Add and Remove using Jquery?


Sample Code:

01 // defining the plugin
02 (function($){
03 $.fn.hoverClass = function(c) {
04 return this.hover(
05 function() { $(this).toggleClass(c); }
06 );
07 };
08 })(jQuery);
09
10 // using the plugin
11 $('li').hoverClass('hover');

JQuery Plugin Development Pattern:

01 //
02 // create closure
03 //
04 (function($) {
05 //
06 // plugin definition
07 //
08 $.fn.hilight = function(options) {
09 debug(this);
10 // build main options before element iteration
11 var opts = $.extend({}, $.fn.hilight.defaults, options);
12 // iterate and reformat each matched element
13 return this.each(function() {
14 $this = $(this);
15 // build element specific options
16 var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
17 // update element styles
18 $this.css({
19 backgroundColor: o.background,
20 color: o.foreground
21 });
22 var markup = $this.html();
23 // call our format function
24 markup = $.fn.hilight.format(markup);
25 $this.html(markup);
26 });
27 };
28 //
29 // private function for debugging
30 //
31 function debug($obj) {
32 if (window.console && window.console.log)
33 window.console.log('hilight selection count: ' + $obj.size());
34 };
35 //
36 // define and expose our format function
37 //
38 $.fn.hilight.format = function(txt) {
39 return '' + txt + '';
40 };
41 //
42 // plugin defaults
43 //
44 $.fn.hilight.defaults = {
45 foreground: 'red',
46 background: 'yellow'
47 };
48 //
49 // end of closure
50 //
51 })(jQuery);

Tagged in:

475
like
0
dislike
0
mail
flag

You must LOGIN to add comments