I am trying to create a countdown timer using a javascript code i found on W3Schools. The code has always worked for me, but now, I need to create the timer inside a php loop which displays comments in a page. This means that the javascript timer code has to be unique for each comment, and I have done with I feel is right, but it just won't work. Here is what I have:
<?php
$post_comments = $this->db->get_where('post_comments', array('display' => 'true'))->result_array();
foreach ($post_comments as $comment) { ?>
Expire time - <span id="cRemTime<?php echo $comment->id; ?>" style="color: red"> </span>
<?php
$comment_stop_time = date("M j, Y H:i:s", strtotime($comment->time. '+1 hours')); //timestamp from table + 1 hour
?>
<script>
var ExhaustTime = "<?php echo $comment_stop_time; ?>";
var countDownDate = new Date(ExhaustTime).getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("cRemTime<?php echo $comment->id; ?>").innerHTML = hours + ": " + minutes + ": " + seconds;
if (distance < 0) {
clearInterval(x);
document.getElementById("cRemTime<?php echo $comment->id; ?>").innerHTML = "Exhausted!";
}
}, 1000);
</script>
<?php } ?>
What am I missing?
Note: I use Code Igniter
span