Today I wrote my first plugin: a simple tool so that the number in an element is counted up. It works great, but I built it on the following examples and some trial and error, so I canβt say that I understand how it works completely.
I do not understand:
a) How should I include convenient functions, such as the secondsToTime() function (if I need it to be in the function), I understand that this is not the case in this example.) Why does it work here from within this block.
b) How are variables declared ( _this, seconds, interval ) declared? All of them are saved simultaneously for each item.
c) Can this plugin be structured better?
code:
$(document).ready(function(){ $('.ticker').countup(); }); (function($) { $.fn.countup = function() { return this.each(function(){ var _this = this, seconds = parseInt($(this).text()), interval = setInterval(updateTicker, 1000 ); updateTicker(); function updateTicker(){ seconds += 1; time = secondsToTime(seconds); outputtime = time.h + ":" + ((time.m <= 9) ? '0' + time.m : time.m) + ":" + ((time.s <= 9) ? '0' + time.s : time.s) $(_this).text(outputtime); } function secondsToTime(secs){ var hours = Math.floor(secs / (60 * 60)); var divisor_for_minutes = secs % (60 * 60); var minutes = Math.floor(divisor_for_minutes / 60); var divisor_for_seconds = divisor_for_minutes % 60; var seconds = Math.ceil(divisor_for_seconds); var obj = { "h": hours, "m": minutes, "s": seconds }; return obj; } }); }; })(jQuery);
Thanks for your feedback.
source share