Posted By

1man on 01/13/10


Tagged

plugin jquery sample


Versions (?)

Simple jQuery plugin layout + how 'this' works


 / Published in: jQuery
 

Simple plugin to demonstrate how the 'this' keyword is used. Plugin also allows chaining via the 'return'

  1. jQuery(function($){
  2. $(".boo").sample().fadeOut('slow');
  3. });
  4.  
  5. /**
  6.  * A Basic sample plugin
  7.  */
  8. (function($){
  9. $.fn.sample = function(){
  10. //Return this to continue chaining after the plugin (this refers to the jQuery object)
  11. console.log(this);//jQuery object
  12. console.log(this[0]);//First selected element
  13. return this.each(function(i){
  14. var $this = $(this);//$this now refers to the current element being iterated over.
  15. console.log(i);//Index of current element
  16. console.log($this.attr('id'));//Use jQuery methods to do what you like with elements
  17. });
  18. };
  19. })(jQuery);

Report this snippet  

You need to login to post a comment.