Search code examples
javascripttimercountdown

Strange problem with JavaScript code


Hi Masters Of Web Development, first I want to say that I did not believe in my eyes - I've got a piece of javascript that works just fine in IE7, and don't in Firefox!!! :)))) That was little joke. :) So I already told you the problem (it wasn't joke), now I'm pasting the 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 very old script I know that. It takes my current remaining song time, from my winamp and countdowns in site. But as I said, it does not work in Firefox.

Body and code that calls 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 look 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

Solution

  • The problem is that it's accessing DOM elements by name.

    Add the following code to the top to declare a variable for the thetime element, add id="thetime" to the INPUT, and add a call to init(); in onload in the body element.

    var thetime;
    
    function init() {
        thetime = document.getElementById('thetime');
    }
    

    By the way, you can replace the textbox with a regular DIV element by setting the div's ID to thetime, and replacing thetime.value with thetime.innerHTML.

    Also, it's better to call setTimeout with a function instead of a string; you should replace "display();" and "recalc();" with display and recalc respectively.