OVERTONE
OVERTONE

Reputation: 12207

jQuery Event handlers for Javascript functions

The question title is a bit obscure so let me explain.

A requirement that was only explained to me recently is the use of jQuery in my project. But it has been noted that my functions are fine as is and can be reused as long as they contain some jQuery.

So I'm exploring the world of event listeners for the first time (js side not in the HTML)

A standard Jquery onclick event:

referenceToElement.onclick = function () { alert('here'); };

One thing I notice is that the function doesn't actually have a name. Is there any clean way of doing something like:

referenceToElement.onclick = myOldJavascriptFunction();

function myOldJavascriptFunction()
{
    //blahblahblah
}

Is this good practice or is there a better way to do it. Will this even work now that I think of it?

Upvotes: 1

Views: 1081

Answers (3)

jAndy
jAndy

Reputation: 236092

Even if the question is actually worth a downvote, since you could easily answer all those questions by searching, I'll give you a headsup.

That

referenceToElement.onclick = function () { alert('here'); };

is for sure no jQuery standard thing. It's pure Javascript, adding a property to a DOM reference, in this case an anonymous function. However, you basically asked two questions now.

  • can we give that anonymous function a name ? => YES
  • can we reference a function which is defined somewhere else ? => YES

To give it a name, we can just create a named function expression like this

referenceToElement.onclick = function myFunctionName() { alert('here'); };

To reference a function, we just pass in it's name

referenceToElement.onclick = myOldJavascriptFunction;

Finally, jQuery's syntax to add the same event listener would look like this:

$( referenceToElement ).click( myOldJavascriptFunction );

Upvotes: 4

nickf
nickf

Reputation: 546253

Your first example there is plain and normal javascript, nothing to do with jQuery at all. If you were using jQuery, the line would look like this:

$(referenceToElement).click(function () { ... });

But in any case, it seems like you question is about anonymous functions. You can assign the function to a variable name, or use a function declaration and still reference that function by name:

function myFunction () { ... }

$(referenceToElement).click(myFunction);

Upvotes: 1

James Allardice
James Allardice

Reputation: 166021

Yes, you were very nearly right:

referenceToElement.onclick = myOldJavascriptFunction;

Note the lack of parentheses. This passes a reference to the function to the onclick event. Also note that this is plain old JavaScript, not jQuery. The jQuery way of doing this is more like:

$(referenceToElement).click(myOldJavascriptFunction);

Upvotes: 1

Related Questions