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.

(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


My css file

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

Usage

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

You can see a working example here.

Leave a Reply