Friday, May 22, 2015

Wrapping up list items into multiple columns

I have a scenario like, a list items should be split into multiple columns while dispalying.

HTML:
'

    '    
  • A

  • '    
  • B

  • '    
  • C

  • '    
  • D

  • '    
  • E

  • '    
  • F

  • '    
  • G

  • '    
  • H

  • '    
  • I

  • '    
  • J

  • '    
  • K

  • '    
  • L

  • '    
  • M

  • '    
  • N

  • '    
  • O

  • '    
  • P

  • '    
  • Q

  • '    
  • R


  • '


      CSS:
      body {
          padding: 25px;
          font-family: 'helvetica neue', helvetica, arial, sans-serif;
          color: #3B3B3E;
      }

      li {
          background: #EFEFEF;
          text-align: center;
          width: 60px;
          padding: 10px 0;
          margin: 5px;
      }

      Java Script:
      $(document).ready(function(){
          Array.prototype.chunk = function(chunk_size){
              var array = this,
                  new_array = [],
                  chunk_size = chunk_size,
                  i,
                  length;
              
              for(i = 0, length = array.length; i < length; i += chunk_size){
                  new_array.push(array.slice(i, i + chunk_size));
              }
              return new_array;
          }
          
          function buildColumns(list, row_limit) {
              var list_items = $(list).children('li').map(function(){return this;}).get(),
                  row_limit = row_limit,
                  columnized_list_items = list_items.chunk(row_limit);
              
              $(columnized_list_items).each(function(i){
                  if (i != 0){
                      var item_width = $(this).outerWidth(),
                          item_height = $(this).outerHeight(),
                          top_margin = -((item_height * row_limit) + (parseInt($(this).css('margin-top')) * row_limit)),
                          left_margin = (item_width * i) + (parseInt($(this).css('margin-left')) * (i + 1));
                      
                      $(this[0]).css('margin-top', top_margin);
                      $(this).css('margin-left', left_margin);
                  }
                  $(this).addClass('col-'+(i+1));

              });
          }
          
          buildColumns('ul#grid-test', 5);
      });