Geo P
Geo P

Reputation: 740

Is there a way to pass a jQuery function as a parameter?

I have a function to which I want to pass a custom jQuery function that was attached to the jQuery prototype: $.fn.

For example,

$.fn.customFx = function() {
  //do something...    
}

function foo(func1) {
  //do something...
  $(selector).func1();
}

$(document).ready(function() {
  foo($.fn.customFx);
}

Is such a thing possible?

Upvotes: 2

Views: 83

Answers (3)

pomeh
pomeh

Reputation: 4912

You have to pass in the function name as a string

$.fn.customFx = function() {
  //do something...    
}

function foo( methodName ) {
  //do something...
  $(selector)[ methodName  ]();
}

$(document).ready(function() {
  foo( "customFx" );
}

Alternatively, you could use the call/apply functions to call the function, but it's quite overhead here.

Upvotes: 1

Tomalak
Tomalak

Reputation: 338228

function foo(func1) {
  func1.call( $(selector) );
}

Upvotes: 7

ShankarSangoli
ShankarSangoli

Reputation: 69905

You can try to pass the function name as a string. Try this.

$.fn.customFx = function() {
  //do something...    
}

function foo(func1) {
  //do something...
  $(selector)[func1]();
}

$(document).ready(function() {
  foo('customFx');
}

Upvotes: 5

Related Questions