Help me refine the JS code

Help me refine the JS code

Valeria_16
Shopify Partner
23 0 3

 

{% comment %} add in "main-collection-product-grid" "main-collection-banner" "collection-list" {% endcomment %}
<style>
.break.page-width {
    margin-top: 20px;
}
.breadcrumb__current {
    text-transform: capitalize;
}
a {
    text-decoration: none;
}
span.breadcrumb__previous {
    text-transform: capitalize;
}
</style>

{% assign current_path = request.path %}
{% assign path_parts = current_path | split: '/' %}
{% assign page_name = path_parts.last %}

<div class="break page-width">
  <nav class="breadcrumb">
    <a href="{{ shop.url }}">Home / </a>
    
    {% if current_path contains '/products/' %}
      <span class="breadcrumb__current" id="breadcrumb-current">{{ product.title }}</span>
    {% elsif current_path contains '/pages/' %}
      <span class="breadcrumb__current" id="breadcrumb-current">{{ page_name }}</span>
      <span class="breadcrumb__separator"></span>
    {% else %}
      <span class="breadcrumb__current" id="breadcrumb-current"></span>
    {% endif %}
  </nav>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const currentPath = window.location.pathname;
    const breadcrumbCurrent = document.getElementById('breadcrumb-current');
    const currentURL = window.location.href;

    let previousCollectionData = JSON.parse(localStorage.getItem('collectionData')) || [];

    if (currentPath.includes('/products/')) {
      breadcrumbCurrent.textContent = document.title;
    } else if (currentPath.includes('/collections/')) {
      const collectionName = currentPath.split('/collections/')[1].split('/')[0];
      breadcrumbCurrent.textContent = collectionName;
    } else if (currentPath.includes('/pages/')) {
      const pageName = currentPath.split('/').pop();
      breadcrumbCurrent.textContent = pageName;
    }

    const pageData = {
      title: breadcrumbCurrent.textContent,
      url: currentURL
    };

    previousCollectionData = previousCollectionData.filter(item => item.title !== pageData.title);
    previousCollectionData.push(pageData);

    localStorage.setItem('collectionData', JSON.stringify(previousCollectionData));

    if (previousCollectionData.length > 1) {
      const previousCollections = previousCollectionData.slice(0, -1).map(item => {
        return `<a href="${item.url}" class="breadcrumb-link">${item.title}</a>`;
      }).join(' / ');

      const breadcrumbSeparator = document.createElement('span');
      breadcrumbSeparator.className = 'breadcrumb__separator';
      breadcrumbCurrent.insertAdjacentElement('beforebegin', breadcrumbSeparator);
      breadcrumbSeparator.insertAdjacentHTML('beforebegin', `<span class="breadcrumb__previous">${previousCollections} / </span>`);
    }

    document.querySelectorAll('.breadcrumb-link').forEach(link => {
      link.addEventListener('click', function(event) {
        event.preventDefault();
        const clickedTitle = this.textContent;
        const index = previousCollectionData.findIndex(item => item.title === clickedTitle);
        if (index !== -1) {
          previousCollectionData = previousCollectionData.slice(0, index + 1);
          localStorage.setItem('collectionData', JSON.stringify(previousCollectionData));
        }
        window.location.href = this.href; 
      });
    });
  });
</script>

 


This is the code for creating dynamic breadcrumbs. In my store, there is a nesting of collections in pages, collections in collections, etc. But there is a problem. When going through the sections, pressing the back button, the last element is not deleted, but moves through the crumbs. How can I fix this? That is, you need to somehow track the click on the back button, just delete the last element from Localstorage.
P.S Please do not write that using localstorage is not the best option for such a project


Replies 2 (2)

BSS-TekLabs
Shopify Partner
2350 702 827

Can you try this code 

- popstate event listener: Added window.addEventListener('popstate', function() {...}); to handle the back button.

- Removing the last breadcrumb: When the user navigates back, the last element in previousCollectionData is removed using previousCollectionData.pop().

document.addEventListener('DOMContentLoaded', function() {
    const currentPath = window.location.pathname;
    const breadcrumbCurrent = document.getElementById('breadcrumb-current');
    const currentURL = window.location.href;

    let previousCollectionData = JSON.parse(localStorage.getItem('collectionData')) || [];

    // Update breadcrumb based on current path
    if (currentPath.includes('/products/')) {
      breadcrumbCurrent.textContent = document.title;
    } else if (currentPath.includes('/collections/')) {
      const collectionName = currentPath.split('/collections/')[1].split('/')[0];
      breadcrumbCurrent.textContent = collectionName;
    } else if (currentPath.includes('/pages/')) {
      const pageName = currentPath.split('/').pop();
      breadcrumbCurrent.textContent = pageName;
    }

    const pageData = {
      title: breadcrumbCurrent.textContent,
      url: currentURL
    };

    // Prevent duplicates and add new page to the breadcrumb data
    previousCollectionData = previousCollectionData.filter(item => item.title !== pageData.title);
    previousCollectionData.push(pageData);

    localStorage.setItem('collectionData', JSON.stringify(previousCollectionData));

    // Display the previous breadcrumb elements
    if (previousCollectionData.length > 1) {
      const previousCollections = previousCollectionData.slice(0, -1).map(item => {
        return `<a href="${item.url}" class="breadcrumb-link">${item.title}</a>`;
      }).join(' / ');

      const breadcrumbSeparator = document.createElement('span');
      breadcrumbSeparator.className = 'breadcrumb__separator';
      breadcrumbCurrent.insertAdjacentElement('beforebegin', breadcrumbSeparator);
      breadcrumbSeparator.insertAdjacentHTML('beforebegin', `<span class="breadcrumb__previous">${previousCollections} / </span>`);
    }

    // Handle clicks on breadcrumb links
    document.querySelectorAll('.breadcrumb-link').forEach(link => {
      link.addEventListener('click', function(event) {
        event.preventDefault();
        const clickedTitle = this.textContent;
        const index = previousCollectionData.findIndex(item => item.title === clickedTitle);
        if (index !== -1) {
          previousCollectionData = previousCollectionData.slice(0, index + 1);
          localStorage.setItem('collectionData', JSON.stringify(previousCollectionData));
        }
        window.location.href = this.href; 
      });
    });

    // Handle the back button using the popstate event
    window.addEventListener('popstate', function() {
      previousCollectionData.pop(); // Remove the last element
      localStorage.setItem('collectionData', JSON.stringify(previousCollectionData));
      location.reload(); // Reload the page to reflect the change in the breadcrumbs
    });
});

 

If our suggestions are useful, please let us know by giving it a like or marking it as a solution.


Salepify: Efficiently increase sales conversion with sale-driven features like auto add to cart, free gifts (free plan available)


Salemate: Boost your AVO with 2-layer offer, countdown upsell in your post purchase page


BSS Commerce - Full-service eCommerce Agency | Use Shopify for 1$ in the first month now
Valeria_16
Shopify Partner
23 0 3

No, it doesn't work. I tried a similar option2024-09-24_21-06-26.png