Hi i'm trying to work out the percentage discount of products that are on sale on a product listing page which have a was and now price.
I've got the code working to get the percentage discount, but i can't seem to get it to work dynamically for each product. As at the moment it'll run the calculation then print the same percentage discount per product, and even for products that are full price.
Any help on this would be appreciated. Thanks!
setTimeout(function discountPrice() {
$('.product-slab__price').each(function() {
var pattern = /[^0-9\.]/g;
var wasPrice = parseFloat($(".product-price__primary .product-price__was").text().replace(pattern, "")) / 100;
var newPrice = parseFloat($(".product-price__primary .product-price__value--discounted").text().replace(pattern, "") / 100);
var subtractPrice = (Math.abs(wasPrice - newPrice));
var dividePrice = (Math.abs(subtractPrice / wasPrice));
var multiplyPrice = (Math.abs(dividePrice * 100));
$('.discountPercentage').html(multiplyPrice.toFixed(0) + "%");
});
}, 500);
.product-price__was {
text-decoration: line-through;
}
.product-price__value.product-price__value--discounted {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-slab__price">
<div class="product-price__primary">
<span class="product-price__was">Was €10,00</span>
<span class="product-price__value product-price__value--discounted">Now €8,00</span>
<span class="discountPercentage" > </span>
</div>
</div>
<div class="product-slab__price">
<div class="product-price__primary">
<span class="product-price__was">€15,00</span>
<span class="product-price__value product-price__value--discounted">€10,00</span>
<span class="discountPercentage"></span>
</div>
</div>
<div class="product-slab__price">
<div class="product-price__primary">
<span class="product-price__value">€15,90</span>
<span class="discountPercentage"></span>
</div>
</div>