All jQuery examples I see has in-line functions.
If the function is pretty long, or if the function is reusable, I may want to separate the function.
For example, how can I turn this
$('#myElement').click(function(){
$(this).addCss('clicked');
})
into something like this
$('#myElement').click(ElementClicked($(this))
function ElementClicked(???){
???.addCss('clicked');
}
Thanks!
This won’t work:
This is executing the function
ElementClicked()with whateverthisis at the time of writing, and binds the return value ofElementClicked()to theclickevent. Which in this case is nothing.You’ll need to pass a function to a click event, like so:
This makes a(n anonymous) function, which will be bound to the
clickevent, and the function callsElementClicked()when run, passingthis. The functionElementClickedcan be defined as:As you will notice though,
thisinside the function that is bound to the event will be the clicked element. So instead of making a function wrapper that calls a function passing the element, you can just abbreviate it like so:Notice that the function is passed to
click()like a variable instead of being executed immediately, because there are no brackets()following it.And BTW, you probably mean
addClassinstead ofaddCss.