jQuery mobile's ListViews are very nice but the framework provides no methods for changing the theme (either of the entire list or an individual element) at run time.
Quite often I need to change the appearance of an element based on state. For example I use a listview on the left hand side of the page and change the content on the right hand side when the user clicks on a category. I, of course, want the selected category to be a different color than the rest of the list.
One would think you could just change the "data-theme" attribute of the element you click on and refresh the list view. This doesn't work because the element you click on doesn't even have a data-theme attribute (even though you specified it in the original markup).
This is because the framework places a lot of wrappers around the element(an href) but doesn't attach the data-theme attribute to it.
In order to change the theme there are a few steps:
- Determine the current theme
- Remove classes associated with the theme on the ancestors of the element
- Add classes on those elements corresponding to the new theme
- Change the data-theme attribute on the appropriate ancestor
- Refresh the listview
I have written a simple function to accomplish this:
2 try {
3 $(selector).each(function(){
4 try {
5 var btn = $(this);
6 var ggpar = btn.parent().parent().parent();
7 var gggpar = ggpar.parent();
8 var th = ggpar.attr("data-theme");
9 var nth = theme;
10 ggpar.removeClass("ui-btn-up-" + th).addClass("ui-btn-up-" + nth);
11 ggpar.removeClass("ui-btn-down-" + th).addClass("ui-btn-down-" + nth);
12 ggpar.attr("data-theme", nth);
13 gggpar.listview("refresh");
14 }catch(exignore){
15 //silent catch because this will fail for non initialized lists
16 //but thats ok
17 }
18 });
19 }
20 catch (ex) {
21 alert(ex);
22 }
23}
Notice that the classes you need to change are ui-btn-up-x and ui-btn-down-x, where x is the theme (a,b,c,d,e). These classes and the theme exist on the great grandparent of the href element. The listview is the great great grandparent.
You can play with the concept here
