jQuery event.data object and .data() method

We usually use the following function to bind an event handler to a jQuery object on some event:

$( "button" ).on("click", function(event){});

The .on method actually has another form:

$( "button" ).on("click", obj,function(event){});

Here, you give an object as the second parameter of on. This object can be obtained by the event handler as event.data. So if you pass obj={value:1} when binding the event handler, you can get the value in the event handler by event.data.value.

You can associate any data to a jQuery object using the jQuery.data() method. The data is organized by the form: key=value. For example, $(“#button”).data(“foo”,”bar”) associates “foo=bar” to the button element. You can get the value of “foo” using¬† $(“#button”).data(“foo”), which is “bar”. If you do not give any parameter when calling the .data method, it will return all key-value pairs associated with the jQuey object in an object. For example,¬† $(“#button”).data() will return {foo:”bar”}. Note that the data associated with a jQuey object has nothing to do with DOM attributes, i.e, you do not need to have a foo attribute in the html tag <button> to set the foo data.

 

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!

Leave a Reply