Home

BreadcrumbsMack Pexton

Introduction

The breadcrumbs() function was written to automatically construct breadcrumb links from the current url. It was written for an intranet but its options and CSS styling allows it to be used most anywhere.

Examples

The following is the simplest way to display breadcrumb links on a page at the location where this script is inserted.

<script>document.write(breadcrumbs());</script>

which for this page on this site produces the following:

If you use jQuery, you can do something like this:

$('.header').after('<div class="breadcrumbs">'+breadcrumbs()+'</div>\n');

There are options to specify the left-most component (the home position), the title of the right-most component, the path to use instead of the script's path, and the starting component of the path to use as the home component. Specifying the starting path allows subdirectories of the DocumentRoot directory to be used as the home directory.

The left-most component, unless specified in the options, is set to be the left-most component of the domain name, so if your url is http://example.domain.com/path/to/file.php, the left-most component is set to "example".

The right-most component of the breadcrumb links, if not defined in the options, is the title of the current page as obtained from the <title> tag. If the title is not defined, then the file name is used instead.

The following example defines all the options to breadcrumbs().

<script>
var options= {
	start_title:'<img src="images/home.gif">',
	start_index:3,
	page_title:'Example Page Title',
	path:'/start/demo/test/document/path/example_page.php'
};
document.getElementById('breadcrumbs2').innerHTML = breadcrumbs(options);
</script>

Script

<script>
/**
 * Construct breadcrumb links.
 *
 * Usage:
 *   document.write(breadcrumbs(opt));
 *   -or-
 *   document.getElementById('element_id').innerHTML = breadcrumbs(opt);
 *
 * Options: an object map having the following properties.
 *   start_title: Title of the left-most component.
 *   start_index: The beginning index of path components.
 *   page_title: The title of the right-most component.
 *   path: Optional path to use in lieu of current document path.
 *
 * Defaults:
 *   If start_title is not specified, and the url is not an ip number, then the
 *   first component of the url is used as the title. For example, for the url
 *   http://intranet.company.com, the start_title is set to "intranet". The
 *   start_index default value is 1, corresponding to the top level path to
 *   start breadcrumbs. If you want to set your home to a subdirectory of the
 *   domain, increase the start_index. If page_title is not specified it is
 *   taken from the document title set in the <title></title> tag. Page titles
 *   specified in the HTML are assumed to be of the format: A Page Title - Company Name
 *   so an attempt is made to remove the Company Name from the page title in
 *   the breadcrumb.
 *
 * Copyright (c) 2010,2015 Mack Pexton (mackpexton.com)
 * License: http://www.opensource.org/licenses/mit-license.php
 */

(function(){
	this.breadcrumbs = function(opt) {
		if (opt == null) opt = {};
		var crumbs      =(opt['path']        ? opt['path']        : location.pathname).split('/'),	// array of path components
		    page_title  = opt['page_title']  ? opt['page_title']  : document.title.replace(/(\w*) \W .*/,'$1'),// trim non-title part of page title
		    start_title = opt['start_title'] ? opt['start_title']
				: /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(location.hostname)
				? location.hostname								// ip address
				: location.hostname.replace(/([^\d])\..*/,'$1').toUpperCase(),			// first component of url
		    start_index = opt['start_index'] ? opt['start_index'] : 1,	// starting path component of crumbs, increase if starting in subdirectory
		    stop_index  = location.pathname.substr(-1) == '/' ? crumbs.length-2 : crumbs.length-1,	// check for empty file component (index pages)
		    link = '/', html = '', i,
		    encodeHTML = function(html){
			return html.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
		   };

		if (page_title == '') page_title = location.pathname.replace(/.*\//,'');	// use file name
		for (i = 1; i < start_index; i++) { link += crumbs[i]+'/'; }			// start link

		html += '<ol>\n';
		if (start_title) html += '<li><a href="'+link+'">'+encodeHTML(start_title)+'</a></li>\n';	// file: schemes don't have start_title
		for (i=start_index; i<stop_index; i++) {
			link += crumbs[i]+'/';
			html += '<li><a href="'+link+'">'+encodeHTML(decodeURIComponent(crumbs[i]).replace(/[-_]/g,' ').capitalize())+'</a></li>\n';
		}
		html += '<li>'+encodeHTML(page_title)+'</li>\n';
		html += '</ol>\n';

		return html;
	}
})();
if (!String.prototype.capitalize) String.prototype.capitalize = function() { return this.replace(/\b\w/g,function(s){return s.toUpperCase();}); };
</script>

Minified Script

The following is the above script minified using the YUI Compressor 2.4.4 made available at http://refresh-sf.com/yui/. It reduces the script size to be only 1020 characters.

<script>
!function(){this.breadcrumbs=function(t){null==t&&(t={});var e,a=(t.path?t.path:location.pathname).split("/"),n=t.page_title?t.page_title:document.title.replace(/(\w*) \W .*/,"$1"),l=t.start_title?t.start_title:/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(location.hostname)?location.hostname:location.hostname.replace(/([^\d])\..*/,"$1").toUpperCase(),i=t.start_index?t.start_index:1,o="/"==location.pathname.substr(-1)?a.length-2:a.length-1,r="/",p="",c=function(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")};for(""==n&&(n=location.pathname.replace(/.*\//,"")),e=1;i>e;e++)r+=a[e]+"/";for(p+="<ol>\n",l&&(p+='<li><a href="'+r+'">'+c(l)+"</a></li>\n"),e=i;o>e;e++)r+=a[e]+"/",p+='<li><a href="'+r+'">'+c(decodeURIComponent(a[e]).replace(/[-_]/g," ").capitalize())+"</a></li>\n";return p+="<li>"+c(n)+"</li>\n",p+="</ol>\n"}}(),String.prototype.capitalize||(String.prototype.capitalize=function(){return this.replace(/\b\w/g,function(t){return t.toUpperCase()})});
</script>

CSS Styles

CSS style definitions control the appearance of the breadcrumb links. The styles used for the above examples are listed below:

<style></style>