Dynamic Breadcrumbs with JavaScript, Revision 2
What a difference a few years makes. The new script is much cleaner than the old one. The source with comments is below. Below that is the source without comments. Below that is the source without comments or the character replacement feature. With a few modifications you could whittle it down even further to fit only the parts you need for your site. I hope you find it useful.
Source With Comments
// Dynamic Breadcrumbs // By Harry Love (http://harrylove.org/) // License: http://creativecommons.org/licenses/by-sa/3.0/ // Updated: May 16, 2007 // To place breadcrumbs in your page, save this // file (the one you're reading) as a .js file to a directory that makes sense to you. // Link to it in the <head> portion of your web page with: <script src="/path/to/your/breadcrumbscript.js" type="text/javascript"></script> // Then in the body portion of your page, // wherever you want the breadcrumbs to appear, // paste the following: <script type="text/javascript">createBreadcrumbs();</script> // To style the breadcrumbs I recommend wrapping the script tags // in a div like this: <div id="breadcrumbs"><script blah blah...></script> // Then use CSS to style the div. // BEGIN CUSTOMIZATION // Text for the 'home' link var homeLinkText = 'Home'; // Characters to use for link separator var sep = ' > '; // Where is home? 0 = domain, 1 = 1st level directory, 2 = 2nd level, and so on. var homeLinkPosition = 0; // Modify link text var replaceChars = [ // Copy or edit the following line to create your own ["this text", "will be replaced with this text"], ['','']]; // END CUSTOMIZATION // Separate link text from url var d = document, text = url = d.location.href.split('//')[1]; // Split the url into segments and remove extraneous elements url = url.split('/'); if(url[url.length-1] == '') url.pop(); url.pop(); // Perform link text replacement for (i in replaceChars) { rex = new RegExp(replaceChars[i][0], "g"); text = text.replace(rex,replaceChars[i][1]); } // Split the link text into segments text = text.split('/'); // Write the crumbs to the page function createBreadcrumbs() { var href = '', crumbs = []; for (i in url) { href += url[i] + '/'; if (i < homeLinkPosition) continue; if (i == homeLinkPosition) text[i] = homeLinkText; text[i] = text[i].charAt(0).toUpperCase() + text[i].substr(1); crumbs.push('<a href="http://' + href + '">' + text[i] + '</a>'); } d.write(crumbs.join(sep) + sep + d.title); }
2 Comments
-
Chris spoke thusly:
The breadcrumbs code does not work?
