Search code examples
javascriptjquerycssjquery-mobilejquery-mobile-listview

Apply css to listview after adding list elements


I am adding elements to a list with JSON after I get the data I do the following :

success: function(data){          
  var list = $('#' + HTMLfieldName[index] + 'Ul');
  $.each(data, function() {
    newLi = document.createElement('li');
    ref = document.createElement('a');
    ref.innerHTML = this.description;
    ref.href = '#' + this.code;
    newLi.appendChild(ref);
   list.append(newLi);
   });          
}

This works fine, but the elements in the lists are show as normal href ( blue and underscore ) instead of the nice CSS used in the listview examples.

This is how the code looks after rendering :

<ul class="levelUl ui-listview ui-listview-inset ui-corner-all ui-shadow" data-role="listview" data-inset="true" name="famUl" id="famUl">
  <li><a href="#2930">Finishing</a></li>
  <li><a href="#2910">Speciality Printing</a></li>
  <li><a href="#2900">Toner</a></li>
</ul>

If I paste that code in the HTML page it looks fine.

Do I need to execute something to apply the CSS after it has been added to the page ?


Solution

  • You must trigger markup enhancement on dynamically added listview elements with:

    $('ul#id').listview('refresh'):
    

    Live example: http://jsfiddle.net/Gajotres/LrAyE/

    Basically your code would look like this:

    success: function(data){          
        var list = $('#' + HTMLfieldName[index] + 'Ul');
        $.each(data, function() {
            newLi = document.createElement('li');
            ref = document.createElement('a');
            ref.innerHTML = this.description;
            ref.href = '#' + this.code;
            newLi.appendChild(ref);
            list.append(newLi);
        });
        list.listview('refresh');    
    }
    

    And remember, you must call .listview('refresh'); after the each loop.

    To find out more, read my other ARTICLE, or find it HERE.