So I'm trying to create a table where if the mouse is over a cell in the table, the background color will change. The table is pretty big (8 x 19), so I'm creating it dynamically. Here's my overall code
<html>
<meta charset="UTF-8">
<body>
Test
<table id="scheduling"></table>
</body>
<style>
body {
color: red;
}
table,
th,
tr {
border: 2px solid black;
width: 10vw;
}
</style>
<!--<link rel="stylesheet" type="text/css" href="scheduler.css">-->
<script>
function createSchedulingTable() {
var scheduling = document.getElementById("scheduling");
var firstrow = document.createElement('tr');
var categories = ['Times', 'S', 'M', 'T', 'W', 'R', 'F', 'Sa'];
for (var a = 0; a < 8; a++) {
var th = document.createElement('th');
th.innerHTML = categories[a];
firstrow.appendChild(th);
}
scheduling.appendChild(firstrow);
for (var a = 0; a < 18; a++) {
var therow = document.createElement('tr');
therow.innerHTML = (a + 7) + ':00';
if (a + 7 == 24) {
therow.innerHTML = '0:00';
}
for (var b = 0; b < 7; b++) {
var th = document.createElement('th');
th.id = ' cell' + a + ',' + b;
th.onmouseenter = function() {
highlight(th);
};
th.onmouseout = function() {
dehighlight(th);
};
th.innerHTML = 'cell';
therow.appendChild(th);
}
scheduling.appendChild(therow);
}
}
createSchedulingTable();
function highlight(element) {
//alert('highlighting ' + this.id);
element.style.background = 'yellow';
}
function dehighlight(element) {
//alert('highlighting ' + this.id);
element.style.background = 'white';
}
</script>
</html>
Everything looks good to me. But when I test it out, only the very last table cell (bottom right corner) will change its background color. Any cell I put my mouse in, only that very last cell will glow yellow. It's almost as if the code is removing the previous onmouseenter for the previous element and replacing it with a new one. Why is this happening?