Newbie Coder
Newbie Coder

Reputation: 10942

How to add table highlighting in PHP?

HI. I wanna know how to add table row highlighting everytime the user hovers the mouse. I was able to successfully alternate the row color. I am a total novice in web programming and have very little knowledge of javascript. Pls help me with this.

Here are the codes:

display.php:

<table class="table_data">
 <tr>
  <th><nobr>ID</nobr></th>
  <th><nobr>First Names</nobr></th>
  <th><nobr>Gender</nobr></th>
 </tr>

 <?php 
  $row_ctr = 1;

  while ($first_names_array = mysql_fetch_array($first_names)) {
   if (($row_ctr % 2) == 0) $alternate = "even";
   else $alternate = "odd";

   echo "<tr>";
   echo "<td class='$alternate'><nobr>"  .  $first_names_array['id'] . "</nobr></td>";
   echo "<td class='$alternate'><nobr>" . $first_names_array['first_name'] . "</nobr></td>";
   echo "<td class='$alternate'><nobr>" . $first_names_array['gender'] . "</nobr></td>";
   echo "</tr>";

   $row_ctr += 1;
  }
 ?>

 </tr>
</table>

and in my css:

style.css

.odd {
 background-color: #525252;
}

.even {
 background-color: #B7ACC6;
}

.highlight {
  background-color: #FF0;
}

I don't have the slightest idea how to do it but as I've said the row color alternation is working. Its just the highlight that I am having trouble with. I am a total novice like I said earlier. Pls help..

Upvotes: 1

Views: 1579

Answers (4)

Susheel
Susheel

Reputation: 1679

void excessive code for styling,do it with css

use following with td or tr or table:

onmouseover="style.backgroundColor='#colorcode'

onmouseout="style.backgroundColor='#colorcode'

 - and for alternating table also use css

tr:nth-child(even) {background: #colorcode}
tr:nth-child(odd) {background: #colorcode}

Upvotes: 0

Karl Laurentius Roos
Karl Laurentius Roos

Reputation: 4399

To add support for IE you can use jQuery:

$(document).ready(function(){
    $(".table tr").mouseenter(function(){
        $(this).addClass("hover");
    }).mouseleave(function(){
        $(this).removeClass("hover");
    };
});

Then you use something like this in your CSS:

.data_table tr.hover td
{background: #ccc;}

Upvotes: 1

KillerFish
KillerFish

Reputation: 5170

Use a class for you tr and following properties

 echo "<tr class='highlightrow'>";
   echo "<td class='$alternate'><nobr>"  .  $first_names_array['id'] . "</nobr></td>";
   echo "<td class='$alternate'><nobr>" . $first_names_array['first_name'] . "</nobr></td>";
   echo "<td class='$alternate'><nobr>" . $first_names_array['gender'] . "</nobr></td>";
   echo "</tr>";

and css for .highlightrow

.highlightrow:hover td
{
  background-color: Black;
  color: white;
  cursor: pointer;
}

Upvotes: 1

Andrei Stanca
Andrei Stanca

Reputation: 908

You don`t need php or javascript.

You can do it by css:

.table_data tr:hover{background-color:#000000;} /*highlight with black background*/

Upvotes: 3

Related Questions