Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reason for storing data with .data() instead of using plain variables?

Let's say I have to remember the initial height of certain element. A common practice I see is to save this value with $.data on that element.

I fail to understand the benefits of this. Why not simply keep a simple variable with that value, or an array with values if there are multiple elements? Keeps the code easy to understand.

like image 562
thelolcat Avatar asked Dec 25 '22 07:12

thelolcat


1 Answers

The main reason for using data() is to store data specific to a certain element so it can be accessed later, here's an example

$('.elements').on('click', function() {
     $(this).data('value', this.value);
});

$('.elements').on('keyup', function() {
    $(this).val( $(this).data('value') );
});

Note that the event handler could match a number of different elements, and using data() keeps the data associated to each element without using several variables for each element or a complex array.

EXAMPLE

like image 154
adeneo Avatar answered May 08 '23 09:05

adeneo