10

I have a jQuery onClick handler, writed with an anonymous function like that:

$("#selector").on("click" function(){
    // do something
})

I would generalize the anonymous function extracting the logic in a named function, that drive me to something like:

$("#selector").on("click" namedFunction())

function namedFunction(){
    // do something
}

To me seemed a good solution. But there's a drawback since the namedFunction is executed as soon script is loaded. Here you can test the bad behaviour.

6 Answers 6

17

Just pass the reference of that function itself.

Try,

$("#selector").on("click", namedFunction);
Sign up to request clarification or add additional context in comments.

3 Comments

And what if I need to send parameters to that function?
The parameters are sent by default; in this case for example, the event is sent as a parameter to namedFunction
@BAD_SEED to send parameters look at here
5

You don't need the () for your function here:

$("#selector").on("click", namedFunction)

Comments

3

Or a shorter version

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

Comments

2

To pass custom parameters to namedFunction use:

$("#selector").on("click", null, {param1: param1}, namedFunction);


namedFunction(event) { console.log(event.data.param1); }

Comments

1

try like

function namedFunction(){
alert("Hello world!")
}
$("#clickTester").on('click', namedFunction)

Updated Fiddle

Comments

1

Named function[view jsFiddle]

Function namedFunction () {
    alert("Hello world!");
}
$("#clickTester").on('click', namedFunction);

Anonymous function [view jsFiddle]

$("#clickTester").click(function(){
   alert("Hello world!");
});

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.