Untitled
unknown
plain_text
2 years ago
4.9 kB
18
Indexable
<div id="bundle-{{_.id}}" class="bundle">
<h2>{{{bundle_name}}}</h2>
<ul class="bundle-products"></ul>
<div class="bundle-footer">
<span class="bundle-total"></span>
<a class="button">Add all to Cart</a>
</div>
</div>
<script>
{{!--
Please add this piece of code to the header of all pages via Script Manager
<script>
var settingsToken = '{{settings.storefront_api.token}}';
</script>
--}}
function fetchProducts(productsIds) {
fetch('/graphql', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + settingsToken
},
body: JSON.stringify({
query: `
query getProducts {
site {
products (entityIds: [${productsIds}]) {
edges {
node {
addToCartUrl
path
defaultImage {
url(width: 350, height: 350)
}
name
prices {
price {
formatted
value
}
salePrice {
value
}
priceRange {
max {
value
}
min {
value
}
}
}
sku
}
}
}
}
}`
}),
})
.then(res => res.json())
.then(json => {
let html = '';
let allProducts = json.data.site.products.edges;
allProducts.forEach(product => {
product = product.node
let productCard = `
<li class="bundle-card" data-add-url="${product.addToCartUrl}" data-bundle-sku="${product.sku}">
<a href="${product.path}">
<img src="${product.defaultImage.url}" alt="${product.name}">
<h3>${product.name}</h3>
</a>
<span>${product.prices.price.formatted}</span>
<input type="number" class="bundle-qty" value="1" min="1" data-bundle-price="${product.prices.price.value}">
</li>
`;
html += productCard;
})
let targetDiv = document.querySelector('.bundle-products');
// Append the HTML to the target div using innerHTML
targetDiv.innerHTML = html;
handleQuantity();
});
};
function handleQuantity() {
document.querySelectorAll('.bundle-qty').forEach(qty => {
qty.addEventListener('input', function(){
calculateBundleTotals();
updateAddToCartURLs();
})
})
}
function calculateBundleTotals() {
let total = 0;
document.querySelectorAll('.bundle-qty').forEach(input => {
const price = parseFloat(input.getAttribute("data-bundle-price"));
const quantity = parseInt(input.value);
total += price * quantity;
});
document.querySelector('.bundle-total').innerHTML = "$" + total.toFixed(2);
}
function updateAddToCartURLs() {
document.querySelectorAll('.bundle-card').forEach(card => {
const url = card.getAttribute('data-add-url');
let value = card.querySelector('.bundle-qty').value;
const urlObj = new URL(url);
if (urlObj.searchParams.has('qty')) {
// If it exists, update its value
urlObj.searchParams.set('qty', value);
} else {
// If not, add the parameter
urlObj.searchParams.append('qty', value);
}
card.setAttribute('data-add-url', urlObj.toString())
console.log(urlObj)
});
}
(function(){
let productsArr = [];
{{#each product.value}}
productsArr.push({{productId}});
{{/each}}
fetchProducts(productsArr) // call the function that will perform the query and append the elements
})();
</script>Editor is loading...
Leave a Comment