Data Attributes are Awesome
The addition of data attributes to HTML5 is one of the key features that enables HTML5 to compete with native style applications in the closed platform world. Developers are no longer building static websites with HTML, but rather full blow applications that need to run in all sorts of different environments. Data attributes help make this a reality.
Always Starts With data-something
When you want to use data attributes in your HTML, the attribute will always begin with
data-. After the dash is where you begin your own naming convention that makes sense for the application. If you are working with a video game application maybe you have things like
Embed Any Data on Any Element
Data attributes can be assigned to any element on the page. In addition, you can store whatever value you need in whatever data attribute you are using for the application.
Access The Data With the Dataset Object
When you assign values to the data attributes, they are inserted into the
You’ll see many times in the HTML5 that you come across that data attributes often use a hyphenated style. Just like we mentioned the video game example that may have
dataset object such as
Data Attributes are Super Flexible
Cool! This was a super simple nonsense example, but it gets the point across. For the first example, we have a button on the page, with some jQuery set up that will act when the button is clicked. When we click the button, jQuery fetches the value of the data attribute in question and places that value into the
myAttribute variable. Then using jQuery, we simply insert a snippet of HTML after the empty content div in the HTML and include the value of
myAttribute in the output.
dataset object. In the HTML, we simply attach an
onclick event and run the function
answer when the user clicks to find out what the greatest video game of all time is. Inside our function we set up three variables and assign their values using the data we were able to access from the three different data attributes that were a part of the element on the page. We then use native DOM functions to assemble a new element and manually append the element to the div on the page. Thanks goodness for jQuery 🙂