Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery on click event that call a named function

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.

like image 849
BAD_SEED Avatar asked Mar 06 '14 09:03

BAD_SEED


People also ask

How can set click event in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.

What is the difference between .on click function ()) and .click function?

on() differs from . click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas . click() does not.

Is jQuery click deprecated?

click() shorthand is deprecated at jQuery 3 on() and . trigger() methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods.

Which jQuery method triggers or binds a function to the error event of selected elements?

jQuery error() Method The error() method triggers the error event, or attaches a function to run when an error event occurs.


2 Answers

Just pass the reference of that function itself.

Try,

$("#selector").on("click", namedFunction);
like image 60
Rajaprabhu Aravindasamy Avatar answered Oct 27 '22 09:10

Rajaprabhu Aravindasamy


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

$("#selector").on("click", namedFunction)
like image 25
Felix Avatar answered Oct 27 '22 08:10

Felix