Strange problem with JavaScript code
Hi web development masters, first I want to say that I didn't believe in my eyes - I have a piece of javascript that works great in IE7, and not Firefox! :)))) It was a little joke. :) So i already told you the problem (it was no joke), now i am embedding javascript:
<script type="text/javascript">
<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Begin
var ms;
ms = %%CONTENT_REFRESH%% - 5;
var stop;
stop = 0;
var myvalue;
function display() {
if (!stop) {
setTimeout("display();", 1000);
}
thetime.value = myvalue;
}
function recalc() {
var hours;
var minutes;
var seconds;
ms = ms - 1;
hours = Math.floor(ms / 3600);
minutes = Math.floor(ms / 60);
if (minutes < 10) {
minutes = "0"+minutes;
}
seconds = ms - (minutes*60) - (hours*3600);
if (seconds < 10) {
seconds = "0"+seconds;
}
myvalue = hours+":"+minutes+":"+seconds;
thetime.value = myvalue;
if (myvalue == "0:00:00") {
stop = 1;
}
if (!stop) {
setTimeout("recalc();", 1000);
}
}
// End -->
</SCRIPT>
This is a very old script I know that. This will take my current remaining song time, from my winamp and countdown on the site. But as I said, it doesn't work in Firefox.
The body and code that calls the countdown timer looks like this:
<body class="playlist_body" onLoad="recalc();display();">
Time Left In Song: <INPUT align="center" TYPE="text" Name="thetime" size=5 />
</body>
// Edit: I was looking at FireBug and I saw the following error:
thetime is not defined
recalc()playlist.cgi (line 87)
function onload(event) { recalc(); display(); }(load )1 (line 2)
error source line: [Break on this error] thetime.value = myvalue;\n
source to share
The problem is that it refers to DOM elements by name.
Add the following code at the beginning to declare a variable for an element thetime
, add id="thetime"
in, INPUT
and add a call init();
to onload
in an element body
.
var thetime;
function init() {
thetime = document.getElementById('thetime');
}
By the way, you can replace the textbox with a regular element DIV
by setting the DIV
ID to thetime
and replacing thetime.value
to thetime.innerHTML
.
Also, it's better to call setTimeout with a function instead of a string; you must replace "display();"
both "recalc();"
with display
and recalc
accordingly.
source to share