As can be seen from the code below I am dynamically generating thumbnails using the template in var sProductTemplate
. The thhumbnails are populated via ajax request which is getting the information from a json file.
My task is to compare the current price in the thumbnail vs the updated price in the json(if such) and display a green arrow in the thumbnail if the new price is higher than the old. If the new price is lower then the old one then I must display a red arrow.
My problem is that I cannot really get to this point, since I cannot figure out how to save the old price and then compare it to the new price for each thumbnail.
Since each thumbnail has a unique id the i've written this code to get the price from the dom by the thumbnail's id's :
var sPriceInDom = Number($("#product-id-"+sProductId+" .product-price").text());
But, of course, this gives me the last price and I cannot really compare it to the old price, since it is replaced by the new price.
If I place this code right after the ajax request, then it gives me just zeroes, since the thumbnail is dynamically generated and it has to be populated first.
Does anyone have an idea how can I keep the old price and compare it to the lastly updated one, so I can calculate the difference?
Here is all the neccesary code :
var sProductTemplate = '<div class="col-sm-6 col-md-3"> \
<div class="thumbnail"> \
<div id="product-id-{{product-id}}" class="product"> \
<img class="imgProduct" src="{{product-icon}}" alt="idiot forgot icon"> \
<div class="caption"> \
<h3>{{product-name}}</h3> \
<div class="product-price">{{product-price}}</div> \
<i {{arrow-updown}}></i> \
</div> \
</div> \
</div>';
getProducts();
function getProducts() {
$.ajax({
"url":'get-products.php',
"method":"get",
"dataType":"text",
"cache":false
}).done( function( jData ){
var jProducts=JSON.parse(jData);
jProducts.forEach( function( jProduct ){
var sProductId = jProduct.id;
var sProductName = jProduct.name;
var sProductBrand = jProduct.brand;
var sProductPrice = jProduct.price;
lastPrice = sProductPrice;
var sPriceInDom = Number($("#product-id-"+sProductId+" .product-price").text());
console.log(sPriceInDom + " DOM");
var arrowUP ='class="fa fa-arrow-up" aria-hidden="true"';
var arrowDOWN ='class="fa fa-arrow-down" aria-hidden="true"';
var sTempProduct = sProductTemplate;
sTempProduct = sTempProduct.replace("{{product-id}}", sProductId);
sTempProduct = sTempProduct.replace("{{product-icon}}", "http://image.flaticon.com/teams/1-freepik.jpg");
sTempProduct = sTempProduct.replace("{{product-name}}", sProductBrand);
sTempProduct = sTempProduct.replace("{{product-price}}", sProductPrice);
sTempProduct = sTempProduct.replace("{{arrow-updown}}",arrowUP);
$("#lblDisplayProducts").append(sTempProduct);
})
});
}