Share:
  • 8
  •  
  •  
  •  
  •  
  •  
    8
    Shares

Using data attributes with JQuery

Data Attributes

A data attribute is a custom attribute that stores information. Data attributes always start with “data-” then followed with a descriptive name of the data that is being stored. You can have multiple data attributes on an element and be used on any HTML element.

In use

Getting the information from the data attribute is really simple with JQuery. One of the most common uses is to have these attributes in an element that is tied to a click event. Say you have a list of items for people to select and the have a button associated with each item.

Storing each item’s information with data attributes in the button element that is associated with the item lets us get the users selection with the least amount of code.

<button class="itemSelect" type="button" data-item-number="156" data-price="49.99">Select</button>

And to get that information with an on click event:

Option 1:

$('.itemSelect').on('click', function() {
     var price = $(this).attr('data-price');
     var itemNumber = $(this).attr('data-item-number');
}

Option 2:

$('.itemSelect').on('click', function() {
     var price = $(this).data('price');
     var itemNumber = $(this).data('item-number');
}

So the above code is triggered on any element that has a class of “itemSelect” (in this example a button) then uses “$(this)” to get the element and uses the attribute function to grab the information that is in the data attributes and assigns them to the variables “price” and “itemNumber”.

Either option 1 or option 2 can be used to retrieve the data. In option one when using the .attr() selector you have to put in the whole data attribute name, in the second one using .data() you only have to put in what is after “data-” to get the value of the data attribute you want.

The real differences between the two are when storing data. When using .attr() you are actually changing the information on the page. When storing data with .data() this information is stored in the object. Another benefit of .data() is you don’t have to just store string values.


Share:
  • 8
  •  
  •  
  •  
  •  
  •  
    8
    Shares