I've made a jQuery countdown timer, using moment.js and moment-duration-format plugin.
Note that $('div#countdown')
is hard-coded inside the function. The function works as presented here. But if I change the hard-coded reference to $(this), it doesn't work. console.log($this)
returns an empty object.
I've tried setting $(this) to a variable at the start of the function, in case the interval was creating a scope issue, but it made no difference.
The confusing part is that I've used this exact $.fn.xxx = function
syntax before for custom jQuery functions, and $(this) has worked fine in those functions. Something about this particular function is tripping it up.
<script>
$.fn.countdown = function ( seconds, tFormat, stopAtZero ) {
tFormat = (typeof tFormat !== 'undefined') ? tFormat : 'hh:mm:ss';
stopAtZero = (typeof stopAtZero !== 'undefined') ? stopAtZero : true;
var eventTime = Date.now() + ( seconds * 1000 );
var diffTime = eventTime - Date.now();
var duration = moment.duration( diffTime, 'milliseconds' );
var interval = 0;
var counter = setInterval(function () {
$('div#countdown').text( moment.duration( duration.asSeconds() - ++interval, 'seconds' ).format( tFormat, { trim: false }) );
if( stopAtZero && interval >= seconds ) clearInterval( counter );
}, 1000);
};
$('div#countdown').countdown( 30*60, 'mm:ss' );
</script>
<div id="countdown"></div>
Edit: RESOLVED. The function was fine. It just needed to come after the Div (or after Document Load) ::headdesk::