Removing All Products From Cart

The following code will remove all products from cart, it can be used for implementing an "Empty Cart" button. This code will function with any number of products in the cart.

{# Set page action to shop:cart #}
{# script runs if cart is not empty #}

{% if items|length %}

    <script>
    
        var itemKeys = [];
        
        // adds item keys to array
        {% for item in items %}
            itemKeys.push("{{ item.key }}");
        {% endfor %}
    
        // add deferred objects
        function getDeferreds() {
            
            var deferredAjax = [];
            
            for (var i = 0; i < itemKeys.length; i++ ) {
                
                var params = { delete_item: itemKeys[i] };
                deferredAjax.push(
                    $.ajax({
                        url: window.location.href,
                        type: 'post',
                        data : $.param( params ), // Serialize data
                        headers: {
                            'X-Event-Handler': 'shop:cart', // LemonStand CMS AJAX handler
                        }
                    })
                );
            }
            
            return deferredAjax;
        }
        
        // items removed from cart asynchronously 
        $.when.apply(null, getDeferreds()).done(function() {
            console.log('all done, refreshing page');
            window.location.href = '/cart';
        });
       
    </script>

{% endif %}