jQuery Bread Crumb Trail Plugin

This plugin will take the URI segment of the URL and split it into links based on directory names. This is not the most attractive method of doing this, but is very useful when trying to add breadcrumbs to older websites that have a good document hierarchy.

/*
  Generate breadcrumbs based on URI
*/
(function( $ ){
  $.fn.breadCrumb = function( options ) {
      //---------------------------------------------------------------
      // jQuery breadCrumb v0.1
      //---------------------------------------------------------------
      var $obj = this;
      var settings = {
          'home'        : "Home",
          'seperator'    : ">",
          'title'        : document.title
      };
      var settings = $.extend(settings, options);
      var $trail = "";
      var $path = document.location.pathname.replace(/%20/gi, " ");
      var $originalContents = $obj.html();
      var $title = settings.title;
      
    //each implementation
    this.each(function(){
        $directories = $path.split("/");
        $directories[0] = settings.home;
        pathRebuild = "/";
        
        //first breadcrumb is link to home
        $trail += '<a href="/">' + settings.home + '</a> ' + settings.seperator + " ";
        
        //loop through subsequent directories skipping the top level document
        for ( i = 1; i < $directories.length - 1; i++ ){
            pathRebuild += $directories[i] + '/';
            $trail += '<a href="' + pathRebuild + '">' + $directories[i] + '</a> ' + settings.seperator + " ";    
        }
        
        //$obj.html($trail + $originalContents);    //alternative
        $obj.html($trail + $title);    //use document title
    });
  }
})( jQuery );

Usage

Under your jQuery $(document).ready statement, use the following to initialize the breadcrumb trail into the DOM Object of your choosing. In this case we are using an element with id=”jquery-breadcrumb”

$("#jquery-breadcrumb").breadCrumb({'home':'Website Name'});

Live Demo

http://jsfiddle.net/BamA8/

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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