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

<ul>
<li><span>Category1</span>
  <ul>
    <li>Subcategory1</li>
    <li>Subcategory2</li>
  </ul>
</li>
<li><span>Category2</span>
  <ul>
    <li>Subcategory</li>
    <li>Subcategory1</li>
  </ul>
</li>
 
</ul>

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.

(function($){
  $.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();
      category.addClass('closed')
 
    });
 
      el.find('.category-header ').bind('touchstart', function(e) {
        e.preventDefault();
        var toExpand = $(this).next('ul');
        var i = toExpand.index('li ul');
 
        if (toExpand.attr('id') == 'active') {
          toExpand
          .removeAttr('id')
          .removeAttr('style')
          .addClass('closed');
 
        } else {
        var active = $('#active')
 
        if (active.length > 0) {
          active
          .removeAttr('id')
          .removeAttr('style')
          .addClass('closed');
        }
 
        toExpand
        .attr('id', 'active')
        .css('height', catHeight[i]+'px')
        .removeClass('closed');
 
      }
  });
}
})(jQuery);

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

<ul class="list">
<li class="category"><a class="category-header" href="#">Category1</a>
  <ul>
    <li>Subcategory1</li>
    <li>Subcategory2</li>
  </ul>
</li>
<li class="category"><a class="category-header" href="#">Category2</a>
  <ul>
    <li>Subcategory</li>
    <li>Subcategory1</li>
  </ul>
</li>
 
</ul>

My css file

.closed {  height: 0; display:none;}
#active{display:block}

Usage

$(document).ready(function() {
  $('.list').accordion();
})

You can see a working example here.