How to create dynamic breadcrumbs using JavaScript?


The breadcrumbs help website users to understand the navigation path, and windows file explorer is the best example that provides the breadcrumbs. When you open a file explorer, you can see the current location in the file explorer at the top bar. Also, if you click on any location, it jumps to that location.

There are two main benefits of using dynamic breadcrumbs on the website. The first is that users can know about the navigation path, and another is users can jump on any location directly in the navigation path.

Here, we will see different approaches to creating breadcrumbs in JavaScript.

Create Breadcrumbs Using jQuery

jQuery contains various methods such as clone(), prepend(), parents(), etc., which we will use here to create a custom algorithm to generate dynamic breadcrumbs.

Syntax

Users can follow the syntax below to use JQuery to create breadcrumbs.

$('.URLS a').on('click', function () {
   $(this).parents('li').each(function (index, list) {
      let anchor = $(list).children('a').clone();
      $select.prepend(' / ', anchor);
   });

In the above syntax, ‘select’ is a selected div using JQuery to add breadcrumbs as HTML.

Methods used

On() – It is used to add a click event on every <a> element.

Parent() – It finds all parent elements of the current element and filters <li> elements from them.

Each () – It is used to iterate through each <li> element, which is the parent of clicked element. It takes the index as the first parameter and the element as a second parameter.

Clone() – It creates a copy of any HTML element.

Prepend () – It is used to append any HTML at the start of the HTML element’s content.

Steps

Step 1 – Use the on() method to add a click event listener on every <a> element.

Step 2 – Access the HTML element in which we want to add breadcrumbs.

Step 3 – Use the parents() method to find all parent elements of clicked elements and filter <li> elements from them.

Step 4 – Iterate through each parent <li> element and access the child <a> element.

Step 5 – Make a clone of child <a> element for each <li> element.

Step 6 – Use the prepend () method to prepend the path component in the HTML of the selected element.

Step 7 – At last, prepend the home page location of the website to the HTML of the selected div element.

Example

In the example below, we created the <li> element to create navigations. We have also added a list as a sub-list of another list to create nested navigation.

In JavaScript, we find the parent list of every clicked element and prepend them to the breadcrumbs. As the parent() method returns the parent elements in reverse order, we need to use the prepend method to show the navigation component in the original order.

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
   <h2> Creating the <i> dynamic breadcrumbs </i> using jQuery </h2>
   <div class = "URLS">
      <ul>
         <li> <a href="/"><b> URL 1 </b></a>
            <ul>
               <li> <a href="#"> Sub URL 1 </a> </li>
               <li> <a href="#"> Sub URL 2 </a> </li>
            </ul>
         </li>
         <li> <a href="#"><b> URL 2 </b></a>
            <ul>
               <li> <a href="#"> Sub URL 1 </a> </li>
               <li> <a href="#"> Sub URL 2</a>
                  <ul>
                     <li> <a href="#"><i> Sub Sub URL 1 </i></a> </li>
                     <li> <a href="#"><i> Sub Sub URL 2 </i></a> </li>
                  </ul>
               </li>
               <li> <a href="#"> Sub URL 3 </a> </li>
               <li> <a href="#"> Sub URL 4 </a> </li>
            </ul>
         </li>
         <li> <a href="#"> <b> URL 3 </b> </a>
            <ul>
               <li> <a href="#"> Sub URL 1 </a> </li>
               <li> <a href=" #"> Sub URL 2 </a> </li>
            </ul>
         </li>
      </ul>
   </div>
   <p class="breadcrumbs"></p> 
   <script type="text/javascript">
      
      // added click event on every anchor element
      $('.URLS a').on('click', function () {
         
         // selecting P element to append texts
         $select = $('<p class="breadcrumbs"></p>');
         
         // iterate through each <li> which are parent of clicked <a> element
         $(this).parents('li').each(function (index, list) {
            
            // make a clone of current <a> element
            let anchor = $(list).children('a').clone();
            
            // prepend current <a> element to breadcrumbs
            $select.prepend(' / ', anchor);
         });
         
         // prepend tutorialspoint.com at the beginning of the breadcrumb menu.
         $select.prepend('<a href="#">TutorialsPoint.com</a>')
         $('.breadcrumbs').html($select);
      })
   </script>
</body>
</html> 

Get the current location and create breadcrumbs

We can use the window.location() method to get the current location of the browser. After that, we can split the location URL into the component and create breadcrumbs using them.

Syntax

Users can follow the syntax below to create breadcrumbs by accessing the location.

let path = location.href.split('/').slice(3);
const linkPaths = [{ "main": 'TutorialsPoint.com', "link": '/' }];
for (let i = 0; i < path.length; i++) {
   linkPaths.push({ "main": anchorText, "link": link });
}
let values = linkPaths.map((part) => {
   return "<a href="" + part.link + "">" + part.main + "</a>"
}).join('<span style="margin: 5px">/</span>')

Steps

Step 1 – Use the location.href() method to access the current location.

Step 1.1 – Use the split() method to split href with the ‘/’ delimiter.

Step 1.2 – Use the slice() method to remove the first three elements from the array, which are ‘http’, ‘www’, etc.

Step 2 – Create a linkPaths array containing objects. The object contains text and link properties.

Step 3 – Use the for loop to iterate through elements of the path array, create text and link using every path component, and push to the link paths array. Also, use the decodeURIComponent() method to decode the URI component.

Step 4 – Use the map() method to add links in the <span> element and create breadcrumbs from the linkPaths object’s array.

Example

In the example below, we access the location from the browser and implement the above algorithm to create breadcrumbs. Also, we have added a link to the homepage of the tutorialspoint website at the start of the breadcrumbs.

<html>
<body>
  <h2>Creating the <i> dynamic breadcrumbs </i> using javascript.</h2>
  <p id="breadcrumbs"> </p>
  <script>
    function configureBredcrumbs() {
      // get the location
      let path = location.href.split('/').slice(3);
      // create an array of objects to store links and anchor text
      const linkPaths = [{ "main": 'tutorialspoint.com', "link": '/' }];
      // iterate through the path array
      for (let i = 0; i < path.length; i++) {
        const component = path[i];
        // convert URL to the text
        const anchorText = decodeURIComponent(component).toUpperCase().split('.')[0];
        // create a link
        const link = '/' + path.slice(0, i + 1).join('/');
        // push to array
        linkPaths.push({ "main": anchorText, "link": link });
      }
      // add links in the span
      let values = linkPaths.map((part) => {
        return "<a href="" + part.link + "">" + part.main + "</a>"
      }).join('<span style="margin: 5px">/</span>')

      let element = document.getElementById("breadcrumbs");
      element.innerHTML = values;
    }
    configureBredcrumbs();
  </script>
</body>
</html>

Updated on: 01-Mar-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements