Small Town Coder

jQuery Mobile allows for custom icons to be used in place of the standard icon set within many of the widgets of that already support icons. These widgets include buttons, list view items, and navigation bar items.

In this example, I wanted to create custom icons for navigation bar items that would draw attention to the user. I did not want to use notification icons (badges) that are usually placed as a superscript above the current icon. As far as I know, jQuery Mobile doesn't support notification icons natively anyway, therefore implementing custom icons seems like a logical thing to try.

The jQuery Mobile data-icon attribute is used to specify the type of icon to display (http://jquerymobile.com/demos/1.2.0/docs/buttons/buttons-icons.html). In order to use custom icons, a unique icon name must be set that will identify the custom icon style rule in the stylesheet. This icon name will be used to generate the custom style rule by appending the custom icon name to the base 'ui-icon' rule. This custom style rule is only added to the widget when the widget is enhanced. The actual definition of the style rule must be created in advance by the developer.

The following style rule defines a red linear gradient background. There is absolutely no requirement to have an actual icon background image.

Notice the additional data-icontext attribute on the anchor. This is an additional custom attribute that I have defined that will allow me to add the value inside our icon. If you have inspected the HTML generated by jQuery Mobile, you will see that data-icons are rendered as span tags which gives us the opportunity to add arbitrary text within the icon.

In order to set the icon text within the icon, I needed to add some script within the "pageinit" event of the page. This event provides the right timing to manipulate the DOM after the page has been enhanced.