Search code examples
javascripthtmlcssonclickchess

Javascript Chessboard Pattern, onclick function help (basic)


function vnos(){
var visina=prompt("Vnesi Visino Sahovnice");
var sirina=prompt("Vnesi Sirino Sahovnice");
document.write("<table>");
for(var i=1; i<=visina; i++)
{
    document.write("<tr>");
    for(var j=1;j<=sirina; j++)
    {
        if(i%2==0){
            if(j%2==0){document.write("<td onclick='myFunction()' class='rdeca'></td>");}
            else{document.write("<td onclick='myFunction()' class='crna'></td>");}
        }
        else{
            if(j%2==0){document.write("<td onclick='myFunction()' class='crna'></td>");}
            else{document.write("<td onclick='myFunction()' class='rdeca'></td>");}
        }   
    }
    document.write("</tr>");    
}
document.write("</table>");}

So the first function serves to create a chess board and as input on how many rows and columns you want. I'm trying to do an onclick even whcih will change the color of a single cell, and i'm not sure what's the correct way of doing that. The second function serves as the onclick function which will change the color. The html document has css in it and the css is working.

function myFunction(){
document.getElementById("celica").className="bela";
}

Solution

  • when you call a clickhandler, the context (this) is set to the element, so you can pass it to the handler function like this:

     <td onclick='myFunction(this)' class='rdeca'></td>
    

    then on myFunction you can do:

    function myFunction(cell) {
        cell.className="bela";                // set clicked classname
        cell.style.backgroundColor="red";     // set clicked backgroundcolor
        cell.innerHTML="clicked on me";       // set clicked html content
    }