Jquery's .click - pass parameters to user function
Directly invoke a function with specific parameters on a jQuery .click
event by incorporating it within an arrow function:
This makes certain param1
and param2
are consistently relayed to myFunction
every time #myElement
is interacted with.
data property and event object
As of jQuery 1.4.3, we have access to a data map that can be delivered as the first argument to .click()
. In essence, this crafty feature allows us to provide additional data directly to the event handler:
The data provided are snugly packed into the event object which can be retrieved through event.data
.
.on() fires versatility at .click()
The .on()
method is known for not being petty, easily letting you assign event handlers and take in parameters as an object:
Can handle multitude of event types and travel through the multi-verse of dynamically-injected elements.
.trigger() for simulated interactions
You want to simulate user interaction? .trigger()
has you covered, passing custom parameters along the way. The users might not be real, but the clicks certainly will:
Once you venture inside the event handler, you are good to go:
Tackle scenarios like a ninja
Level up with higher order functions
Stack up functions neatly using higher-order functions that return an event handler:
It keeps your syntax crisp and wraps parameters inside the handler, just like a sushi roll.
Playing with multiple parameters
To deal with more than one parameters across varied contexts, extend the caterToClicks
function:
Now, the handler is like a buffet that accommodates any number of parameters.
Inline functions vs. event.data, the duel
While heroic in their quick implementation, inline functions like arrow functions or function()
expressions can tire when performance is king:
In high stakes, journeying on event.data
can result in cheery performance as the function isn't reborn at every click:
Was this article helpful?