Javascript onclick stops working, multiple dynamically created divs.

Posted by Patrick on Stack Overflow See other posts from Stack Overflow or by Patrick
Published on 2010-03-16T18:17:01Z Indexed on 2010/03/16 18:21 UTC
Read the original article Hit count: 285

Filed under:
|
|
|
|

I have run into a strange problem, i am creating a lot of dynamically divs. And i recently found out that some of my divs doesn't fire the onclick event? All the divs are created using the same template, so why are some not working? Most of the time, its the 4-5 from the bottom. If you click on one of the others and then try again, you might get one of those to trigger. But only sporadically.

Code to create the divs:

GameField.prototype.InitField = function(fieldNumber) {
var newField = document.createElement("div");
if (fieldNumber == 0 || fieldNumber == 6 || fieldNumber == 8 || fieldNumber == 17)
    newField.className = 'gameCellSmall borderFull gameText gameTextAlign';
else
    newField.className = 'gameCellSmall borderWithoutTop gameText gameTextAlign';

var instance = this;
if (fieldNumber == 6 || fieldNumber == 7 || fieldNumber == 17) { }
else
    newField.onclick = function() { instance.DivClick(fieldNumber); return false; }

this.fields[fieldNumber] = newField;
this.score[fieldNumber] = 0;
return newField;
}

I added the return false to the click function, but it still behaves strangely. Why are some not triggering? I create around 18 divs / player. But it happens even if i just create one player.

Do i perhaps need to cancel the event once i am done with it? (Like the return false; is trying to do)

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about div