Skip to content

Instantly share code, notes, and snippets.

@dylanjhunt
Last active December 4, 2020 17:57
Show Gist options
  • Save dylanjhunt/71fe3fbaa3eb5ace60e488cab29ab5bd to your computer and use it in GitHub Desktop.
Save dylanjhunt/71fe3fbaa3eb5ace60e488cab29ab5bd to your computer and use it in GitHub Desktop.
This code will add any variant you want to the cart when adding another product. This is good for free giveaways and promotions
(function(){
// when I click on the add to cart button
$('.add_to_cart').on('click', function(e){
var variantId = 12275195905;
jQuery.getJSON('/cart.js', function(data){
var items = data.items;
console.log(items);
var currentVarId;
var quantity;
var isProduct = false;
items.forEach(function(e,i,a){
console.log(e);
currentVarId = e.variant_id;
if(currentVarId === variantId) {
isProduct = true;
quantity = e.quantity;
}
});
if(!isProduct) {
jQuery.post('/cart/add.js', {
quantity: 1,
id: variantId
});
} else {
if(quantity > 1) {
jQuery.post('/cart/change.js', {
quantity: 1,
id: variantId
});
}
}
});
});
})();
@cameroncowden
Copy link

Hey, was following along the example here. Don't you need to update the selector such that it will only match when the liquid conditional code adds the additional class? (e.g. $('.add_to_cart') -> $('.add_to_cart.free_item'))

@jstukey
Copy link

jstukey commented Oct 27, 2020

@cameroncowden - totally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment