How to create dynamic breadcrumbs using JavaScript?

In this article, we will see how to create dynamic breadcrumbs using JavaScript.
A dynamic breadcrumb allows us to navigate to different pages within the navigational hierarchy, and thus we can organize various pages of the website in a hierarchical manner just like a folder-like structure.
Approach:
The following example is implemented using HTML and JavaScript.
HTML lists like <ol>,<ul>,<li> are used to create the navigation links.
Breadcrumbs dynamic navigation is implemented using various JavaScript functions like jQuery prepend(),clone() and click() methods. On click of each navigation link <a> , the child nodes are appended to its parent along with the “zambiatek /” link in the bottom div with the class display. This whole navigation hierarchy is shown in the last HTML div using jQuery html() method.
Example: The following code demonstrates the above approach.
HTML
<!DOCTYPE HTML><html><head> <script src= </script> </head><style> body{ background-color:white; } .display{ background-color:red; } </style><body> <h2 style="color:green;">zambiatek</h2> <div class="topics"> <ol> <li><a href="#"><b>Searching</b></a> <ul> <li><a href="#">Linear Search</a></li> <li><a href="#">Binary Search</a></li> </ul> </li> <li><a href="#"><b>Sorting</b></a> <ul> <li><a href="#">Bubble Sort</a></li> <li><a href="#">Merge Sort</a> <ul> <li><a href="#"><i>Recursive Merge Sort</i></a></li> <li><a href="#"><i>Iterative Merge Sort</i></a></li> </ul> </li> <li><a href="#">Selection Sort</a></li> <li><a href="#">Insertion Sort</a> </ul> </li> <li><a href="#"><b>Tree</b></a> <ul> <li><a href="#">Binary Tree</a></li> <li><a href=" #">Binary Search Tree</a></li> </ul> </li> </ol></div> <div class="display"> <div class="syllabus"> <a href="#">zambiatek / </a> </div> </div> <script type="text/javascript"> $('.topics a').on('click', function() { //selecting the syllabus class $select = $('<div class="syllabus"></div>'); $(this).parents('li').each(function(n, li) { //Adding / to each anchor tag of li $select.prepend(' / ',$(li).children('a').clone()); }); // Displaying the hierarchical order of pages. $('.display').html( $select.prepend('<a href="#syllabus">zambiatek</a>')); }) </script></body> </html> |
Output:
- Before execute:
- After execute:




