So I have two scripts on a page:
- The first one randomly chooses a number from an array and inserts it into an element called ‘number’.
- The second one is a countdown script which counts down from two variables which are interpreted as minutes and seconds. It then plays a sound once the countdown has reached zero.
At the moment, the second script is all manually set-up, so the number of minutes and seconds are hard-coded into the script itself. I’d like the second script to take whatever number was inserted into the page by the first script, and use it as its variable.
Here’s a better example of how I’d like it to work:
You load the page, and it tells you that you only have (X) minutes to spare (X = inserted by first script), and whatever (X) is, acts as the ‘minutes’ variable in the second script, which is now displaying a countdown from (X) minutes elsewhere on the page.
The first script’s output is inserted into:
<span id="minutes"></span>
And here’s the code for the second script (the one that needs changing):
var interval;
var minutes = 5;
var seconds = 0;
window.onload = function() {
countdown('countdown');
}
function play(file) {
var embed = document.createElement("embed");
embed.setAttribute('src', file);
embed.setAttribute('hidden', true);
embed.setAttribute('autostart', true);
document.body.appendChild(embed);
}
function countdown(element) {
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
el.innerHTML = "Time's up!";
clearInterval(interval);
play('alarm.mp3');
return;
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? 'seconds' : 'second';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
seconds--;
}, 1000);
}
I’ve tried changing
var minutes = 5;
var seconds = 0;
to
var minutes = document.getElementById(minutes);
var seconds = 0;
(the second script runs after the first one)
… but it doesn’t seem to work, just starting at ‘null’ minutes.
Could anyone shed any light on this?
Solution:
Explanation:
You probably mean the string minutes: (add quotes)
But that returns the DOM object. The innerHTML will return what is inside the
<span>tagBut then you need to realise that it is a string everywhere it is used, so that where you might have had implicit type conversions with
string + numberyou will now have to do it explicitly, or change code to allow for implicit conversion, or handle it when you first instantiate minutes.Thus we do the type conversion using
Number()