I have a peice of code that counts from 0 to a specified number and displays it while it is counting.
The problem is that I want to use the code in a web app that is made using jQuery mobile.
When the code is used with normal html i works fine, but when I use it with jQuery mobile it wont work.
I dont want the number to start counting until a certain mobile page is loaded, is there a way to do this??
I think the problem is because in jquery mobile all of the pages are contained within one html document and the number sarts counting when the html page is open and I want it to start when the ‘#about’ section is displayed?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#foo').counter({
start: 1000,
end: 400000,
time: 1,
step: 50,
callback: function() {
$("#foo").html("400000");
}
});
});
;(function($) {
$.fn.counter = function(options) {
var options = $.extend(defaults, options);
var counterFunc = function(el, increment, end, step) {
var value = parseInt(el.html(), 10) + increment;
if(value >= end) {
el.html(Math.round(end));
options.callback();
} else {
el.html(Math.round(value));
setTimeout(counterFunc, step, el, increment, end, step);
}
}
$(this).html(Math.round(options.start));
var increment = (options.end - options.start) / ((1000 / options.step) * options.time);
(function(e, i, o, s) {
setTimeout(counterFunc, s, e, i, o, s);
})($(this), increment, options.end, options.step);
}
})(jQuery);
</script>
<style type="text/css">
</style>
</head>
<body>
<span id="foo"></span>
</body>
</html>
Check-out the events documentation for jQuery Mobile: http://jquerymobile.com/demos/1.0rc1/docs/api/events.html.
Rather than running your code on
document.readyyou want to run it onpageshow.Change:
To:
I have not used the “counter” plugin so I’m not sure how to do it but you may want to stop the counter when the user navigates to another page, to do so just bind whatever code stops the counter to the
pagehideevent:A NOTE: I use the
.delegate()function in the examples above which when used on the$(document)object acts like the.live()function:$(document).delegate('#about', 'event-name', function () {});is similar to$(#about).live('event-name', function () {});however.delegate()performs more efficiently. Documentation for delegate is here: http://api.jquery.com/delegate/