Ask questions and get good answers on jQuery

I want to know how to make my own jQuery plugins for show dynamic content (open a div) on an determinate event.

asked Nov 10 '09 at 13:22

Federico%20Soldani's gravatar image

Federico Soldani
173128

edited Nov 10 '09 at 20:46

Pietro%20Polsinelli's gravatar image

Pietro Polsinelli ♦♦
407


Basically:

// plugin definition

$.fn.myPlugin = function(options) {
  var defaults = {
    key1: val1,
    key2: val2
  };
  // Extend our default options with those provided.
  var opts = $.extend(defaults, options);
  // Our plugin implementation code goes here.
};

To define more functions without cluttering the namespace and without exposing the implementation you shoul wrap your function creating a closure:

// create closure
(function($) {

$.fn.myPlugin = function(options) {
      var defaults = {
        key1: val1,
        key2: val2
      };
      // Extend our default options with those provided.
      var opts = $.extend(defaults, options);
      // Our plugin implementation code goes here.
    };
// end of closure
})(jQuery);

To provide public access to your function elements (for example options):

// create closure
(function($) {
  $.fn.myPlugin = function(options) {
     return this.each(function() {
      // Extend our default options with those provided.
      var opts = $.extend({}, $.fn.myPlugin.defaults , options);
      // Our plugin implementation code goes here.
     }
  };
$.fn.myPlugin.defaults = {
        key1: val1,
        key2: val2
};
// end of closure
})(jQuery);

Now you can change the defaults before invoking your plugin:

$.fn.myPlugin.defaults.key1= val3;
$("myDOMElements").myPlugin();

Useful links:

answered Nov 10 '09 at 20:25

Matteo%20Bicocchi's gravatar image

Matteo Bicocchi ♦♦
1776129

edited Nov 10 '09 at 20:37

Your answer
toggle preview

jQuery main site - Matteo Bicocchi