Jump to content

changing cells in a javascript generated table.


studsm

Recommended Posts

Howdy everyone. I'm working on a school assignment and can't seem to quite find the answers i need in the w3 tutorials. I have this js file that generates an empty grid

 

var text = "<table class = 'BSGrid'>";
function generateGrid(row, col)
{
var cells = 0;
for (var j = 0; j < row; j++)
{
text += "<tr>";
for (var i = 0; i < col; i++)
{
text += "<td class = 'cells'><div id = 'myTableId" + cells + "'></div> " + " " + "</td>";
cells++;
}
text += "</tr>";
}
text += "<br><br></table>";
document.getElementById("player1").innerHTML = text + "<br><br>";
document.getElementById("player2").innerHTML = text;
}
I need to make it so that when i click on any individual cell it will change the background color or whatever else I want to do, but if you can just show me how to make it change the background color i'll figure the rest out. This is what I have tried but it doesn't seem to work I could just be missing a simple thing or it could be completely wrong so just let me know please :)
var terd = document.getElementById("player1");
var cells = terd.getElementsByTagName("td");
for (var i = 0; i < 100; i++)
{
cells.onclick = onClickHandler;
}
function onClickHandler()
{
this.innerHTML += "style = 'background-color: #00CED1;'"
}

 

Link to comment
Share on other sites

The onclick event can be put on anything. It can be a button or any other element.

 

What matters is how you modify the CSS, which is shown clearly in that tutorial page. What part of it do you have trouble understanding?

Link to comment
Share on other sites

This is way wrongthis.innerHTML += "style = 'background-color: #00CED1;'"You are just adding this as text within the clicked td cellTo apply css styling to current clicked td use .stylethis.style.theStylePropertyYouWishToApplyINcamelCase="theStylePropertyValue";

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...