Javascript, problem with binding an event to a div-tag

Posted by Patrick on Stack Overflow See other posts from Stack Overflow or by Patrick
Published on 2010-03-14T20:55:57Z Indexed on 2010/03/14 21:05 UTC
Read the original article Hit count: 156

Filed under:
|
|
|
|

Hello, i am trying to bind an event to a dynamically created div.

function GameField(playerNumber) {
this.fields = new Array();
this.player = playerNumber;
this.isPlayerActive = false;
this.currentRound = 0;
}

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';
    newField.onclick = function() { this.DivClick('a'); }
    this.fields[fieldNumber] = newField;
    return newField;
}

GameField.prototype.DivClick = function(fieldNumber) {
    alert('Nummer: ' + fieldNumber);
}

Everything works perfectly, but when you click on one of the created divs, i end up with the following error message: Error: Object doesn't support this property or method.

If i replace the onclick function with this, then it works:

newField.onclick = function() { alert('Nummer: ' + fieldNumber); }

How can i get the onclick event to fire my DivClick function instead?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about function