HTML5 Custom Data Attributes are a great way to associate specific pieces of data with html tags.
You can use CSS 'class' for this but classes are intended for Style information. Using them for other purposes can result in confusing code.
One use for data attributes is when you need to perform a simple calculation or conversion on a piece of data in response to user action.
A classic example of this is the online recipe where you might want to change the number of servings and have the amounts of each ingredient update. Or you might want to change from imperial to metric measurements or from fahrenheit to celsius.
allrecipes.com, for example, already has this feature but implements it using classes such as "ingredient-amount" and "ingredient-name". That works just fine but data attributes offer a 'cleaner' approach.
Here is an example of a simple recipe for pizza dough (very loosely based on a Jamie Oliver recipe)
The 'variables' in the text are wrapped in 'span' tag pairs, each with 3 data attributes:
data-type is the 'type' of the data - 'quantity' or 'temperature' (e.g. data-type='quantity')
data-value is the default value for that item before any conversion (e.g. data-value='5 g')
data-unit is the current unit for that item (e.g. data-unit='metric')
These three serve as the reference values for each item. Clicking on the Radio buttons will trigger a conversion/calculation based on that reference.
1 kg white flour
5 g salt
15 g dried yeast
12 g sugar
60 ml olive oil
650 ml water
Mix ingredients, knead, let it rest then bake at 450 F for 30 minutes.
Temperature Units Fahrenheit Celsius
Quantity Units Metric Imperial
Number of Servings 2 4 6
This demo was created by Robert Jones of Craic Computing and is freely distributed under the terms of the MIT license.