Examples

Simple examples to get you started with the Spiffy JavaScript API

Show/Hide Section Based on Field Value

This is a basic example of how to toggle the visibility of elements on your checkout based on the value of a field.

<script>

    // Declare a constant `sectionToToggle` which contains a CSS selector for the section that will be toggled.
    // This points to the HTML element with the ID 'section-91735'.
    const sectionToToggle = '#section-91735';
    
    // Declare a constant `customFieldName` which specifies the name of the custom field we're interested in monitoring.
    // This is named "24_occupancy_options" in this case.
    const customFieldName = "24_occupancy_options";
    
    // Declare a constant `fieldValueToShow` that holds the value the custom field must have for the section to be visible.
    // In this instance, the section will be shown when the field's value is "double-occupancy".
    const fieldValueToShow = "double-occupancy";

    // The `checkout.ready()` function ensures the code inside runs once the Spiffy checkout system is fully initialized.
    checkout.ready(() => {
        
        // Add an event listener to monitor any changes in checkout fields.
        // The callback function runs whenever a checkout field value changes.
        checkout.on('change:field', (fields) => {
            
            // Initially hide the specified section by setting its CSS 'display' property to 'none'.
            document.querySelector(sectionToToggle).style.display = 'none';
            
            // Filter the `fields` array to find the custom field of interest by its name.
            // The filter function returns an array, but we're only interested in the first item ([0]),
            // as field names should be unique.
            let field = fields.filter(f => f.name == customFieldName)[0];
            
            // Check if the field's value matches `fieldValueToShow`.
            if (field && field.value == fieldValueToShow) {
                
                // If the value matches, make the specified section visible again by resetting its 'display' property.
                document.querySelector(sectionToToggle).style.display = null;
            }
        });
    });

</script>

Charge Flat-Rate Shipping by Country

This is a basic example of how to select/deselect checkout items based on the value of a field. This can be expanded to include all sorts of logic for determining items active on the checkout

<script>
// Declare a variable `shippingBlockId` that contains the ID of a block (or item) related to shipping.
var shippingBlockId = 377;

// The code inside `checkout.ready()` will execute once the checkout is fully initialized and ready for interactions.
checkout.ready(() => {
    
    // Add an event listener to monitor changes in any checkout field.
    // When any field value changes, this listener will be triggered.
    checkout.on('change:field', (value) => {
        
        // Extract the changed field from the event's value.
        const field = value.filter(f => f.name == 'billing_country')[0];
        
        // Check if the changed field's name is 'billing_country'.
        if (field.name == 'billing_country') {
            
            // If the new value of 'billing_country' is 'US'...
            if (field.value == 'US') {
                
                // Set the shipping block's quantity to 0, essentially deselecting or disabling it.
                checkout.set('item', shippingBlockId, 0);
            } else {
                
                // If the 'billing_country' is any other value than 'US'...
                // Set the shipping block's quantity to 1, essentially selecting or enabling it.
                checkout.set('item', shippingBlockId, 1);
            }
        }
    });
})
</script>
<style>#section-319 { display: none !important; }</style>

Subscription Option Specific Discounts

This is an example of how to automatically swap between promo codes depending on which subscription option is selected

<script>
// These suffix's map to the order of your subscription options.
// eg, the first suffix in the list below will be used to change
// the promo code (if any) that is used on the checkout.
// You'll need to add all these promo codes/discounts to your checkout
// in order for this to work properly. Eg, TESTX4F5 and TESTG7DK should
// be valid promo codes. You can add as many sets of promo codes as you
// like and you can should add as many suffixes as you have subscription
// options
const PROMO_SUFFIX = [
  'X4F5',
  'G7DK',
]

checkout.ready(() => {
  // Find a subscription block
  const blockEl = document.querySelector("[id*=basicSubscription-]")
  const BLOCK_ID = blockEl.getAttribute('id').replace('basicSubscription-', '')
  let selected = 0 // store selected in global scope
  
  // Handle subscription plan changes
  checkout.on('change:item', ev => {
    const item = ev.items[0]
    if (ev.block == BLOCK_ID) {
      selected = ev.selected[0]
      setPromo()
    }
  })
  
  // Handle promo code changes
  checkout.on('change:discount', setPromo)
  
  function setPromo () {
    // No promo applied
    if (!checkout.data.promo) return
    
    // Handle removing existing suffix and adding new one
    let code = checkout.data.promo
    PROMO_SUFFIX.forEach(suf => {
      if (code.lastIndexOf(suf) !== -1) {
        code = code.substring(0, code.lastIndexOf(suf))
      }
    })
    
    // Dont update it if we dont need to
    if (code + PROMO_SUFFIX[selected] === checkout.data.promo) return
    
    // Set the discount
    checkout.set('discount', code + PROMO_SUFFIX[selected])
  }
})
</script>

Hide/Show Payment Plans based on Field Value

This is a basic example of how to hide/show payment plan options based on the value of a field.

<script>
// Declare a variable `fieldName` that is a string of the custom field name
// that we should be looking at the values of.
var fieldName = 'event_dates';

// Declare a variable `onlySinglePay` containing an array of custom field values 
// that should only allow single payments.
// Right now, the array contains only one value: 'october'. 
// More values can be added to this array if required.
var onlySinglePay = ['october'];

// Declare a variable `payplanSectionId` that contains the ID of a section 
// that has the payment plan block. This section might be hidden or shown based on conditions.
var payplanSectionId = 123456;

// Initially hide the payment plan section using its ID.
// This uses a template literal to construct the CSS selector based on the provided section ID.
document.querySelector(`#section-${payplanSectionId}`).style.display = 'none';

// The code inside `checkout.ready()` will execute when the checkout is fully loaded and ready.
checkout.ready(() => {
    
    // Check if the event_date from the checkout data matches any of the dates in `onlySinglePay`.
    if (onlySinglePay.includes(checkout.data.fields.event_date)) {
        
        // If it matches, then set the 'payplan' to null. This might mean disabling a payment plan option.
        checkout.set('payplan', null);
        
        // Also hide the section associated with the payment plan using its ID.
        checkout.hide('section', payplanSectionId);
    }

    // Add an event listener to monitor changes in the checkout fields.
    // When a field changes, this listener will be triggered.
    checkout.on('change:field', (value) => {
        
        // Extract the changed field from the event's value.
        const field = value[0];
        
        // Check if the changed field's name is 'event_date'.
        if (field.name == fieldName) {
            
            // If the new value of 'event_date' is in the `onlySinglePay` array...
            if (onlySinglePay.includes(field.value)) {
                
                // Set 'payplan' to null and hide the payment plan section.
                checkout.set('payplan', null);
                checkout.hide('section', payplanSectionId);
            } else {
                
                // If the new value of 'event_date' is not in the `onlySinglePay` array...
                // Show the payment plan section.
                checkout.show('section', payplanSectionId);
            }
        }
    });
})
</script>

Last updated