Philll_t
Philll_t

Reputation: 4437

using $(this) in a custom plugin?

I have a plugin that adds a pseudo event handler. The user will then pass a function in the parameter, much like you would in any assigned event in jQuery. How would one add the $(this) functionality in the function that the user can use in the custom function? Also, please let me know the proper terminology if there is any.

// Implementation
$("some_selector").myCustomHandler(function(){
  $(this).css("background-color", "red");
});

// Plugin

(function( $ ){

   $.fn.myCustomHandler = function(fn){
   //some code
   //some code
   // then do this:
       fn();
   }
})( jQuery );

Upvotes: 1

Views: 28

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

you might be looking for

(function( $ ){

   $.fn.myCustomHandler = function(fn){
   //some code
   //some code
   // then do this:
       this.each(function(idx, el){
           fn.call(this, idx, el)
       })
   }
})( jQuery );

or even

(function( $ ){

   $.fn.myCustomHandler = function(fn){
   //some code
   //some code
   // then do this:
       this.each(fn)
   }
})( jQuery );

Upvotes: 2

Related Questions