jQuery Plugin template


/ Published in: JavaScript
Save to your folder(s)

Uses the object prototype to extend data. Instantiate as an object and use as specified below (bottom of the code)


Copy this code and paste it in your HTML
  1. /*
  2.  * Plugin template
  3.  */
  4. (function(window, $){
  5. var Plugin = function(elem, options){
  6. this.elem = elem;
  7. this.$elem = $(elem);
  8. this.options = options;
  9. };
  10.  
  11. Plugin.prototype = {
  12. defaults: {
  13. message: 'Hello world!'
  14. },
  15. init: function() {
  16. this.config = $.extend({}, this.defaults, this.options);
  17.  
  18. this.displayMessage();
  19.  
  20. return this;
  21. },
  22. displayMessage: function() {
  23. alert(this.config.message);
  24. }
  25. };
  26.  
  27. Plugin.defaults = Plugin.prototype.defaults;
  28.  
  29. $.fn.plugin = function(options) {
  30. return this.each(function() {
  31. new Plugin(this, options).init();
  32. });
  33. };
  34.  
  35. window.Plugin = Plugin;
  36. })(window, jQuery);
  37.  
  38. /*
  39.  * Use plugin
  40.  */
  41. //Set the message per instance:
  42. $('#elem').plugin({
  43. message: 'Goodbye World!'
  44. });
  45.  
  46. var p = new Plugin(document.getElementById('elem'), {
  47. message: 'Goodbye World!'
  48. }).init();
  49.  
  50. //Or, set the global default message:
  51. Plugin.defaults.message = 'Goodbye World!';

URL: http://markdalgleish.com/2011/05/creating-highly-configurable-jquery-plugins/

Report this snippet


Comments


You need to login to view comments.