webmonkey: code: Breadcrumbs in javascript
I originally submitted this code to Evolt on 04 Sep 2001
introduction
There are two main ways of approaching breadcrumbs. The first is the kind left by Hansel and Gretel, which is of the form, 'I went here, then here, then here, then here'. The second is probably more useful as a navigation aid in a web site and is of the form, 'I'm at this page, which is part of this section, which is part of this section'.
The script below, uses a web site's directory structure to show where a given page is in that structure. Obviuosly, it isn't very useful for sites, where all the pages are in a single directory.
example
code
<script language="JavaScript" type="text/javascript">
<!--
function breadcrumbs(){
sURL = new String;
bits = new Object;
var x = 0;
var stop = 0;
var output = "<A HREF=\"/\">Home</A> | ";
sURL = location.href;
sURL = sURL.slice(8,sURL.length);
chunkStart = sURL.indexOf("/");
sURL = sURL.slice(chunkStart+1,sURL.length)
while(!stop){
chunkStart = sURL.indexOf("/");
if (chunkStart != -1){
bits[x] = sURL.slice(0,chunkStart)
sURL = sURL.slice(chunkStart+1,sURL.length);
}else{
stop = 1;
}
x++;
}
for(var i in bits){
output += "<A HREF=\"";
for(y=1;y<x-i;y++){
output += "../";
}
output += bits[i] + "/\">" + bits[i] + "</A> | ";
}
document.write(output);
}
-->
</script>
discussion
All we did was grab the URL and cut off the 1st 8 chars (allowing for http:// and https://). We then grabbed the next chunk up to a "/" and discarded that (the domain name). Finally, we grabbed all the remaining chunks between the "/" characters and built the html string with them. To use it, stick the function between your HEAD tags (or in a .js file) and then call it where you want the breadcrumbs to appear with <script>breadcrumbs()</script>.