Last active
October 25, 2018 17:38
-
-
Save atikju/4976ccd8033b89020c86e1071e2e6e6a to your computer and use it in GitHub Desktop.
Shopify - Real time cart update
This file contains 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
{% for item in cart.items %} | |
<div class="mbl-cart-container" id="DevLine-{{forloop.index}}"> | |
<div class="mbl-quantity"> | |
<p><i class="fas fa-plus" data-line-id="{{ forloop.index }}"></i></p> | |
<p class="dev-line-qty" id="Q-{{forloop.index}}">{{ item.quantity }}</p> | |
<p><i class="fas fa-minus" data-line-id="{{ forloop.index }}"></i></p> | |
</div> | |
<div class="mbl-line-image"> | |
<a href="{{ item.url }}"> | |
<img src="{{ item | img_url: 'small' }}" alt="{{ item.title | escape }}" /> | |
</a> | |
</div> | |
<!-- todo: Should this be a link to the product page? --> | |
<div class="mbl-line-title"> | |
<h3><a class="name" href="{{ item.url }}">{{ item.title }}</a></h3> | |
<p class="DevLinePrice">{{ item.line_price | money }}</p> | |
<a class="cart-removal" data-line-id="{{ forloop.index }}" href="/cart/change?line={{ forloop.index }}&quantity=0" rel="{{ item.id }}">Remove Item</a> | |
</div> | |
</div> | |
{% endfor %} | |
<script> | |
$('.mbl-quantity .fas').on('click', function(){ | |
console.log('clicked +'); | |
var lineID = $(this).data('line-id'); | |
var lineQty = $('#Q-'+lineID).text(); | |
var newQty = parseInt(lineQty)+parseInt(1); | |
if($(this).hasClass('fa-minus')){ | |
newQty = parseInt(lineQty)-parseInt(1); | |
} | |
if(newQty == 0){ | |
//do nothing | |
}else{ | |
//update quantity value | |
$('#Q-'+lineID).text(newQty); | |
//update the cart | |
jQuery.post('/cart/change.js', { line: lineID, quantity: newQty }); | |
}); | |
setTimeout(function(){ | |
//update the cart price | |
$.ajax({ | |
type: 'GET', | |
url: '/cart.json', | |
dataType: 'jsonp', | |
success: function(datax) { | |
var theLineId = parseInt(lineID)-parseInt(1); | |
var selectedItem = datax.items[theLineId]; | |
var thisPrice = selectedItem.line_price; | |
thisPrice = Shopify.formatMoney(thisPrice); | |
$('#DevLine-'+lineID).find('.DevLinePrice').html(thisPrice); | |
//update subtotal | |
var cartTotalPrice = Shopify.formatMoney(datax.total_price); | |
$('.devSubtotal').html(cartTotalPrice); | |
} | |
}); | |
}, 1000); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment