Mumblesxoxo Mumblesxoxo - 5 months ago 13
Javascript Question

Running the same javascript for multiply onclicks

Basically I want to create a directory of links, each time the link gets clicked it restarts that links timer.

<Script> function countdown(elementName, minutes, seconds) {
var element, endTime, hours, mins, msLeft, time;

function twoDigits(n) {
return (n <= 9 ? "0" + n : n);
}

function updateTimer() {
msLeft = endTime - (+new Date);
if (msLeft < 1000) {
element.innerHTML = "countdown's over!";
} else {
time = new Date(msLeft);
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours + ':' + twoDigits(mins) : mins) + ':' + twoDigits(time.getUTCSeconds());
setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
}
}


element = document.getElementById(elementName);
endTime = (+new Date) + 1000 * (60 * minutes + seconds) + 500;
updateTimer();
}
</script>

<p>
<a onclick='countdown("countdown",
120,0);' href="https://www.bing.com/" target="_blank">Bing</a>
<div id="countdown"></div>
</p>

<p>
<a onclick='countdown("countdown2",
120,0);' href="https://www.google.com.au/" target="_blank">Google</a>
<div id="countdown"></div>
</p>


The problem that I have is that this will only run one countdown.

Is there a simply way that each link has it's own timer without having a script for each one?

Answer

Use different div id's for countdown.

<a onclick='countdown("countdown1",
120,0);' href="https://www.bing.com/" target="_blank">Bing</a>
<div id="countdown1"></div>
</p>

<p>
<a onclick='countdown("countdown2",
120,0);' href="https://www.google.com.au/" target="_blank">Google</a>
<div id="countdown2"></div>
</p>