/ Published in: jQuery

Simple plugin to demonstrate how the 'this' keyword is used. Plugin also allows chaining via the 'return'
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
jQuery(function($){ $(".boo").sample().fadeOut('slow'); }); /** * A Basic sample plugin */ (function($){ $.fn.sample = function(){ //Return this to continue chaining after the plugin (this refers to the jQuery object) console.log(this);//jQuery object console.log(this[0]);//First selected element return this.each(function(i){ var $this = $(this);//$this now refers to the current element being iterated over. console.log(i);//Index of current element console.log($this.attr('id'));//Use jQuery methods to do what you like with elements }); }; })(jQuery);
Comments
