I have this snippet of code below in which what I wanted was when I hover through a table header, the whole column below it will change its background color. My code seem to only change the first iteration but not the rest of data below it. How can I can change my code to do it that way?
JS:
function chooseColumn() {
document.getElementById("table-data-sl-envb").style.background = "red";
}
function outColumn() {
document.getElementById("table-data-sl-envb").style.background = "#B5EB74";
}
HTML:
<tr>
<th class="table-header-otp" id="table-header-otp" onmouseover="chooseColumn();" onmouseout="outColumn();";>Time</th>
</tr>
PHP
<?php
foreach ((array) $parseData as $data) {
$timeData = explode(",",$data);
?>
<tr>
<td class="table-data-otp" id="table-data-otp"><?=$timeData[0]?><`your text`/td>
</tr>
<?php
}
?>
I’m still new to these langauges and I have browsed through all of the pages in w3schools but I still couldn’t make it work the way I wanted it to
3
Answers
This is the simple way to do it. put the id on
<td></td>
too.Rather than using ID attributes and inline event handlers you could use two externally registered delegated event handlers that use the
event
to find and identify cells within the table.In the below code – the event (on a
th
) is used to find theindex
( the number of theth
within the collection for this table ) and that index is then used to identify table-cells of the same index (ie: column)For a simple Table structure as below this works fine but has not been tested with a more complex example that uses
rowspan
orcolspan
attributes to merge rows/columns – but there are no hardcoded IDs and this would scale to any number of rows.It can be quite fiddly going thro’ with JS.
Just for interest, here’s an alternative using only CSS – which you could create in PHP once the number of columns is known if required.