Mike Mike - 5 months ago 10
Javascript Question

Onclick function arguments

I am trying to simulate a number counting up from 0 to 100 and I am having issues.
First I tried to use a for loop and send the iteration values to an

.innerHTML div
but it only showed the last number. So I searched online for a an animated javascript counter and I found this one: http://jsfiddle.net/jfriend00/aJrj4/.

It works for my needs however I am not sure how to apply this so that it can be triggered by a button. This script is written with argument inputs when the function is defined, and then passes them at the end by running the function after wards.
I cant figure out how do I input arguments for an
onclick
event?
This was my attempt but I keep getting errors, specifically with the
onclick
line.

var loadSim_btn = document.getElementsByTagName('button')[0];

loadSim_btn.onclick=function load_Sim(pCent, 25, 100, 2000);

function load_Sim (pCent, start, end, duration) {
var range = end - start;
// no timer shorter than 50ms (not really visible any way)
var minTimer = 50;
// calc step time to show all interediate values
var stepTime = Math.abs(Math.floor(duration / range));
// never go below minTimer
stepTime = Math.max(stepTime, minTimer);
// get current time and calculate desired end time
var startTime = new Date().getTime();
var endTime = startTime + duration;
var timer;

function run() {
var now = new Date().getTime();
var remaining = Math.max((endTime - now) / duration, 0);
var value = Math.round(end - (remaining * range));
obj.innerHTML = value;
if (value == end) {
clearInterval(timer);
}
}

timer = setInterval(run, stepTime);
run();
}


ANSWER:
So the from what I can tell one issue was I forgot the obj definition line. In addition Joshua Davison answered my main question.
"The onclick callback doesn't provide arguments, so we wrap the function call in an anonymous function (that takes no arguments)"
So my options for assigning the button in java script was:


loadSim_btn.onclick=function() { load_Sim(pCent, 25, 100, 2000); }


and using an Event Listener:


loadSim_btn.addEventListener("click", function() { load_Sim(pCent,
25, 100, 2000); }, true);

Answer

The onclick callback doesn't provide arguments, so we wrap the function call in an anonymous function (that takes no arguments)

loadSim_btn.onclick=function() { load_Sim(pCent, 25, 100, 2000); }

May I also recommend that you use event listeners rather than using onclick

loadSim_btn.addEventListener("click", function() { load_Sim(pCent, 25, 100, 2000); }, true);

Lastly, rather than using getElementsByTagName(...)[0], it's preferable to use getElementById("btnId") if possible (only one element should have that ID) - and add id="btnId" to the button in the HTML

I hope this turns out OK (posting from my phone).