2

I have this function:

 $("#btn").click(function(e,someOtherArguments)
   {  //some code
    e.stopPropagation();});

It works, but If I have named function I can't use e because it is undefined.

var namedFunction= function(e,someOtherArguments) 
{
 //some code
  e.stopPropagation();
 }
$("#btn").click(namedFunction(e,someOtherArguments));

I would like to use this namedFunction because several buttons use it.

3 Answers 3

5

Either:

$("#btn").click(namedFunction);

Or:

$("#btn").click(function(e,someOtherArguments){ 

  namedFunction(e, someOtherArguments);

});
Sign up to request clarification or add additional context in comments.

1 Comment

+1. Further to this, @impeRAtoR, if you say $("#btn").click(anyFunction) jQuery will call anyFunction() with the number of arguments it wants to pass, not with the number of arguments you may or may not have declared anyFunction() to accept. (Indeed in JS a function doesn't need to explicitly declare named arguments at all since it can access them via the arguments object.)
0

You can call that function directly in the click event

$("#btn").click(function(e,someOtherArguments){ 
  namedFunction(e, someOtherArguments);

}); 

Comments

0

You can use apply like so:

$("#btn").click(function(e,someOtherArguments){ 
  namedFunction.apply(this, arguments);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.