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.

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

Leave a Reply