Have your say in Community Polls: What was/is your greatest motivation to start your own business?

Adding & Replacing Variant Price to ATC Button

Adding & Replacing Variant Price to ATC Button

robpizzo
New Member
9 0 0

I am using the following code to add the price to the ATC button, and while upon switching variants, it successfully adds the price, it keeps the old price, consecutively adding prices to the button, instead of replacing them.

 

How can I revise this code so that it replaces, or removes the previous price every time. If you have or know of a different or better way to do this, I am open to anything. Thank you!

 

 

renderProductInfo() {
    const requestedVariantId = this.currentVariant.id;
    const sectionId = this.dataset.originalSection ? this.dataset.originalSection : this.dataset.section;

    fetch(`${this.dataset.url}?variant=${requestedVariantId}&section_id=${this.dataset.originalSection ? this.dataset.originalSection : this.dataset.section}`)
      .then((response) => response.text())
      .then((responseText) => {
        // prevent unnecessary ui changes from abandoned selections
        if (this.currentVariant.id !== requestedVariantId) return;

        const html = new DOMParser().parseFromString(responseText, 'text/html')
        const destination = document.getElementById(`price-${this.dataset.section}`);
        const source = html.getElementById(`price-${this.dataset.originalSection ? this.dataset.originalSection : this.dataset.section}`);
        const skuSource = html.getElementById(`Sku-${this.dataset.originalSection ? this.dataset.originalSection : this.dataset.section}`);
        const skuDestination = document.getElementById(`Sku-${this.dataset.section}`);
        const inventorySource = html.getElementById(`Inventory-${this.dataset.originalSection ? this.dataset.originalSection : this.dataset.section}`);
        const inventoryDestination = document.getElementById(`Inventory-${this.dataset.section}`);
        
        if (source && destination) destination.innerHTML = source.innerHTML;
        if (inventorySource && inventoryDestination) inventoryDestination.innerHTML = inventorySource.innerHTML;
        if (skuSource && skuDestination) {
          skuDestination.innerHTML = skuSource.innerHTML;
          skuDestination.classList.toggle('visibility-hidden', skuSource.classList.contains('visibility-hidden'));
        }

        // BEGIN CUSTOM CODE IN QUESTION 
        const atc=document.querySelector('.product-form__submit')
        const customAddPriceToAtc=()=>{
        atc.innerHTML+=`<span style="margin:0 4px" >-</span><span class="custom-content">${document.querySelector('.price-item--sale').innerText}</span>`
        }

        customAddPriceToAtc()
        document.querySelector('input[type="hidden"][name="id"]').addEventListener('change', ()=>{
        document.querySelector('.custom-content').innerHTML= document.querySelector('.price-item--regular').innerText        
        });

        // END CODE IN QUESTION
        
        const price = document.getElementById(`price-${this.dataset.section}`);

        if (price) price.classList.remove('visibility-hidden');
        
        if (inventoryDestination) inventoryDestination.classList.toggle('visibility-hidden', inventorySource.innerText === '');
        
        const addButtonUpdated = html.getElementById(`ProductSubmitButton-${sectionId}`);
        this.toggleAddButton(addButtonUpdated ? addButtonUpdated.hasAttribute('disabled') : true, window.variantStrings.soldOut);

        publish(PUB_SUB_EVENTS.variantChange, {data: {
          sectionId,
          html,
          variant: this.currentVariant
          
        }});
      });
  }

 

 

 

<div class="product-form__buttons">
          {%- liquid
            assign check_against_inventory = true
            if product.selected_or_first_available_variant.inventory_management != 'shopify' or  product.selected_or_first_available_variant.inventory_policy == 'continue'
              assign check_against_inventory = false
            endif
            if product.selected_or_first_available_variant.quantity_rule.min > product.selected_or_first_available_variant.inventory_quantity and check_against_inventory
              assign quantity_rule_soldout = true
            endif
          -%}
          <button
            id = "ProductSubmitButton-{{ section_id }}"
            type="submit"
            name="add"
            class="product-form__submit button button--full-width {% if show_dynamic_checkout %}button--secondary{% else %}button--primary{% endif %}"
            {% if product.selected_or_first_available_variant.available == false or quantity_rule_soldout %}
              disabled
            {% endif %}
          >
            <span>
              {%- if product.selected_or_first_available_variant.available == false or quantity_rule_soldout -%}
                {{ 'products.product.sold_out' | t }}
              {%- else -%}
                {{ 'products.product.add_to_cart' | t }} &mdash; {{ product.selected_variant.price | money }}
              {%- endif -%}
            </span>
            <div class="loading-overlay__spinner hidden">
              <svg
                aria-hidden="true"
                focusable="false"
                class="spinner"
                viewBox="0 0 66 66"
                xmlns="http://www.w3.org/2000/svg"
              >
                <circle class="path" fill="none" stroke-width="6" cx="33" cy="33" r="30"></circle>
              </svg>
            </div>
          </button>
          {%- if show_dynamic_checkout -%}
            {{ form | payment_button }}
          {%- endif -%}
        </div>
      {%- endform -%}
    </product-form>

 

 

Reply 1 (1)

jesperahlbomUK
Shopify Partner
53 4 26

Hi,

 

First, update your buy-buttons.liquid file so it looks like the below:

            <span>
              {%- if product.selected_or_first_available_variant.available == false or quantity_rule_soldout -%}
                {{ 'products.product.sold_out' | t }}
              {%- else -%}
                {{ 'products.product.add_to_cart' | t }}
              {%- endif -%} 
            </span>
            <span class="atc-price" id="atcPrice-{{ section.id }}">
                  {{ product.selected_or_first_available_variant.price | money_without_trailing_zeros| prepend: "- " }}
            </span>

buy buttons - atc.png

Then go to section-main-product.css and add this at the bottom of that file

.atc-price {
  margin-left: .5rem;
}

 

Then go to global.js and add the below code in the renderProductInfo function just above 

const price = document.getElementById(`price-${this.dataset.section}`);
        const atcPrice = `atcPrice-${this.dataset.section}`;
        const destinationAtcPrice = document.getElementById(atcPrice);
        const sourceAtcPrice = html.getElementById(atcPrice);
        if (destinationAtcPrice && sourceAtcPrice) destinationAtcPrice.innerHTML = sourceAtcPrice.innerHTML;

 global - atc.png

Hope it solves your problem or at least gets you somewhere 🙂