Hi Guys,
While I was working for a project I was doing some basic things, one of which was to display a counter of 10 seconds and then firing up a callback function.
Now I know this may not be the best out there but its extendible and you can add animations and that kinda stuff to it.
Pre-requisites
- jQuery library
- Javascript enabled in browser
Here is the code snippet
[geshi lang=”javascript” nums=”1″ target=”_self” ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
jQuery.fn.simpleCountDown = function(settings,whereat) { settings = jQuery.extend({ interval: 1000, startFrom: 10, endAt: 0, callBack: function() { } }, settings); return this.each(function() { if(whereat == null && whereat != settings.endAt) { whereat = settings.startFrom; } jQuery(this).text(whereat); if(whereat > settings.endAt) { whereat = whereat-1; var eleCont = jQuery(this); setTimeout(function(){ eleCont.simpleCountDown(settings, whereat);},settings.interval); } else { jQuery(this).text("Done"); settings.callBack(this); } }); }; |
And this is how you use it
First a container. This can be anything a Div, span, p etc but with a unique ID
[geshi lang=”html5″ nums=”1″ target=”_self” ]
1 |
And now lets call our jquery function on above div
[geshi lang=”javascript” nums=”1″ target=”_self” ]
1 |
jQuery("#countdown").simpleCountDown({interval:1000,startFrom:10,callBack:function(){alert('done');}}); |
1 |
Above function will fire alert after 10 seconds. You can control the interval between each step and Max and min range.
I hope this helps
To improve this function please add your input in comments.
Cheers,
Advertisement
Leave a Reply