I'm working on of the coupon based website where i need to use countdown script(http://hilios.github.io/jQuery.countdown/) with datatables.
I encounter that page change event stops timer of the first page and also count is not working on other pages.
Here is my code for updating counter when page loads each time
$('#sample_2').on( 'page.dt', function () {
alert("page changed");
$('[data-countdown]').each(function() {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('%D days %H:%M:%S'));
});
}).on('finish.countdown', function(event) {
$(this).addClass("label label-sm label-danger");
$(this).html('This offer has expired!');
});
} );
HTML code
<tr>
<td>f2 coupon</td>
<td>
<div data-countdown="2015-05-18 12:09:00" class="label label-sm label-success">20 days 15:04:54</div>
</td>
<td class="numeric">1</td>
<td class="numeric">1</td>
</tr>
Feel free to ask for more info if needed
Please advise.
-Niks
You need to use rowCallback event of datatables plugin. Check the code snippet below.
// rowCallback is what you need
function initDataTable() {
$('table').DataTable({
rowCallback: function(nRow) {
/* This is your code */
$(nRow).find('[data-countdown]').each(function() {
var $this = $(this),
finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('%D days %H:%M:%S'));
});
}).on('finish.countdown', function(event) {
$(this).addClass("label label-sm label-danger");
$(this).html('This offer has expired!');
});
}
});
};
// Ignore code below.. (I just needed something to populate this example table)
$(document).ready(function() {
for (var i = 0; i < 100; i++) {
$('table tbody').append('<tr>' +
'<td> f2 coupon </td>' +
'<td>' +
'<div data-countdown="2015-05-18 12:09:00" class="label label-sm label-success">20 days 15:04:54</div> ' +
' </td>' +
'<td class="numeric">1</td> ' +
' <td class = "numeric"> 1 </td>' +
'</tr> ');
}
initDataTable();
});
<html>
<head>
<link href="http://cdn.datatables.net/1.10.6/css/jquery.dataTables.min.css" rel="stylesheet">
<body>
<table border="1">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
</tr>
</thead>
<tbody>
<tr>
<td>f2 coupon</td>
<td>
<div data-countdown="2015-05-18 12:09:00" class="label label-sm label-success">20 days 15:04:54</div>
</td>
<td class="numeric">1</td>
<td class="numeric">1</td>
</tr>
</tbody>
</table>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.datatables.net/1.10.6/js/jquery.dataTables.min.js"></script>
<script src="http://cdn.rawgit.com/hilios/jQuery.countdown/2.0.4/dist/jquery.countdown.min.js"></script>
</html>