Hi, I’m having trouble to get my code to work as I want.
I have a list of products on a page, each product contains it’s own <form>
which allows the user to set a quantity and add the product to the cart. This is done via AJAX. Once the item has been added a small banner appears over the product image that says ‘Added’ and then disappears. Here’s the code that handles this:
// Create some HTML for the confirmation message
var addedMessage = $('<div style="display:none;" class="item-added">ADDED</div>');
// Add an item to the cart
$(document).on('submit', 'form.add-to-cart-form', function(e){
e.preventDefault();
// Find elements within this form
submitButton = $(this).find('input.submit'); // The 'Add to cart' submit button
qtyInput = $(this).find('input.qty'); // The quantity input
product_id = $(this).find('input.product_id').val(); // A hidden input that holds the product id
productHTML = $('#product'+product_id).find('.inside'); // The div that wraps this product
// Get the original button text
submitButtonText = submitButton.val();
// Let the user know something is happening
submitButton.val('Adding...');
// Add an item to the cart and execute the callback when completed
Cart.addItem(product_id,qtyInput.val(),function(){
// Reset the quantity field back to the default value of 1
qtyInput.val(1);
// Restore the original button text
submitButton.val(submitButtonText);
// Add the message to the product's HTML
message = addedMessage.appendTo(productHTML);
// Slide the message down, then back up and remove from DOM
message.slideDown(100).delay(1000).slideUp(100, function(){
message.remove();
});
});
});
This works except for the when multiple ‘Add to cart’ buttons are pressed in quick succession. If the animation for the banner from the previous click hasn’t completed then it gets interrupted. In an ideal world I’d like it so that the user could go along a row of products, clicking the ‘Add to cart’ button and the banner for each one would independently animate and complete. Multiple animations could be happening at once.
I sort of understand this happens because I’m changing which element is referenced by message
on every click. I just don’t know how to solve it.
Thanks