473,473 Members | 2,215 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Script doesn't work in Safari

I've got a short script that works fine in I.E. and Firefox, but not in
Safari. It is supposed to print a constantly-updating counter on the
webpage. Any ideas how to get it to work in Safari? The script uses the
Date object, especially Date.getTime(). Could that have something to do
with the problem?

Thanks,

E
// This <form> is put into the same HTML page as the script...
<form name="counter" style="margin: 0; padding: 0;">
<input type="text" name="amount" value="0" size="40" readonly="true"
style="margin:0;padding:0;border:none;font-size:24px;color:#cc0000;">
</form>

// Here is the script...
<script type="text/javascript">

// The formatNumber function comes from Danny Goodman's JavaScript
Cookbook.
[ ... some code left out here for brevity ... ]

var startingDate = new Date(2005, 0, 1);
var startingDebt = 1000000000;
function updateCounter(){
var nowDate = new Date();
var debtTimeInSeconds = (nowDate.getTime() -
startingDate.getTime())/1000;
var newValue = startingDebt + (debtTimeInSeconds * 3.47);
document.counter.amount.value = "$" + formatNumber(newValue, 2);
}
updateCounter();
intervalID = setInterval("updateCounter()", 1000);
</script>

Jul 23 '05 #1
13 2212
elektrophyte wrote:
I've got a short script that works fine in I.E. and Firefox, but not in
Safari. It is supposed to print a constantly-updating counter on the
webpage. Any ideas how to get it to work in Safari? The script uses the
Date object, especially Date.getTime(). Could that have something to do
with the problem?

Thanks,

E
// This <form> is put into the same HTML page as the script...
<form name="counter" style="margin: 0; padding: 0;">
<input type="text" name="amount" value="0" size="40" readonly="true"
style="margin:0;padding:0;border:none;font-size:24px;color:#cc0000;">
</form>

// Here is the script...
<script type="text/javascript">

// The formatNumber function comes from Danny Goodman's JavaScript
Cookbook.
[ ... some code left out here for brevity ... ]

var startingDate = new Date(2005, 0, 1);
var startingDebt = 1000000000;
function updateCounter(){
var nowDate = new Date();
var debtTimeInSeconds = (nowDate.getTime() -
startingDate.getTime())/1000;
Manually wrap posted code at about 70 characters, allowing
auto-wrapping can cause problems and with space indents not tabs.

You also don't need the 'getTime()' method:

var debtTimeInSeconds = (nowDate - startingDate)/1000;

var newValue = startingDebt + (debtTimeInSeconds * 3.47);
document.counter.amount.value = "$" + formatNumber(newValue, 2);
}
updateCounter();
intervalID = setInterval("updateCounter()", 1000);
</script>


It works fine in Safari 1.0.3 as far as I can tell if you remove the
'formatNumber()' function. Post it for a fix.
--
RobG
Jul 23 '05 #2
RobG wrote:
elektrophyte wrote:
[...]
It works fine in Safari 1.0.3 as far as I can tell if you remove the
'formatNumber()' function. Post it for a fix.


A little more playing shows that the debit in cents seems to exceed the
size of integer that Safari can handle. I'll guess that the Danny
Goodman's function converts the amount to cents and uses Math.floor (or
round maybe) to truncate the decimal cents.

Here's a version of the script that uses a modified version of Dr J R
Stockton's 'TryCash()' function (which originally was based on cents
but I've modified it to use decimal currency). Lightly tested (Firefox
& Safari on OS X):
<script type="text/javascript">

var startingDate = new Date(2005,0,1);
var startingDebt = 1000000000;

function updateCounter(){
var nowDate = new Date();
var debtTimeInSeconds = (nowDate - startingDate)/1000;
var newValue = startingDebt + (debtTimeInSeconds * 3.47);
document.counter.amount.value = TryCash(newValue + ' $ , .');
}
updateCounter();
intervalID = setInterval("updateCounter()",1000);

function toCash(p, c, t, d) {
var s = (0 > p)? "-" : "";
p = p.split('.');
var m = String(Math.abs(p[0]));
var j, k = "", f;
c = c || "";
t = t || "";
d = d || ".";
while (m.length < 3) {
m = "0"+m;
}
f = (p[1])? twoDigits(p[1]) : '00';
j = m.length;
while (j > 3) {
k = t+m.substring(j-3, j)+k;
j -= 3;
}
k = m.substring(0, j)+k;
return s+c+k+d+f;
}

function TryCash(S) {
var T = S.split(/\s+/);
return toCash(T[0], T[1], T[2], T[3]);
}

function twoDigits(x){
return (x.length < 2)? x+'0' : x.substring(0,2);
}

</script>

--
RobG
Jul 23 '05 #3
JRS: In article <428e9d89$0$956$5a62ac22@per-qv1-newsreader-
01.iinet.net.au>, dated Sat, 21 May 2005 12:31:32, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.auau> posted :
RobG wrote:
elektrophyte wrote:

[...]

It works fine in Safari 1.0.3 as far as I can tell if you remove the
'formatNumber()' function. Post it for a fix.


A little more playing shows that the debit in cents seems to exceed the
size of integer that Safari can handle.
...


Which is?

Does Safari actually have a distinct integer type?

Is it just that Math.floor .ceil .round use Int32 internally (so that
they may have the mechanism for returning larger numbers, but never
generate them)?

AFAIR, according to spec, the only things that should be limited to
Int32 are the seven operators ~ & | ^ << >> >>> and their assignment
forms.

~~X appears to truncate X towards zero and do a signed modulo
2^32 on it. There must be a use for that.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #4
Thank you very much for the replies. As suggested I removed the
getTime() and formatNumber() calls and now it works in Safari. Now I
just need to debug formatNumber(). I got it from Danny Goodman's
JavaScript Cookbook (Oreilly). Maybe I'll just try to write my own
function to format the number. In case anyone is curious, I'll add
Goodman's code below.

// The formatNumber function comes from Danny Goodman's
// JavaScript Cookbook.
function formatNumber (num, decplaces) {
// convert in case it arrives as a string value
num = parseFloat(num);
// make sure it passes conversion
if (!isNaN(num)) {
// multiply value by 10 to the decplaces power;
// round the result to the nearest integer;
// convert the result to a string
var str = "" + Math.round (eval(num) *
Math.pow(10,decplaces));
// exponent means value is too big or small
// for this routine
if (str.indexOf("e") != -1) {
return "Out of Range";
}
// if needed for small values, pad zeros
// to the left of the number
while (str.length <= decplaces) {
str = "0" + str;
}
// calculate decimal point position
var decpoint = str.length - decplaces;
// assemble final result from: (a) the string
// up to the position of
// the decimal point; (b) the decimal point;
// and (c) the balance
// of the string. Return finished product.
return str.substring(0,decpoint) + "." +
str.substring(decpoint,str.length);
} else {
return "NaN";
}
}

Jul 23 '05 #5
elektrophyte wrote:
Thank you very much for the replies. As suggested I removed the
getTime() and formatNumber() calls and now it works in Safari. Now I
just need to debug formatNumber(). I got it from Danny Goodman's
JavaScript Cookbook (Oreilly). Maybe I'll just try to write my own
function to format the number. In case anyone is curious, I'll add
Goodman's code below.


Here's another that can handle any precision and adds commas. Remove
validation and comments and it's only marginally longer that DG's.
function formatDecimal(n, d) {
// Is n digit(s) with optional point or optional point and digit(s)
if ( !/^(\d+)[\.|(\.\d+)]*$/.test(n) ) {
return "Number part should be format 0 or 0.0";
}

// Is d an int?
if ( !/^(\d+)[\.|(\.0+)]*$/.test(d) ) {
return "Number of decimal places must be an integer";
}

// nd is number of digits before zero
var nd = (n + '').split('.')[0].length;

// len is total number of digits required
var len = +d + nd;

// n is array of digits with decimal place removed
n = n.replace(/\./,'').split('');

// If there is a digit after required length, do rounding,
var i=len, r='';

// If last+1 digit is bigger than 4
if ( n[i] && n[i] > 4 ){
// While preceding number is 9 and not first
while ( 9 == n[--i] && i > 0 ) {
// Make it zero
n[i] = 0;
}
// Add one to wherever we got to
n[i] -= -1;
}

// Build up integer part
i = 0;
while ( i < nd ) {
// No commas version;
// r += '' + n[i++];

// Commas version
r += (( (nd-i)%3 )? '' : (0 == i)? '':',') + n[i++];
}

// Add decimal part
if ( d > 0 ) {
r += '.';
while ( i < len ) {
r += n[i++] || '0';
}
}
return r;
}
--
Rob
Jul 23 '05 #6
RobG wrote:
[...]
Here's another that can handle any precision and adds commas. Remove
validation and comments and it's only marginally longer that DG's.
I should post sooner, I'd find the bugs quicker...


function formatDecimal(n, d) {
// Is n digit(s) with optional point or optional point and digit(s)
if ( !/^(\d+)[\.|(\.\d+)]*$/.test(n) ) {
return "Number part should be format 0 or 0.0";
}

// Is d an int?
if ( !/^(\d+)[\.|(\.0+)]*$/.test(d) ) {
return "Number of decimal places must be an integer";
}

// nd is number of digits before zero
var nd = (n + '').split('.')[0].length;

// len is total number of digits required
var len = +d + nd;

// n is array of digits with decimal place removed
n = n.replace(/\./,'').split('');

// If there is a digit after required length, do rounding,
var i=len, r='';

// If last+1 digit is bigger than 4
if ( n[i] && n[i] > 4 ){
// While preceding number is 9 and not first
while ( 9 == n[--i] && i > 0 ) {
// Make it zero
n[i] = 0;
}
// Add one to wherever we got to
n[i] -= -1;
}


If the number is 999.9, result is 1000.0 not 1,000.0. Here's the fix:

// Add one to wherever we got to
n[i] -= -1;

// Make sure it's not '10'
if ( 10 == n[i] )
n[i] = 0;
n.splice(i,0,'1');
}

If the 'comma' output is not required, the fix isn't needed.

[...]

--
Rob
Jul 23 '05 #7
RobG wrote:
RobG wrote:
[...]
[...]
// Make sure it's not '10'
if ( 10 == n[i] )
n[i] = 0;
n.splice(i,0,'1');
}


Brain-dead day:

// Make sure it's not '10'
if ( 10 == n[i] ) {
n[i] = 0;
n.splice(i,0,'1');
nd++;
}


--
Rob
Jul 23 '05 #8
JRS: In article <11*********************@o13g2000cwo.googlegroups. com>,
dated Mon, 23 May 2005 11:03:26, seen in news:comp.lang.javascript,
elektrophyte <el**********@yahoo.com> posted :
Thank you very much for the replies. As suggested I removed the
getTime() and formatNumber() calls and now it works in Safari. Now I
just need to debug formatNumber(). I got it from Danny Goodman's
JavaScript Cookbook (Oreilly). Maybe I'll just try to write my own
function to format the number.
That would be unwise, unless you need the practice; many have done so
and got it wrong. Instead, read the newsgroup FAQ.
In case anyone is curious, I'll add
Goodman's code below.

// The formatNumber function comes from Danny Goodman's
// JavaScript Cookbook.
function formatNumber (num, decplaces) {
// convert in case it arrives as a string value
num = parseFloat(num);
// make sure it passes conversion
if (!isNaN(num)) {
// multiply value by 10 to the decplaces power;
// round the result to the nearest integer;
// convert the result to a string
var str = "" + Math.round (eval(num) *

^^^^

Pointless. Function parseFloat always returns a Number, even though it
may be NaN or an Infinity.

When replying, please quote, attribute & ignore Lahn :

Keith Thompson wrote in comp.lang.c, message ID
<ln************@nuthaus.mib.org> :-
If you want to post a followup via groups.google.com, don't use
the "Reply" link at the bottom of the article. Click on "show
options" at the top of the article, then click on the "Reply" at
the bottom of the article headers.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9
JRS: In article <08*****************@news.optus.net.au>, dated Tue, 24
May 2005 04:33:00, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.auau> posted :

Here's another that can handle any precision and adds commas. Remove
validation and comments and it's only marginally longer that DG's.
function formatDecimal(n, d) {

Float arithmetic has rounding errors; therefore, a Number that ideally
would be zero may be slightly negative. Your routine fails with those,
as with genuine negatives.

Also, it fails with input '5e5', though it works with '550000'

It looks rather slow, though I've not checked.

I don't see why one should want a routine that treats its parameter as a
string; but it does work with numbers that more-numeric methods would
find too big.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #10
Dr John Stockton wrote:
JRS: In article <08*****************@news.optus.net.au>, dated Tue, 24
May 2005 04:33:00, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.auau> posted :
Here's another that can handle any precision and adds commas. Remove
validation and comments and it's only marginally longer that DG's.
function formatDecimal(n, d) {
Float arithmetic has rounding errors; therefore, a Number that ideally
would be zero may be slightly negative. Your routine fails with those,
as with genuine negatives.


Yes, but the negative part could be easily fixed.

Also, it fails with input '5e5', though it works with '550000'

Yes.
It looks rather slow, though I've not checked.
Takes about 6 times longer than toFixed(), 3 times longer than simple
string truncation methods.

I don't see why one should want a routine that treats its parameter as a
string; but it does work with numbers that more-numeric methods would
find too big.


'cos it's more fun than using toFixed() :-)

toFixed() is *the* fastest method and, in the OP's case, if it's not
supported, then simply truncating the decimal cents is likely perfectly
adequate (unless decimal cents are important in what looks like US
military spending or national debt).

--
Rob
Jul 23 '05 #11
JRS: In article <RM*****************@news.optus.net.au>, dated Wed, 25
May 2005 04:01:53, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.auau> posted :

toFixed() is *the* fastest method and, in the OP's case, if it's not
supported, then simply truncating the decimal cents is likely perfectly
adequate (unless decimal cents are important in what looks like US
military spending or national debt).


AIUI, when actually doing accounts, the arithmetic must be exact, and in
compliance with applicable rounding rules.

Here, BT has recently announced that, from 2005-06-17, billed VAT will
be rounded up, rather than down, to the nearest penny. In either case,
small rounding errors such as can be expected when using non-integers
can flip the result from one state to another, when the nominal
calculation gives an exact result.

Wasting a few billion is another matter, of course; only to be expected.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #12
elektrophyte wrote:
[...]
// The formatNumber function comes from Danny Goodman's
// JavaScript Cookbook.
function formatNumber (num, decplaces) {
// convert in case it arrives as a string value
num = parseFloat(num);
// make sure it passes conversion
if (!isNaN(num)) { ^^^^^^^^^^^ // multiply value by 10 to the decplaces power;
// round the result to the nearest integer;
// convert the result to a string
var str = "" + Math.round (eval(num) * ^^^^^^^^^ Math.pow(10,decplaces));


OK, at least from now on Goodman can no longer be considered a viable
source for JS information either. Sometimes I hate it when I'm right.
PointedEars
Jul 23 '05 #13
Thomas 'PointedEars' Lahn wrote:
elektrophyte wrote:
// The formatNumber function comes from Danny Goodman's <snip> var str = "" + Math.round (eval(num) *

^^^^^^^^^
Math.pow(10,decplaces));


OK, at least from now on Goodman can no longer be considered
a viable source for JS information either.


No change then. Danny Goodman has promoted the most extraordinary -
eval - abuses over the years, and much else that is positively
discouraged by the competent.

Richard.
Jul 23 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: woodsie | last post by:
i'm looking for a back script that will work in Safari (on mac). the one below works fine in IE and netscape but not safari. <a href="#" onClick="history.go(-1)">go back</a> any help plz?
5
by: Kim Forbes | last post by:
Hi, I realize my first problem is that I'm using browser detection and not feature detection. Maybe someone can help me understand feature detection. This script works in every browser that I...
4
by: MPennig | last post by:
Here's my situation. I have a function defined in my document's <head> section which adds a <script> tag to a specified <div> tag. The added <script> has a src="" attribute pointing to a PHP file,...
4
by: Pasquale | last post by:
I am using the function below to add multiple checkbox selection to an array. The form gets submitted to a PHP script. The function works fine with IE 6, Netscape 7 and Firefox 1, but it is not...
28
by: Randy Starkey | last post by:
Hi, Does anyone know where I can get a script that show a little plus sign after a line of text, that when you click the plus sign, more text is revealed on that same page, like a continuing...
4
by: petermichaux | last post by:
Hi, I'm hoping for a reason I'm wrong or an alternate solution... I'd like to be able to dynamically include some javascript files. This is like scriptaculous.js library but their solution is...
13
by: Ralph | last post by:
Hi Is it possible to trigger the certain event from JS function? I have an image with on click event handler assigned. Now if like to trigger this event for this image from some other...
10
by: Tim Streater | last post by:
I have a form and a button to submit it. The button is made from: <input type=button onclick='myHandler(this.form);'> This all works fine except that in Safari 2.0.4, the enter/return keys, if...
7
by: mike57 | last post by:
The minimal AJAX script below works in Firefox, but not in IE, Opera, or Chrome. I could use some suggestions or referrals to resources that will help me get the script working in other browsers. ...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.