Friday, October 23, 2009

Best practice to develop jQuery plugin

  1. Create a private scope for $
  2. Attach plugin to $.fn alias
  3. Add implicit iteration
  4. Enable chaining
  5. Add default options
  6. Add custom options
  7. global custom options
<!DOCTYPE html><html lang="en"><body> <div id="counter1"></div><div id="counter2"></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script><script> (function($) { $.fn.count = function(customOptions){ var options = $.extend({},$.fn.count.defaultOptions, customOptions); return this.each(function(){ var $this = $(this); $this.text(options.startCount); var myInterval = window.setInterval(function(){ var currentCount = parseFloat($this.text()); var newCount = currentCount+1; $this.text(newCount+''); }, 1000); }); }; $.fn.count.defaultOptions = { startCount:'100' }; })(jQuery); jQuery.fn.count.defaultOptions.startCount = '300'; jQuery('#counter1').count(); jQuery('#counter2').count({startCount:'500'}); </script></body></html>

1 comment:

  1. It's very easy to find out any topic on web as compared to books, as I found this post at this web page.

    Here is my blog bmi calculator for men

    ReplyDelete