Divider

A divider is often use when the list gets long.

One simple usage of divider is to make a normal li with data-role=list-divider.

Recent jQuery mobile added an automatically divider option that make this much more easier.

All you need to do is add a data-autodividers="true" to the ul listview.

1<ul data-role='listview' data-autodividers="true" id='tags'></ul>

What jQuery mobile does is get the first character of each list item heading and group the same character into one list divider. In our case, the first character is ‘<’ which doesn’t help grouping at all. To workaround this issue, we need to provide our own autodividersSelector function for jQuery mobile to use.

This function takes the each li as argument. In order to use it, we need to put the tag name into tha li. One way to archive this is to make use of the data- attribute. We can make up an attribute, say “data-tag-name”.

1return "<li data-tag-name='" + this.name + "' ... </li>";

Previously we just tell the listview to “refresh”. Now we do one more step by calling the listview method with a object option. Inside the object, we set both autodividers and autodividersSelector.

In the autodividersSelector function, we tell jQuery mobile to use the first character of the tag name, where we just add it via data-tag-name. And as a bonus, we make it in upper case.

1// refresh the tags listview programatically.
2$("#tags").listview({
3  autodividers: true,
4  autodividersSelector: function (li) {
5    return li.data("tagName")[0].toUpperCase();
6  }
7}).listview("refresh");

At last, it is better to ensure the list is sorted to make the divider grouping works as expected. Therefore we add the following code snippet before the our tags-looping code.

1// before adding dividers, make sure we have sort the tags
2app.tags.sort(function(a, b) {
3  if (a.name < b.name)
4    return -1;
5  if (a.name > b.name)
6    return 1;
7  return 0;
8});

The result:

Listview 8

What’s next? We’re going to take a look at “Filtering”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content