Small Town Coder

sharing code samples for desktop, web, and mobile

jQuery Mobile Custom Data Icons

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.

 

.ui-icon-red {
	background: linear-gradient(#FF0000, #CC0000);
	background: -webkit-linear-gradient(#FF0000, #CC0000);
        border:solid 2px #fff;
	border-radius:30px;
}

 

Now that I have defined my custom icon style rule, I can apply it to my navigation bar item.

 

<div data-role="navbar" data-iconpos="top">
  <ul>
    <li><a href="#" data-theme="b" data-icon="red" data-icontext="3">Messages</a></li>
    <li><a href="#" data-theme="b" data-icon="gear">Settings</a></li>
  </ul>
</div>

 

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.

 

$(document).bind("mobileinit", function() {
  $("div:jqmData(role='page')").live('pageinit', function() {
	 $("*[data-icontext]").each(function() {
		var e = $(this).find('.ui-icon'); //span with the ui-icon style
		var v = $(this).attr('data-icontext');
		e.text(v);
	 });
  });
});

 

That's all there is to it. Simple and effective.

Live Sample