i'm new in JS, i have a 3x3 table filled as below:
<table id="mytable">
<tr>
<td id="1" onclick="select_home(1)"></td>
<td id="2" onclick="select_home(this.id)"></td>
<td id="3" onclick="select_home(this.id)"></td>
</tr>
<tr>
<td id="4" onclick="select_home(this.id)"></td>
<td id="5" onclick="select_home(this.id)"></td>
<td id="6" onclick="select_home(this.id)"></td>
</tr>
<tr>
<td id="7" onclick="select_home(this.id)"></td>
<td id="8" onclick="select_home(this.id)"></td>
<td id="9" onclick="select_home(this.id)"></td>
</tr>
</table>
im updating template whenever a click happen on tables as below:
var table = document.querySelector("table");
// listen for a click
table.addEventListener("click", function (ev) {
// get the event targets ID
var serviceID = ev.target.id;
turn() ? blue_checked(serviceID) : red_checked(serviceID);
});
function blue_checked(id) {
var table = document.getElementById("mytable").getElementsByTagName("td");
selected_home_blue.push(id);
table[id - 1].style.backgroundColor = "blue";
check_game(selected_home_blue, "blue");
}
i am updating background color of td's first then run check_game function but check_game run first and then td background color change, how can i handle it ?
CodePudding user response:
I simplified your cell-coloring code. You can directly get the table cell that needs to be colored using the id. You can show a message with your own div instead of using an alert()
. This prevents the problem that the alert()
always shows before the DOM is actually changed.
const table = document.querySelector("table");
const messagebox = document.querySelector("message");
// listen for a click
table.addEventListener("click", function (ev) {
// get the event targets ID
const serviceID = ev.target.id;
blue_checked(serviceID); // example for blue
});
function blue_checked(id) {
const tablecell = document.getElementById(id);
tablecell.style.backgroundColor = "blue";
showMessage("blue played")
}
function showMessage(msg) {
messagebox.innerText = msg
}
And in your HTML add the message box
<div id="message"></div>