Sometimes, we want to store a function with jQuery data()
method.
In this article, we’ll look at how to store a function with jQuery data()
method.
How to store a function with jQuery data() method?
To store a function with jQuery data()
method, we can create custom events and set our function as the event handler function.
For instance, we write:
<div id='foo'>
</div>
to add a div.
Then we write:
$('#foo').on('say', (e, arg) => {
console.log('Foo says', arg);
});
$('#foo').trigger('say', 'hello');
to select the div with $('#foo')
.
Then we call on
with the event name and event handler function respectively.
We get the value we triggered the event with from the arg
parameter.
Then we trigger the event with the trigger
function with the event name and data we want to send with our event.
Conclusion
To store a function with jQuery data()
method, we can create custom events and set our function as the event handler function.