I'm writing a small JavaScript game.
The code I'm looking at is this bit:
cells[i].onmouseover = function() {
cells[i].style.top =
(cells[i].getAttribute('data-top') - 25).toString() + "px";
}
Each cells[i] element is a member of an array of <img>
elements.
Currently, whenever I hover over an img element it generates the following error:
Uncaught TypeError: Cannot read property 'style' of undefined
I can't work out what's going on. Why is cells[i]
undefined?
Here's all the potentially relevant code:
for(var i = 0; i < mapSize; ++i) {
cells[i] = document.createElement('img');
cells[i].src = 'base1.png';
cells[i].class = 'base1';
cells[i].id = 'cell' + i;
game.appendChild(cells[i]);
row = Math.floor(i / mapWidth);
top = tops[i%mapWidth + row];
left = lefts[mapWidth + (i % mapWidth) - row];
cells[i].setAttribute('data-top',top);
cells[i].setAttribute('data-left',left);
cells[i].style.top = top.toString() + "px";
cells[i].style.left = left.toString() + "px";
cells[i].style.zindex = i;
console.log(cells[i]);
cells[i].onmouseover = function() {
cells[i].style.top =
(cells[i].getAttribute('data-top') - 25).toString() + "px";
}
}