dimanche 6 novembre 2011

Build a hierarchical list with jQuery

Here is a little plugin jQuery I made to auto format hierarchical list.

The plugin code :

(function( $ ) {
  $.fn.hierarchical = function(options) {
   
   var settings = {
       'openImage' : 'none',
       'closeImage' : 'none',
       'imageWidth' : '0'
     };
   
   if(options) { 
    $.extend( settings, options );
   }
   
   indent(this, 0, settings.openImage, settings.closeImage, settings.imageWidth);
   return this;
  };
})( jQuery );


function indent(list, indentation, openImage, closeImage, imageWidth) {
 $(list).children('li').each(function() {
  if($(this).children('div').size() == 1) {
   
   $(this).children('div')
     .css('margin-left', indentation + 'px')
     .css('padding-left', imageWidth + 'px')
     .css('background', 'url(' + closeImage + ') no-repeat top left')
     .css('cursor','pointer')
     .click(function() {
      if($(this).parent().children('ul').css('display')=='none') {
       $(this).parent().children('ul').css('display', 'block');
       $(this).css('background', 'url(' + openImage + ') no-repeat top left')
      }
      else {
       $(this).parent().children('ul').css('display', 'none');
       $(this).css('background', 'url(' + closeImage + ') no-repeat top left')
      }
     });
   
   $(this).children('ul')
     .css('display', 'none')
     .css('margin-left',(indentation + 16) + 'px');
   
   indent($(this).children('ul'), (indentation + 5), openImage, closeImage, 16);
   
  }
  else {
   $(this).css('margin-left', indentation + 'px');
  }
 });
}
The list architecture should follow the architecture below. Each li element should have a title inside a div element and a content inside a ul element.

<ul class="hierarchical-list">
   <li>
      <div>First Element Title</div>
      <ul>
         <li>
            <div>Second Level Element Title</div>
            <ul>
               <li>
                  <div>Third Element Title</div>
                  <ul>
                      <li>Simple element.</li>
                  </ul>
               </li>
            </ul>
         </li>
      </ul>
   </li>
</ul>

Last thing to do is to call the plugin on your list :
$(document).ready(function() {
   $('.hierarchical-list').hierarchical({
    'openImage' : images/open.png',
        'closeImage' : images/close.png',
        'imageWidth' : '16'
   });
  });

And that's it. jQuery is really a write less do more lib.

0 commentaires:

Enregistrer un commentaire