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?
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
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.
To give it a name, we can just create a named function expression like this
To reference a function, we just pass in it’s name
Finally, jQuery’s syntax to add the same event listener would look like this: