Categories
JavaScript Answers

How to store a function with jQuery data() method?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *