Last active
December 4, 2020 17:57
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 | |
}); | |
} | |
} | |
}); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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')
)