Skip to content
Progress Bar Item Count - Free Tutorial
Browse other ways to boost conversion rate & profit

Progress Bar Item Count - Free Tutorial

In this tutorial, we add another upgrade to the cart progress bar. This one tracks goals based on item quantity instead of value, making it easy to boost your AOV and conversions. We also added an exclusion feature, the option to calculate pricing before discounts for individual goals, and fixed scaling issues.

Compatible Themes: This code should work on all free Shopify themes (Dawn, Refresh, Craft, Studio, Publisher, Crave, Origin, Taste, Colorblock, Sense, Ride, Spotlight).

Ā 

Updated progress bar with new features:

  • Based on item count
  • individual total/subtotal for each goal
  • separate progress bar segments for equidistant goals
  • exclusions

Create metafield

Create new market metafields

  • Name: Cart Progress Goal Threshold 1
    • Namespace and key: custom.cart_progress_goal_threshold_1
    • Type: Decimal (one value)
    • Minimum value: 0
    • Maximum decimal places: 2
  • Name: Cart Progress Goal Threshold 2
    • Namespace and key: custom.cart_progress_goal_threshold_2
    • Type: Decimal (one value)
    • Minimum value: 0
    • Maximum decimal places: 2
  • Name: Cart Progress Goal Threshold 3
    • Namespace and key: custom.cart_progress_goal_threshold_3
    • Type: Decimal (one value)
    • Minimum value: 0
    • Maximum decimal places: 2

Edit Theme Code

Add settings to settings_schema.json

  {
    "name": "Cart Progress Bar",
    "settings": [
      {
        "type": "checkbox",
        "id": "enable_cart_progress_bar",
        "label": "Enable Cart Progress Bar",
        "default": false
      },
      {
        "type": "checkbox",
        "id": "show_progress_bar_icons",
        "label": "Show progress bar icons",
        "default": false
      },
      {
        "type": "select",
        "id": "progress_bar_basis",
        "label": "Progress Bar Basis",
        "options": [
          {
            "label": "Cart Price (total or subtotal)",
            "value": "item_price"
          },
          {
            "label": "Cart Item Count",
            "value": "item_count"
          }
        ],
        "default": "item_price"
      },
      {
        "type": "text",
        "id": "excluded_product_ids",
        "label": "Excluded product IDs (comma-separated)",
        "placeholder": "123456789,987654321",
        "info": "List product IDs to exclude from item count, separated by commas."
      },      
      {
        "type": "header",
        "content": "Goal 1"
      },
      {
        "type": "checkbox",
        "id": "enable_goal_1",
        "label": "Enable Goal 1",
        "default": true
      },
      {
        "type": "select",
        "id": "goal_1_basis",
        "label": "Goal 1 Basis (for price goal only)",
        "options": [
          { "label": "Total", "value": "total" },
          { "label": "Subtotal", "value": "subtotal" }
        ],
        "default": "total"
      },
      {
        "type": "text",
        "id": "goal_1_pre_goal_message",
        "label": "Goal 1 Pre-Goal Message",
        "default": "You're only [remaining_for_goal] away from <strong>FREE SHIPPING</strong>",
        "info": "Use [remaining_for_goal] to insert the dynamic remaining amount."
      },
      {
        "type": "text",
        "id": "goal_1_post_goal_message",
        "label": "Goal 1 Post-Goal Message",
        "default": "šŸŽ‰ Congrats! You've unlocked <strong>FREE SHIPPING</strong>",
        "info": "Message displayed after reaching Goal 1."
      },
      {
        "type": "text",
        "id": "goal_1_description",
        "label": "Goal 1 Description",
        "default": "Free Shipping",
        "info": "Text displayed beneath Goal 1 icon."
      },
      {
        "type": "image_picker",
        "id": "goal_1_icon",
        "label": "Goal 1 Icon"
      },
      {
        "type": "image_picker",
        "id": "goal_1_icon_reached",
        "label": "Goal 1 Reached Icon"
      },
      {
        "type": "header",
        "content": "Goal 2"
      },
      {
        "type": "checkbox",
        "id": "enable_goal_2",
        "label": "Enable Goal 2",
        "default": false
      },
      {
        "type": "select",
        "id": "goal_2_basis",
        "label": "Goal 2 Basis (for price goal only)",
        "options": [
          { "label": "Total", "value": "total" },
          { "label": "Subtotal", "value": "subtotal" }
        ],
        "default": "total"
      },
      {
        "type": "text",
        "id": "goal_2_pre_goal_message",
        "label": "Goal 2 Pre-Goal Message",
        "default": "You're only [remaining_for_goal] away from a <strong>FREE GIFT</strong>",
        "info": "Use [remaining_for_goal] to insert the dynamic remaining amount."
      },
      {
        "type": "text",
        "id": "goal_2_post_goal_message",
        "label": "Goal 2 Post-Goal Message",
        "default": "šŸŽ‰ Congrats! You've unlocked your <strong>FREE GIFT</strong>",
        "info": "Message displayed after reaching Goal 2."
      },
      {
        "type": "text",
        "id": "goal_2_description",
        "label": "Goal 2 Description",
        "default": "Free Gift",
        "info": "Text displayed beneath Goal 2 icon."
      },
      {
        "type": "image_picker",
        "id": "goal_2_icon",
        "label": "Goal 2 Icon"
      },
      {
        "type": "image_picker",
        "id": "goal_2_icon_reached",
        "label": "Goal 2 Reached Icon"
      },
      {
        "type": "header",
        "content": "Goal 3"
      },
      {
        "type": "checkbox",
        "id": "enable_goal_3",
        "label": "Enable Goal 3",
        "default": false
      },
      {
        "type": "select",
        "id": "goal_3_basis",
        "label": "Goal 3 Basis (for price goal only)",
        "options": [
          { "label": "Total", "value": "total" },
          { "label": "Subtotal", "value": "subtotal" }
        ],
        "default": "total"
      },
      {
        "type": "text",
        "id": "goal_3_pre_goal_message",
        "label": "Goal 3 Pre-Goal Message",
        "default": "You're only [remaining_for_goal] away from <strong>20% OFF</strong>",
        "info": "Use [remaining_for_goal] to insert the dynamic remaining amount."
      },
      {
        "type": "text",
        "id": "goal_3_post_goal_message",
        "label": "Goal 3 Post-Goal Message",
        "default": "šŸŽ‰ Congrats! You've unlocked <strong>20% OFF</strong>",
        "info": "Message displayed after reaching Goal 3."
      },
      {
        "type": "text",
        "id": "goal_3_description",
        "label": "Goal 3 Description",
        "default": "20% OFF",
        "info": "Text displayed beneath Goal 3 icon."
      },
      {
        "type": "image_picker",
        "id": "goal_3_icon",
        "label": "Goal 3 Icon"
      },
      {
        "type": "image_picker",
        "id": "goal_3_icon_reached",
        "label": "Goal 3 Reached Icon"
      },
      {
        "type": "header",
        "content": "Formatting Options"
      },
      {
        "type": "color",
        "id": "cart_progress_bar_color",
        "label": "Progress Bar Color",
        "default": "#d53600"
      },
      {
        "type": "color",
        "id": "cart_progress_bar_full_color",
        "label": "Progress Bar Full Color",
        "default": "#d53600"
      },
      {
        "type": "color",
        "id": "cart_progress_bar_background_color",
        "label": "Progress Bar Background Color",
        "default": "#eee"
      },
      {
        "type": "color",
        "id": "cart_progress_bar_text_color",
        "label": "Progress Bar Text Color",
        "default": "#333"
      }
    ]
  }

Create a new snippet cart-progress-bar-custom.liquid

{% if cart != empty and settings.enable_cart_progress_bar %}
  {% if localization.market.metafields.custom.cart_progress_goal_threshold_1 != nil or localization.market.metafields.custom.cart_progress_goal_threshold_2 != nil or localization.market.metafields.custom.cart_progress_goal_threshold_3 != nil %}

    {% assign progress_bar_basis = settings.progress_bar_basis %}
    {% assign raw_ids = settings.excluded_product_ids | default: '' %}
    {% assign raw_ids = raw_ids | replace: ' ', '' %}
    {% assign excluded_product_ids = raw_ids | split: ',' %}

    {% assign item_count_metric = 0 %}
    {% assign excluded_subtotal_metric = 0 %}
    {% assign excluded_total_metric = 0 %}

    {% for item in cart.items %}
      {% assign product_id_num = item.product.id | split: '/' | last %}
      {% unless excluded_product_ids contains product_id_num %}
        {% assign item_count_metric = item_count_metric | plus: item.quantity %}
        {% assign excluded_subtotal_metric = excluded_subtotal_metric | plus: item.original_line_price %}
        {% assign excluded_total_metric = excluded_total_metric | plus: item.line_price %}
      {% endunless %}
    {% endfor %}

    {% assign thresholds = '' %}
    {% assign pre_goal_messages = '' %}
    {% assign post_goal_messages = '' %}
    {% assign descriptions = '' %}
    {% assign goal_bases = '' %}

    {% assign previous_threshold = 0 %}
    {% for i in (1..3) %}
      {% assign enable_goal_key = 'enable_goal_' | append: i %}
      {% assign enable_goal = settings[enable_goal_key] %}
      {% assign metafield_name = 'cart_progress_goal_threshold_' | append: i %}
      {% assign current_metafield = localization.market.metafields.custom[metafield_name] %}

      {% assign basis_key = 'goal_' | append: i | append: '_basis' %}
      {% assign goal_basis = settings[basis_key] | default: 'total' %}

      {% if enable_goal and current_metafield != blank %}
        {% if progress_bar_basis == 'item_count' %}
          {% assign potential_threshold = current_metafield | round %}
        {% else %}
          {% assign potential_threshold = current_metafield | times: 100 | round %}
        {% endif %}

        {% if i == 1 or potential_threshold > previous_threshold %}
          {% assign threshold = potential_threshold %}
          {% assign previous_threshold = threshold %}

          {% assign pre_goal_message_key = 'goal_' | append: i | append: '_pre_goal_message' %}
          {% assign pre_goal_message = settings[pre_goal_message_key] %}
          {% assign post_goal_message_key = 'goal_' | append: i | append: '_post_goal_message' %}
          {% assign post_goal_message = settings[post_goal_message_key] %}
          {% assign description_key = 'goal_' | append: i | append: '_description' %}
          {% assign description = settings[description_key] %}

          {% if thresholds != '' %}
            {% assign thresholds = thresholds | append: ',' %}
            {% assign pre_goal_messages = pre_goal_messages | append: '||' %}
            {% assign post_goal_messages = post_goal_messages | append: '||' %}
            {% assign descriptions = descriptions | append: '||' %}
            {% assign goal_bases = goal_bases | append: ',' %}
          {% endif %}

          {% assign thresholds = thresholds | append: threshold %}
          {% assign pre_goal_messages = pre_goal_messages | append: pre_goal_message %}
          {% assign post_goal_messages = post_goal_messages | append: post_goal_message %}
          {% assign descriptions = descriptions | append: description %}
          {% assign goal_bases = goal_bases | append: goal_basis %}
        {% endif %}
      {% endif %}
    {% endfor %}

    {% assign thresholds = thresholds | split: ',' %}
    {% assign pre_goal_messages = pre_goal_messages | split: '||' %}
    {% assign post_goal_messages = post_goal_messages | split: '||' %}
    {% assign descriptions = descriptions | split: '||' %}
    {% assign goal_bases = goal_bases | split: ',' %}

    {% if thresholds.size > 0 %}
      {% assign total_threshold = thresholds.last | plus: 0 %}
    {% else %}
      {% assign total_threshold = 0 %}
    {% endif %}

    {% assign number_of_segments = thresholds.size %}

    {% if number_of_segments > 0 %}
      {% assign first_basis = goal_bases.first %}
      {% if progress_bar_basis == 'item_count' %}
        {% assign display_metric = item_count_metric %}
      {% else %}
        {% if first_basis == 'subtotal' %}
          {% assign display_metric = excluded_subtotal_metric %}
        {% else %}
          {% assign display_metric = excluded_total_metric %}
        {% endif %}
      {% endif %}

      {% if total_threshold > 0 %}
        {% assign progress_fraction = display_metric | times: 100 | divided_by: total_threshold %}
      {% else %}
        {% assign progress_fraction = 0 %}
      {% endif %}
    {% else %}
      {% assign progress_fraction = 0 %}
    {% endif %}

    {% if progress_fraction > 100 %}
      {% assign progress_percentage = 100 %}
    {% else %}
      {% assign progress_percentage = progress_fraction %}
    {% endif %}

    {% assign next_goal_index = -1 %}
    {% assign last_threshold_index = thresholds.size | minus: 1 %}
    {% for i in (0..last_threshold_index) %}
      {% assign this_threshold = thresholds[i] | plus:0 %}
      {% assign this_basis = goal_bases[i] %}
      {% if progress_bar_basis == 'item_count' %}
        {% assign current_metric_for_goal = item_count_metric %}
      {% else %}
        {% if this_basis == 'subtotal' %}
          {% assign current_metric_for_goal = excluded_subtotal_metric %}
        {% else %}
          {% assign current_metric_for_goal = excluded_total_metric %}
        {% endif %}
      {% endif %}

      {% assign diff = current_metric_for_goal | minus: this_threshold %}
      {% if diff < 0 %}
        {% assign next_goal_index = i %}
        {% break %}
      {% endif %}
    {% endfor %}

    {% if next_goal_index == -1 %}
      {% assign message = post_goal_messages.last %}
    {% else %}
      {% assign this_basis = goal_bases[next_goal_index] %}
      {% if progress_bar_basis == 'item_count' %}
        {% assign current_metric_for_goal = item_count_metric %}
      {% else %}
        {% if this_basis == 'subtotal' %}
          {% assign current_metric_for_goal = excluded_subtotal_metric %}
        {% else %}
          {% assign current_metric_for_goal = excluded_total_metric %}
        {% endif %}
      {% endif %}

      {% assign threshold = thresholds[next_goal_index] | plus:0 %}
      {% assign remaining_for_goal = threshold | minus: current_metric_for_goal %}
      {% if remaining_for_goal < 0 %}
        {% assign remaining_for_goal = 0 %}
      {% endif %}

      {% assign pre_goal_message_template = pre_goal_messages[next_goal_index] %}

      {% if progress_bar_basis == 'item_count' %}
        {% assign remaining_for_goal_formatted = remaining_for_goal %}
      {% else %}
        {% if settings.currency_code_enabled %}
          {% assign remaining_for_goal_formatted = remaining_for_goal | money_with_currency %}
        {% else %}
          {% assign remaining_for_goal_formatted = remaining_for_goal | money %}
        {% endif %}
      {% endif %}

      {% assign message = pre_goal_message_template | replace: '[remaining_for_goal]', remaining_for_goal_formatted %}
    {% endif %}

    {% assign goal_positions = '' %}
    {% if number_of_segments > 0 %}
      {% assign segment_width = 100 | divided_by: number_of_segments %}
      {% for idx in (1..number_of_segments) %}
        {% assign pos = idx | times: segment_width %}
        {% if goal_positions != '' %}
          {% assign goal_positions = goal_positions | append: ',' %}
        {% endif %}
        {% assign goal_positions = goal_positions | append: pos %}
      {% endfor %}
    {% endif %}

    <div id="cart-progress-wrapper"
      class="{% if progress_percentage == 100 %}full{% else %}not-full{% endif %}"
      data-thresholds="{{ thresholds | join: ',' }}"
      data-pre-goal-messages="{{ pre_goal_messages | join: '||' | escape }}"
      data-post-goal-messages="{{ post_goal_messages | join: '||' | escape }}"
      data-goal-positions="{{ goal_positions }}"
      data-currency-format="{% if settings.currency_code_enabled %}{{ shop.money_with_currency_format | escape }}{% else %}{{ shop.money_format | escape }}{% endif %}"
      data-progress-bar-basis="{{ progress_bar_basis }}"
      data-excluded-product-ids="{{ settings.excluded_product_ids }}"
      data-goal-bases="{{ goal_bases | join: ',' }}"
    >
      <div class="cart-progress-bar-and-icons-wrapper">
        {% if number_of_segments > 0 %}
          {% assign last_segment_index = number_of_segments | minus: 1 %}
          <div class="cart-segments-container">
            {% assign start_value = 0 %}
            {% for i in (0..last_segment_index) %}
              {% assign threshold_value = thresholds[i] | plus:0 %}
              {% assign segment_length = threshold_value | minus: start_value %}

              {% assign this_basis = goal_bases[i] %}
              {% if progress_bar_basis == 'item_count' %}
                {% assign segment_metric = item_count_metric %}
              {% else %}
                {% if this_basis == 'subtotal' %}
                  {% assign segment_metric = excluded_subtotal_metric %}
                {% else %}
                  {% assign segment_metric = excluded_total_metric %}
                {% endif %}
              {% endif %}

              {% if segment_metric >= threshold_value %}
                {% assign fill_percentage = 100 %}
              {% elsif segment_metric <= start_value %}
                {% assign fill_percentage = 0 %}
              {% else %}
                {% assign filled = segment_metric | minus: start_value %}
                {% assign fill_percentage = filled | times:100 | divided_by:segment_length %}
              {% endif %}

              <div class="cart-segment" style="width: {{ segment_width }}%;">
                <div class="cart-segment-fill" style="display:block; width: {{ fill_percentage }}%;"></div>
              </div>
              {% assign start_value = threshold_value %}
            {% endfor %}
          </div>
        {% else %}
          <div class="cart-segments-container">
            <div class="cart-segment" style="width:100%;">
              <div class="cart-segment-fill" style="display:block; width:{{ progress_percentage }}%;"></div>
            </div>
          </div>
        {% endif %}

        {% if settings.show_progress_bar_icons and number_of_segments > 0 %}
          {% assign goal_positions_array = goal_positions | split: ',' %}
          {% assign last_goal_position_index = goal_positions_array.size | minus:1 %}
          <div class="goal-icons-container">
            {% for index in (0..last_goal_position_index) %}
              {% assign goal_position = goal_positions_array[index] %}
              {% assign threshold = thresholds[index] | plus: 0 %}
              {% assign this_basis = goal_bases[index] %}

              {% if progress_bar_basis == 'item_count' %}
                {% assign icon_metric = item_count_metric %}
              {% else %}
                {% if this_basis == 'subtotal' %}
                  {% assign icon_metric = excluded_subtotal_metric %}
                {% else %}
                  {% assign icon_metric = excluded_total_metric %}
                {% endif %}
              {% endif %}

              {% assign cart_total_diff = icon_metric | minus: threshold %}
              {% assign current_index = index | plus: 1 %}
              {% assign icon_key = 'goal_' | append: current_index | append: '_icon' %}
              {% assign icon_reached_key = 'goal_' | append: current_index | append: '_icon_reached' %}
              {% assign image_icon = settings[icon_key] %}
              {% assign image_icon_reached = settings[icon_reached_key] %}
              {% assign image_alt_text = 'Goal ' | append: current_index %}
              {% assign image_alt_text_reached = 'Goal ' | append: current_index | append: ' Reached' %}

              {% if image_icon != blank %}
                {% assign image_icon_url = image_icon | image_url: width: 50 %}
                {% unless preload_images contains image_icon_url %}
                  {% if preload_images != '' %}
                    {% assign preload_images = preload_images | append: ',' %}
                  {% endif %}
                  {% assign preload_images = preload_images | append: image_icon_url %}
                {% endunless %}
              {% endif %}
              {% if image_icon_reached != blank %}
                {% assign image_icon_reached_url = image_icon_reached | image_url: width: 50 %}
                {% unless preload_images contains image_icon_reached_url %}
                  {% if preload_images != '' %}
                    {% assign preload_images = preload_images | append: ',' %}
                  {% endif %}
                  {% assign preload_images = preload_images | append: image_icon_reached_url %}
                {% endunless %}
              {% endif %}

              <div class="goal-icon" style="left: {{ goal_position }}%;"
                {% if image_icon != blank %}data-regular-icon="{{ image_icon_url }}"{% endif %}
                {% if image_icon_reached != blank %}data-reached-icon="{{ image_icon_reached_url }}"{% endif %}
                data-index="{{ current_index }}"
              >
                {% if image_icon != blank or image_icon_reached != blank %}
                  {% if cart_total_diff < 0 %}
                    {% if image_icon != blank %}
                      {{ image_icon_url | image_tag: preload: true, alt: image_alt_text }}
                    {% endif %}
                  {% else %}
                    {% if image_icon_reached != blank %}
                      {{ image_icon_reached_url | image_tag: preload: true, alt: image_alt_text_reached }}
                    {% elsif image_icon != blank %}
                      {{ image_icon_url | image_tag: preload: true, alt: image_alt_text }}
                    {% endif %}
                  {% endif %}
                {% endif %}
                {% if descriptions[index] != blank %}
                  <div class="goal-description">{{ descriptions[index] }}</div>
                {% endif %}
              </div>
            {% endfor %}
          </div>
        {% endif %}
      </div>
      <div class="goal-message">
        {{ message }}
      </div>
    </div>

    {% assign preload_images_array = preload_images | split: ',' %}
    <div style="display:none;">
      {% for preload_image in preload_images_array %}
        <img src="{{ preload_image }}" alt="">
      {% endfor %}
    </div>

    <style>
      .cart-segments-container {
        display: flex;
        width: 100%;
        background-color: {{ settings.cart_progress_bar_background_color }};
        border-radius: 10px;
        overflow: hidden;
        position: relative;
        height: 12px;
        margin: 10px auto;
      }
      .cart-segment {
        position: relative;
        height: 100%;
        background-color: {{ settings.cart_progress_bar_background_color }};
        border-right: 1px solid #ddd;
      }
      .cart-segment:last-child {
        border-right: none;
      }
      .cart-segment-fill {
        height: 100%;
        background-color: {{ settings.cart_progress_bar_color }};
      }
      #cart-progress-bar {
        display: none; 
      }
      #cart-progress-wrapper.full .cart-segment-fill {
        background-color: {{ settings.cart_progress_bar_full_color }};
      }
      {% if settings.show_progress_bar_icons %}
      .cart-progress-bar-and-icons-wrapper {
        margin-right: 20px;
      }
      .goal-icons-container {
        position: relative;
        margin-top: -30px;
        height: 60px;
        pointer-events: none;
      }
      .goal-icon {
        position: absolute;
        top: 0;
        transform: translateX(-50%);
        text-align: center;
        margin: 0;
        padding: 0;
        line-height: 1;
        width: 60px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      .goal-icon img {
        width: 30px;
        height: 30px;
        margin: 0 auto;
        display: block;
      }
      .goal-description {
        font-size: 12px;
        color: {{ settings.cart_progress_bar_text_color }};
        margin-top: 4px;
        text-align: center;
        width: 100%;
        overflow-wrap: break-word;
        word-wrap: break-word;
        hyphens: auto;
      }
      {% endif %}
      .goal-message {
        text-align: center;
        margin: 10px auto;
        font-size: 1em;
        color: {{ settings.cart_progress_bar_text_color }};
      }
    </style>
  {% endif %}
{% endif %}

Edit main-cart-items.liquid

{%- unless settings.cart_type == 'drawer' -%}
	{% render 'cart-progress-bar-custom' %}
{%- endunless -%}

Edit cart-drawer.liquid

{% render 'cart-progress-bar-custom' %}

Add a new method in cart.js

Call the new method in updateQuantity

this.updateProgressBar({ items: parsedState.items });

New methods

  updateProgressBar({ items }) {
    const progressWrapper = document.getElementById('cart-progress-wrapper');
    if (!progressWrapper) return;
  
    const progressBarBasis = progressWrapper.dataset.progressBarBasis;
    const excludedProducts = progressWrapper.dataset.excludedProductIds
      ? progressWrapper.dataset.excludedProductIds.split(',').map(id => id.trim()).filter(Boolean)
      : [];
  
    const currencyFormat = progressWrapper.dataset.currencyFormat;
    const thresholds = progressWrapper.dataset.thresholds.split(',').map(Number);
    const preGoalMessages = progressWrapper.dataset.preGoalMessages.split('||');
    const postGoalMessages = progressWrapper.dataset.postGoalMessages.split('||');
    const goalPositions = progressWrapper.dataset.goalPositions ? progressWrapper.dataset.goalPositions.split(',').map(Number) : [];
    const goalBases = progressWrapper.dataset.goalBases ? progressWrapper.dataset.goalBases.split(',') : [];
  
    let itemCountMetric = 0;
    let excludedSubtotalMetric = 0;
    let excludedTotalMetric = 0;
  
    for (const item of items) {
      if (!excludedProducts.includes(item.product_id.toString())) {
        itemCountMetric += item.quantity;
        excludedSubtotalMetric += item.original_line_price;
        excludedTotalMetric += item.line_price;
      }
    }
  
    let cartMetric;
    if (progressBarBasis === 'item_count') {
      cartMetric = itemCountMetric;
    } else {
      cartMetric = excludedTotalMetric;
    }
  
    const totalThreshold = thresholds.length > 0 ? thresholds[thresholds.length - 1] : 0;
    if (thresholds.length === 0 || totalThreshold === 0) {
      progressWrapper.style.display = 'none';
      return;
    }
  
    const segmentsContainer = progressWrapper.querySelector('.cart-segments-container');
    if (!segmentsContainer) return;
  
    const segmentElements = segmentsContainer.querySelectorAll('.cart-segment');
    const goalIcons = progressWrapper.querySelectorAll('.goal-icon');
    const goalMessageElement = progressWrapper.querySelector('.goal-message');
  
    if (cartMetric === 0 && progressBarBasis === 'item_count') {
      progressWrapper.style.display = 'none';
      if (goalMessageElement) goalMessageElement.style.display = 'none';
      segmentElements.forEach(segment => {
        const fill = segment.querySelector('.cart-segment-fill');
        if (fill) fill.style.width = '0%';
      });
      return;
    }
  
    progressWrapper.style.display = 'block';
  
    let previousSegmentValue = 0;
    segmentElements.forEach((segmentElement, index) => {
      const segmentFill = segmentElement.querySelector('.cart-segment-fill');
      if (!segmentFill) return;
  
      let segmentMetricValue;
      if (progressBarBasis === 'item_count') {
        segmentMetricValue = itemCountMetric;
      } else {
        const segmentBasis = goalBases[index] || 'total';
        segmentMetricValue = (segmentBasis === 'subtotal') ? excludedSubtotalMetric : excludedTotalMetric;
      }
  
      const currentThreshold = thresholds[index];
      let fillPercentage = 0;
  
      if (segmentMetricValue <= previousSegmentValue) {
        fillPercentage = 0;
      } else if (segmentMetricValue >= currentThreshold) {
        fillPercentage = 100;
      } else {
        const segmentRange = currentThreshold - previousSegmentValue;
        const filledAmount = segmentMetricValue - previousSegmentValue;
        fillPercentage = Math.min((filledAmount / segmentRange) * 100, 100);
      }
  
      segmentFill.style.width = fillPercentage + '%';
      previousSegmentValue = currentThreshold;
    });
  
    let nextGoalIndex = -1;
    for (let i = 0; i < thresholds.length; i++) {
      let metricForGoal;
      if (progressBarBasis === 'item_count') {
        metricForGoal = itemCountMetric;
      } else {
        const goalBasis = goalBases[i] || 'total';
        metricForGoal = (goalBasis === 'subtotal') ? excludedSubtotalMetric : excludedTotalMetric;
      }
  
      if (metricForGoal < thresholds[i]) {
        nextGoalIndex = i;
        break;
      }
    }
  
    goalIcons.forEach((goalIcon, index) => {
      let iconMetric;
      if (progressBarBasis === 'item_count') {
        iconMetric = itemCountMetric;
      } else {
        const goalBasis = goalBases[index] || 'total';
        iconMetric = (goalBasis === 'subtotal') ? excludedSubtotalMetric : excludedTotalMetric;
      }
  
      const cartTotalDiff = iconMetric - thresholds[index];
      const icon = goalIcon.querySelector('img');
      const goalNumber = goalIcon.dataset.index;
  
      if (icon) {
        if (cartTotalDiff < 0) {
          const regularIconUrl = goalIcon.dataset.regularIcon;
          if (regularIconUrl) {
            icon.src = regularIconUrl;
            icon.srcset = `${regularIconUrl} 50w`;
            icon.alt = `Goal ${goalNumber}`;
          }
        } else {
          const reachedIconUrl = goalIcon.dataset.reachedIcon;
          if (reachedIconUrl) {
            icon.src = reachedIconUrl;
            icon.srcset = `${reachedIconUrl} 50w`;
            icon.alt = `Goal ${goalNumber} Reached`;
          }
        }
      }
    });
  
    if (goalMessageElement) {
      goalMessageElement.style.display = 'block';
      if (nextGoalIndex === -1) {
        const message = postGoalMessages[postGoalMessages.length - 1];
        goalMessageElement.innerHTML = message;
        progressWrapper.classList.add('full');
      } else {
        progressWrapper.classList.remove('full');
        let metricForMessage;
        if (progressBarBasis === 'item_count') {
          metricForMessage = itemCountMetric;
        } else {
          const msgBasis = goalBases[nextGoalIndex] || 'total';
          metricForMessage = (msgBasis === 'subtotal') ? excludedSubtotalMetric : excludedTotalMetric;
        }
  
        const remainingForGoal = thresholds[nextGoalIndex] - metricForMessage;
        if (progressBarBasis === 'item_count') {
          const preGoalMessageTemplate = preGoalMessages[nextGoalIndex];
          const message = preGoalMessageTemplate.replace('[remaining_for_goal]', remainingForGoal < 0 ? 0 : remainingForGoal);
          goalMessageElement.innerHTML = message;
        } else {
          const remainingAmount = Math.max(0, remainingForGoal) / 100;
          const remainingAmountFormatted = this.formatCurrency(currencyFormat, remainingAmount);
          const preGoalMessageTemplate = preGoalMessages[nextGoalIndex];
          const message = preGoalMessageTemplate.replace('[remaining_for_goal]', remainingAmountFormatted);
          goalMessageElement.innerHTML = message;
        }
      }
    }
  }
  
	formatCurrency(currencyFormat, amount) {
	  let formattedAmount = '';
	  formattedAmount = currencyFormat
	    .replace('{{amount}}', amount.toFixed(2)) // Standard with two decimals
	    .replace('{{amount_no_decimals}}', amount.toFixed(0)) // No decimals
	    .replace('{{amount_with_comma_separator}}', amount.toFixed(2).replace('.', ',')) // Replace period with comma
	    .replace('{{amount_no_decimals_with_comma_separator}}', amount.toFixed(0).replace('.', ',')) // No decimals, use comma
	    .replace('{{amount_with_apostrophe_separator}}', amount.toFixed(2).replace('.', "'")) // Apostrophe separator
	    .replace('{{amount_no_decimals_with_space_separator}}', amount.toFixed(0).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ' ')) // No decimals, space
	    .replace('{{amount_with_space_separator}}', amount.toFixed(2).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ' ').replace('.', ',')) // Space separator
	    .replace('{{amount_with_period_and_space_separator}}', amount.toFixed(2).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ' ')); // Period and space
	  return formattedAmount;
	}

Browse other ways to boost conversion rate & profit