Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Breadcrumbs in Javascript

Rated 3.68 (Ratings: 6) (Add your rating)

Log in to add a comment
(11 comments so far)

Want more?

 
Picture of stormy

Justin Whitford

Member info | Full bio

User since: September 04, 2001

Last login: August 15, 2006

Articles written: 2

Those unfamiliar with the breadcrumb navigation concept should read MartinB's article, Breadcrumbs for All, a great tutorial if you're using SSI. ASP people should read Aardvark's Breadcrumbs for Those Using ASP and jstetser has written a nice PHP tutorial entitled Breadcrumbs for PHP Lovers.

Why Javascript?

Because I can. I know that being a client-side technology Javascript is bound to be less of a reliable tool than a server-side script that produces uncontroversial HTML, but it will work for 95% or more of internet users and, frankly, not everyone has server-side tools available to them.

All we're going to do here is grab the URL and cutting off the 1st 8 chars (allowing for http:// and https://). We then grab the next chunk up to a "/" and discard that (the domain name). Now, we grab all the remaining chunks between the "/" characters and build 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>.

[Ed note: The following script will not degrade gracefully in pre-4.x browsers. Users of Javascript 1.0 and 1.1 will not see the navigation used below. Instead, they will encounter JavaScript errors. However, this script is a good basis for accomplishing a breadcrumb navigation with Javascript on any site.]

<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 + document.title);
  }
// -->
</script>

A self proclaimed web monkey, Justin is a 'Jack of all trades' when it comes to web design & coding. Justin's hobby became a career when he was offered a junior web design position whilst chatting in an IRC channel. Having recently dropped out of a teaching degree , he eagerly accepted the job.

Justin's natural curiosity and his hunger for knowledge have seen him play/work with such technologies as HTML, XML, VRML, CSS, JavaScript, Flash, Perl, ASP, Java, JSP and PHP. Get him interested in a problem and he'll happily set about solving it using whatever tools and technologies are available.

Although preferring coding over design, Justin is comfortable with graphics/multimedia packages as varied as Adobe Photoshop(v5/6), Micrographix Picture Publisher(v5), Macromedia Fireworks(v4/5), and Flash(v4/5). The open source package, "the GiMP", is the latest to capture his attention.

Justin currently lives in Sydney, Australia.

why throw errors for pre js1.2 browsers?

Submitted by Jeff Howden on September 8, 2001 - 02:09.

may i suggest the following function which will work in js1.1 browsers and degrade gracefully for js1.0 users, instead of the one above. in the off-chance that you actually need to support js1.0 browsers, it would be fairly simple to change the fuction to not use the split() method and split the string by bruteforce with a for/next loop.

<script language="JavaScript" type="text/javascript">
<!--
  function breadcrumbs(sClass, sDelimiter)
  {
    if(!sDelimiter) sDelimiter = '|';
    var sURL = (location.pathname.indexOf('?') != -1) ? location.pathname.substring(0, location.pathname.indexOf('?')) : location.pathname;
        sURL = (location.pathname.charAt(0) == '/') ? location.pathname.substring(1) : location.pathname;
    var aURL = sURL.split('/');
    if(aURL)
    {
      var sOutput = '<a href="/">Home</a> ' + sDelimiter + ' ';
      var sPath = '/';
      for(var i = 0; i < aURL.length; i++)
      {
        sPath += aURL[i] + '/';
        sOutput += '<a href="' + sPath + '"';
        if(sClass) sOutput += ' class="' + sClass +'"';
        sOutput += '>' + aURL[i] + '</a>';
        sOutput += ' ' + sDelimiter + ' ';
      }
      sOutput += document.title;
      document.write(sOutput);
    }
  }
// -->
</script>

notice my use of location.pathname as opposed to location.href. this property of the location object gives you the precise amount of information you need to create your breadcrumb. this eliminates the need to snip off the protocol, the host, and the querystring.

.jeff

login or register to post comments

yet another breadcrumb script....

Submitted by jc2astro on September 16, 2001 - 16:28.

A while ago in May, I had the same idea to use JavaScript to make breadcrumbs. I was going to use it in my web site, but I am STILL not satisfied with what I've got so far. Oh, well; I think being an amateur and a perfectionist has it's ups and downs.... ;)

Anyway, youz inspired me to rewrite my code, and like all self-important hackers I like to show off what I write (although I'm not really that good). Naturally, I think my solution is better than the two above, which just proves that simply copying code almost never works - you must write it yourself (using others' code as an example). Anyway, here's the code.

The listing:

function breadcrumbs () {
	var sURL   = window.location.href;
	var sURLen = sURL.length;
	var aURL   = new Array();
	var aURLoc = new Array();
	var aURLen = 0;
	var letter = '';
	var word   = '';
	var output = '<div class="navbreadcrumbs"> ';
	var theend = 'index.html';
	var begin  = 'www.geocities.com';
	var now    = (theend != '') ? 0 : 1;
	var sl     = '/';
	var home   = 'nullvectorus';

	for (i=0; i < sURLen; i++) {
		justbeforeme = sURLen - i;
		fromme       = justbeforeme - 1;
		letter       = sURL.substring(fromme,justbeforeme);

		if (letter != sl) word = letter + word;
		if (((letter == sl) || (i == sURLen-1)) && (word != '')) {
			aURL[aURLen]   = word;
			aURLoc[aURLen] = sURL.substring(0,justbeforeme) + word;
			word = '';
			aURLen++;
		}
	}

	for (i=aURLen-1; i > 0; i--) {
		word = aURL[i];
		loc  = aURLoc[i];
		if (word == theend) now = 0;
		if (now  == 1) {
			if (word == home )
				output = output + '<a href="' + loc + '">home</a>' + ' &gt; ';
			else
				output = output + '<a href="' + loc + '">' + word + '</a>' + ' &gt; ';
		}
		if (word == begin)  now = 1;
	}
	document.write(output + 'here.</div>');
}

breadcrumbs();

Anyway, I decided to parse the URL entirely, since I am afraid of browser differences. Note that the code will work in Netscape (4 or 6) but not in IE when testing offline (ie, on your computer @ home, work). Simply change the variable 'sl' to the other slash mark, since IE likes to use windows notation for local files.

I'm sure there is a better way to do this - There smells like a way to use only one 'for' loop. That would be more efficient. I used variables to hold most of the options, instead of the actual values, because **I think** it is more efficient that way.

There is a working example of this code in action at http://www.geocities.com/nullvectorus/test/test2/test3which is my web page. Use with care and enthusiasm. ;-)

Jimmy C.

login or register to post comments

For those that don't own an entire domain

Submitted by mwmistak on September 17, 2001 - 07:13.

For those of us who are working on a site that uses a subfolder of a domain does anyone have an idea on how this can be altered to create breadcrumbs from a "user specified" root folder?

login or register to post comments

Re: For those that don't own an entire domain

Submitted by jc2astro on September 19, 2001 - 13:58.

You can use my code to do what you wish by modifying the variables 'begin' and 'home'. In fact, notice that I don't own the domain to the web site my test page is on 'www.geocities.com'. There is a better methode than the one used in my code, but I want you to figure that out yourself, so you can learn how the code works... :-)

login or register to post comments

Small edit to user

Submitted by shaunshull on November 16, 2001 - 13:39.

Here is a small edit I made to the code submitted by Jeff. Bascially follows the same process but eliminates the actual name of the page showing up in the breadcrumb and cycles through an array to replace names of directories with customized names. in this example the staging directory would be named to "This is a test".

var dList = new Array();
var nList = new Array();

// dir staging to This is a test
dList[0] = 'staging';
nList[0] = 'This is a test';

function breadcrumbs(sClass, sDelimiter)
{
    if(!sDelimiter) sDelimiter = '|';
    var sURL = (location.pathname.indexOf('?') != -1) ? location.pathname.substring(0, location.pathname.indexOf('?')) : location.pathname;
        sURL = (location.pathname.charAt(0) == '/') ? location.pathname.substring(1) : location.pathname;
    var aURL = sURL.split('/');
    if(aURL)
    {
      var sOutput = 'Home ' + sDelimiter + ' ';
      var sPath = '/';
      for(var i = 0; i < aURL.length; i++)
      {
        if(aURL[i].indexOf('.html')!=-1)continue;
        sPath += aURL[i] + '/';
        for(var s = 0; s < dList.length; s++)if(aURL[i]==dList[s])aURL[i]=nList[s];        
        sOutput += '';
        sOutput += ' ' + sDelimiter + ' ';
      }
      sOutput += document.title;
      document.write(sOutput);
    }
}

login or register to post comments

breadcrumbs code not working like it should....

Submitted by bruceg on June 19, 2002 - 16:30.

i used the code listed by Justin at the top, but it doesn't have the full functionality that I would like it to. The site I put the code in is http://www.egeneralmedical.com. For instance this link http://www.egeneralmedical.com/thermometers.html should be at HOME/ADC/ADC Thermometers, but only states HOME/ADC Thermometers...so its skipping a level. I would like to get that intermediate level to show up. Thanks in advance for any help! Bruce Gilbert webmaster eGeneralMedical, Inc.

login or register to post comments

Non-directory based breadcrumbs

Submitted by jgreatrex on January 20, 2005 - 02:56.

If you want to create a breadcrumb trail but don't want to be tied down to a rigid directory structure then you can use the following:- var text = new Array() var url = new Array() text[0] = "Home" url[0] = "default.htm" text[1] = "Text 1" url[1] = "link1.htm" text[2] = "Text 2" url[2] = "link2.htm" text[3] = "Text 3" url[3] = "link3.htm" text[4] = "Text 4" url[4] = "link4.htm" text[5] = "Text 5" url[5] = "link5.htm" text[6] = "Text 6" url[6] = "link6.htm" text[7] = "Text 7" url[7] = "link7.htm" var crouton = new Array("1","3","4","7"); document.write(""+text[0]+""+" > "); for (i = 0; i < crouton.length; i++){ if (i < crouton.length - 1) { document.write(""+text[crouton[i]]+""+" > "); } else { document.write(""+text[crouton[i]]+"" ); } } } Where the VAR crouton identifies which elements you want to include.

login or register to post comments

A more "all-encompassing" breadcrumbs script in the making...

Submitted by opyate on October 20, 2005 - 02:37.

It seems I'm a couple of years late to the breadcrumbs party.

I've also developed a Javascript breadcrumbs script, and plan some more features. Have a look at it here: http://www.opyate.com/code/index.html#youarehere, and please email me with comments.

Cheers,

Juan

login or register to post comments

Multi Word Directory Name

Submitted by rothr on December 8, 2005 - 15:46.

Justin, I thought your script worked well. The only problem I have is with directories that have a name which is more than one word. The escape characters appear. I normally don't use more than one word in my directory structure, but I do need a more descriptive breadcrumb trail. Is there a way around this? Thanks.

login or register to post comments

How to activate the url hyperlinks?

Submitted by taigar on April 18, 2007 - 18:23.

Hi,

I'm a newbie to javascript and I'm having trouble activating the url hyperlinks in the Non-directory based breadcrumbs excample submitted by jgreatrex. All it's showing is the text. Can you please advice how to create hyperlinks or point me in the right direction?

Thanks

login or register to post comments

Help

Submitted by mikeiam on June 7, 2007 - 22:48.

Why is the file name displaying: http://beta.globalathletics.com/Athletes/Meseret_Defar.php And here? http://beta.globalathletics.com/Athletes/

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.