HTML lists with jQuery for mobile devices

Recently I had to transform a group of li elements into an accordion for a mobile version of a client website. So this is what I came up with.
I had an html that looked like this

  • Category1
    • Subcategory1
    • Subcategory2
  • Category2
    • Subcategory
    • Subcategory1

And I wanted to collapse all the subcategories on load leaving only the categories visible and when they click/touched each category subcategories will expand. So I wrote this script based off from Sam Croft script.

  $.fn.accordion = function() {
    var el = this;
    var catHeight;
    catHeight = new Array();
    el.find('.category ul').each(function(i){
      var category = $(this);
      catHeight[i] = category.height();
      el.find('.category-header ').bind('touchstart', function(e) {
        var toExpand = $(this).next('ul');
        var i = toExpand.index('li ul');
        if (toExpand.attr('id') == 'active') {
        } else {
        var active = $('#active')
        if (active.length > 0) {
        .attr('id', 'active')
        .css('height', catHeight[i]+'px')

And with this script I had to modify my html lists to look like this

My css file

.closed {  height: 0; display:none;}


$(document).ready(function() {

You can see a working example here.




Leave a Reply

Your email address will not be published. Required fields are marked *