Home > Articles > Programming > Ajax

  • Print
  • + Share This
This chapter is from the book

Using Data Roles

Before we dive into data roles, you need to first learn what they are. We know that HTML elements are limited in the attributes they can contain to be considered valid. For example an img element requires an src and an alt attribute to be valid. While there are some optional attributes that you can also put in the img element that would still allow it to be valid, if you were to throw in an attribute of imgtitle it would not validate. Listing 4.2 demonstrates this with two img elements; one is valid and the other is not.

Listing 4.2 An Example of Valid and Invalid HTML Markup

1: <!-- The following img element is valid and will pass HTML validation -->
2: <img src="images/logo.png" alt="Site Logo" />
3: <!-- The following img element has been customized and will fail HTML validation -->
4: <img src="images/logo.png" alt="Site Logo" imgtitle="Tremble before our mighty logo of fury!" />

Let’s walk through the code snippet in Listing 4.2. Line 1 is an HTML comment that I included to help you understand what is going on. Line 2 is a perfectly valid img element that contains both src and alt attributes. Line 3 is another HTML comment, and line 4 is an invalid img element because it contains a custom attribute with a custom value.

We know that the code in line 4 is invalid, but what happens when we need that extra text in that img element? For example, what if we had a tooltip function that was built in JavaScript that we wanted to use that would take the text from the custom imgtitle attribute and display it? This is why data attributes exist.

Data attributes are part of the HTML5 specification. They were created so that developers who need to use custom tags can use them without fear of breaking validation of the element they are customizing. To create a data attribute you must start the attribute with data- you may then use any letters you want as long as they are lowercase.

Experienced jQuery users may already be familiar with data attributes and the use of the jQuery .data() function when working with them. If you decide to reference data attributes with this function, be aware that after the first dash any extra text will be formatted in CamelCase. For example, data-my-attribute will become data-myAttribute. To get around this you can use the jQuery .attr() method instead to specify your custom attribute. For more information on the .attr() method, visit http://api.jquery.com/attr/.

Using a data-attribute and an HTML5 DOCTYPE informs the browser to ignore the attribute and any data contained in it, thereby allowing it to validate.

jQuery Mobile uses these data attributes to create data roles for data storage. This allows the jQuery Mobile library to find the data contained in custom attributes and manipulate them without making any of the code invalid.

  • + Share This
  • 🔖 Save To Your Account