Skip to content

Instantly share code, notes, and snippets.

@jholl
Last active November 13, 2015 21:28
Show Gist options
  • Save jholl/02c39a3ac441589e4c07 to your computer and use it in GitHub Desktop.
Save jholl/02c39a3ac441589e4c07 to your computer and use it in GitHub Desktop.
$(document).ready(function(){
// Create two variables:
// 1) Create a '<span></span>' element that we'll eventually put into the DOM
// 2) Cache the container already in the DOM where we'll put the span
var itemCountSpan = document.createElement("SPAN"),
cart = document.getElementById('cart-icon-wrapper');
// Set the initial text and class for the span before we put into the DOM
itemCountSpan.innerHTML = '0';
itemCountSpan.className = 'cart-count';
// Attach the new span into the DOM as the last child of the cached element above
// Before this, the elem object only exists her in the js, not in the DOM and not on the page
// After this, it will exist on the page and in the DOM (see it in inspect element)
cart.appendChild(itemCountSpan);
// Create a private function in here
// (meaning js outside of this snippet cannout use this function)
// that we can call to update the inner text of that span.
// It will get the count from the Snipcart api
// and then set the span text to that count value
function updateNavItemCount () {
var count = Snipcart.api.getItemsCount();
itemCountSpan.innerHTML = count;
}
// Use Snipcart's api 'execute' method to listen for Snipcart events
// and when the event occurs perform a callback function
// Snipcart documentation tells us the args that the callback will have (i.e. 'item')
// But we're not going to use them in this callback so we don't really need to specify.. but we do.
Snipcart.execute('bind','cart.ready',function(item){
// When the Snipcart 'cart.ready' event fires, do this callback
// This is essentially going to update our cart count when the page loads
// by running our private function above, which will update the text in the span
updateNavItemCount();
// It's good to return, but it's not really necessary here
return false;
});
// Use Snipcart's api 'execute' method to listen for a different Snipcart event
// This time we're listening for Snipcart's 'item.added' event (it exists bc the api says so)
// Then fire a callback function with args whenever the event is emitted
Snipcart.execute('bind','item.added', function(item){
// This is going to do the same thing as above,
// update the count everytime an item is added
updateNavItemCount();
return false;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment