jquery - dynamic breadcrumb

user1970557 picture user1970557 · May 7, 2013 · Viewed 23.8k times · Source

I'm trying to create a breadcrumb system for my site using the following:

<div class="breadcrumb">
    <div class="item"><a href="#home">Home / </a></div>
</div>

<div class="items">
   <ul>
     <li><a href="#test1">Test 1</a></li>
     <li><a href="#test1">Test 2</a>
        <ul>
            <li><a href="">Level 1</a></li>
            <li><a href="">Level 2</a></li>
        </ul>
     </li>
     <li><a href="#test1">Test 3</a></li>
  </ul>
</div>

What I'm looking to do is so when a user clicks on Test 1 the breadcrumb is Home / Test 1, if they then click on Test 2 and then Level 1, the breadcrumb will become Home / Test 1 / Level 2

I've been looking at jQuery to do this, but not 100% sure how best to approach it.

Any ideas would be much appreciated

Thanks

Answer

David Fregoli picture David Fregoli · May 7, 2013

example http://jsfiddle.net/mPsez/3/

$('.items a').on('click', function() {
  var $this = $(this),
      $bc = $('<div class="item"></div>');

  $this.parents('li').each(function(n, li) {
      var $a = $(li).children('a').clone();
      $bc.prepend(' / ', $a);
  });
    $('.breadcrumb').html( $bc.prepend('<a href="#home">Home</a>') );
    return false;
})