Using a foreach loop I list products on a page using the product data from a database. Every product has its own start and stop time, which is used by this jQuery countdown script to create a timer for that product.
I know that including the countdown script IN the foreach-loop is probably the worst way to do it, but I can't think of any other way. This is an attempt to make all products countdown to their own time, but they are all counting down to the same time (the time of the last product listed). I've given every countdown-element a unique ID that includes the product ID like <div id="auction-counter-<?php echo $product['product_id']; ?>"></div>
.
How do I make every product countdown to its own time, and what is a proper way to do this?
Very simplified example:
<head>
<link rel="stylesheet" href="catalog/view/javascript/countdown/css/jquery.countdown.css">
<script src="catalog/view/javascript/countdown/js/jquery.plugin.min.js"></script>
<script src="catalog/view/javascript/countdown/js/jquery.countdown.js"></script>
</head>
<body>
<?php
foreach ($products as $product) {
# Start loop
?>
<script>
var current = new Date();
var startdate = new Date("<?php echo $product['start_time']; ?>");
var stopdate = new Date("<?php echo $product['stop_time']; ?>");
function auctionStart() {
// Countdown to stop time
function auctionStop() {
// Disable timer when finished
function auctionClosed() {
$('#auction-counter-<?php echo $product['prduct_id']; ?>').countdown('destroy');
}
// Countdown to start time
$(function () {
$('#auction-counter-<?php echo $product['prduct_id']; ?>').countdown('destroy');
$('#auction-counter-<?php echo $product['prduct_id']; ?>').countdown({
until: stopdate,
onExpiry: auctionClosed,
format: 'DHMS',
padZeroes: true,
alwaysExpire: true
});
});
}
// Countdown to stop time
$(function () {
$('#auction-counter-<?php echo $product['prduct_id']; ?>').countdown({
until: startdate,
onExpiry: auctionStop,
format: 'DHMS',
padZeroes: true,
alwaysExpire: true
});
});
}
auctionStart();
</script>
<div id="auction-counter-<?php echo $product['product_id']; ?>"></div>
<?php
} # End loop
?>
</body>