skip to Main Content

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


  1. This is the simple way to do it. put the id on <td></td> too.

    function chooseColumn() {
        document.getElementById("theader").style.background = "red";
        document.getElementById("theader2").style.background = "red";
    }
    function outColumn() {
        document.getElementById("theader").style.background = "yellow";
        document.getElementById("theader2").style.background = "yellow";
    }
    <table>
    <thead>
    <tr>
        <th id="theader" onmouseover="chooseColumn();" onmouseout="outColumn();";>Time</th>
    </tr>
    </thead>
    <tbody>
        <tr>
          <td id="theader2">1</td>
        </tr>
    </tbody>
    </table>
    Login or Signup to reply.
  2. 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 the index ( the number of the th 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 or colspan attributes to merge rows/columns – but there are no hardcoded IDs and this would scale to any number of rows.

    const d=document;
    
    let tbl=document.querySelector('table');
    
    // Mouseover delegated listener
    tbl.addEventListener('mouseover', function(e){
      /*
        inspect the `event.target` property to ensure that
        processing of the event only happens when a `th` element
        is at the root..
      */
      if( e.target instanceof HTMLTableCellElement && e.target.tagName=='TH' ){
        // Find All `th` elements and iterate through to find the specific
        // index of the event target
        [...this.querySelectorAll('th')].some((th,i)=>{
          if( e.target===th ){
            // Find ALL table Cells using nth child type syntax
            // and iterat ethrough those nodes to add the chosen highligh class
            let cells=this.querySelectorAll(`tr td:nth-of-type(${i+1})`);
                cells.forEach(td=>{
                  td.classList.add('highlight')
                })
          }
        })
      }
    });
    
    // mouseout delegated listener
    tbl.addEventListener('mouseout',function(e){
      if( e.target instanceof HTMLTableCellElement && e.target.tagName=='TH' ){
        [...this.querySelectorAll('th')].some((th,i)=>{
          if( e.target===th ){
            let cells=this.querySelectorAll(`tr td:nth-of-type(${i+1})`);
                cells.forEach(td=>{
                  // Same approach as above but remove highlight class
                  td.classList.remove('highlight')
                })
          }
        })
      }
    });
    table{
      border:1px solid grey;
      border-collapse:none;
      font-family:monospace;
    }
    td{
      border:1px dotted grey;
      padding:0.25rem
    }
    th{
      background:grey;
      color:white;
      cursor:pointer;
    }
    tbody td{
      background:#B5EB74
    }
    .highlight{
      background:rgba(255,0,0,0.5);
    }
    <table>
      <colgroup>
        <col width='33.3%' />
        <col width='33.4%' />
        <col width='33.3%' />
      </colgroup>
      <thead>
        <tr>
          <th role='columnheader'>Column 1</th>
          <th role='columnheader'>Column 2</th>
          <th role='columnheader'>Column 3</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Row 1 col 1</td>
          <td>Row 1 col 2</td>
          <td>Row 1 col 3</td>
        </tr>
        <tr>
          <td>Row 2 col 1</td>
          <td>Row 2 col 2</td>
          <td>Row 2 col 3</td>
        </tr>
        <tr>
          <td>Row 3 col 1</td>
          <td>Row 3 col 2</td>
          <td>Row 3 col 3</td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
  3. 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.

    table:has(th:nth-child(1):hover) tr>*:nth-child(1),
    table:has(th:nth-child(2):hover) tr>*:nth-child(2),
    table:has(th:nth-child(3):hover) tr>*:nth-child(3),
    table:has(th:nth-child(4):hover) tr>*:nth-child(4) {
      background-color: pink;
    }
    <table>
      <thead>
        <tr>
          <th>head1</th>
          <th>head2</th>
          <th>head3</th>
          <th>head4</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td>2</td>
          <td>3</td>
          <td>4</td>
        </tr>
        <tr>
          <td>1</td>
          <td>2</td>
          <td>3</td>
          <td>4</td>
        </tr>
        <tr>
          <td>1</td>
          <td>2</td>
          <td>3</td>
          <td>4</td>
        </tr>
        <tr>
          <td>1</td>
          <td>2</td>
          <td>3</td>
          <td>4</td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search