Binding an existing JavaScript function in jQuery

Viewed 25699

Using jQuery I want to bind an existing function to a button. I've been through the documentation and have found the bind method but the examples on the jQuery site bind newly created functions where as I want to bind a function that's already defined, e.g:

function fHardCodedFunction(){
   //Do stuff
}

function fBindFunctionToElement(){
   $("#MyButton").bind("click", fHardCodedFunction());
}

Is this possible? Or am I going about this the wrong way?

4 Answers

Since this answer is tagged with event-handling, I suspect it would be useful to talk about the events, too. Your immediate problem, as stated by others, is simply to use the defined function function, and not call function(). The parens indicate to call the function, whereas you're trying to specify the function to use.

So, how do you handle the event? You only need to define it as the first argument of your function...

function fHardCodedFunction(event){
    console.log(event);
}

function fBindFunctionToElement(){
    $("#MyButton").bind("click", fHardCodedFunction);
}

The api.jquery.com documentation for bind() indicate as much, too. I have also put together a very small, working demo, to demonstrate event-handling.

HTML...

<input type="text" id="text">
<div id="main">Results appear here.</div>

JavaScript...

function clickFunction(e) { return $('#main').html(e.which); }
$('#text').bind('keypress', clickFunction);
Related