Cause of issue
In you hitTest()
function i
has the value as of exit by loop when event is triggered. Thus it is length of allMyLabels
which does not exist. (Last ++
makes it go over.) As a result we get allMyLabels[ number of allMyLabels ]
, and as index start at 0
, that is a non existent element.
In short
If we have:
allMyLabels === [
label[0], // allMyLabels[0]
label[1], // allMyLabels[1]
label[2] // allMyLabels[2]
];
allMyLabels.length === 3
allMyLabels[3] === undefined
Solution
You would need to wrap it in to an anonymous function, or (as I prefer), use bind (note Polyfill section).
»Sample fiddle«
divs = document.getElementsByTagName('DIV');
function change_div(i, e) {
divs[i].innerHTML = "Hello " + i + ", " + e.timeStamp;
}
function ok_one() {
dl = divs.length;
for (i = 0; i < dl; ++i) {
divs[i].addEventListener("mouseover", change_div.bind(this, i));
// | |
// | +-- Current i
// +------- Or null
}
}
Using (anonymous) function wrap, (from what I have heard named functions leak in IE).
for (i = 0; i < dl; ++i) {
divs[i].addEventListener("mouseover", (function(k) {
// | |
// | +---- Passed current i.
// +-------------- Wrap and execute.
//
// Name it "i" if you want
// +---- Return function having CURRENT environment, thus k === i.
// |
return function(e) {
divs[k].innerHTML = "Hello " + k + ", " + e.timeStamp;
}
})(i));
// | |
// | +----- Pass current loop i to function AND execute it NOW.
// +------- Wrap end.
//
}