Simple jQuery plugin layout + how 'this' works


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

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.