CSS: customize the color of a highlighted row within a table

I am struggling to implement a new feature in my table. Specifically, I want the row to change color (#FFCF8B) when a user selects it. I attempted using #newspaper-b tbody tr.selected td, but it was not successful.

   #newspaper-b {
        border-collapse: collapse;
        border-color: #B7DDF2;
        border-style: solid;
        border-width: 1px;
        font-family: Arial,Helvetica,sans-serif;
        font-size: 11px;
        margin: 0;
        text-align: left;
        width: 480px;
    }
    #newspaper-b th {
        background: none repeat scroll 0 0 #EBF4FB;
        border-color: lightgray;
        font-size: 11px;
        font-weight: bold;
        padding: 15px 10px 10px;
    }
    #newspaper-b tbody tr td {
        background: none repeat scroll 0 0 #FFFFFF;
    }
    #newspaper-b td {
        border-top: 1px dashed #FFFFFF;
        color: #000000;
        padding: 10px;
    }
    #newspaper-b tbody tr:hover td {
        background: none repeat scroll 0 0 #FFCF8B;
        color: #000000;
    }
    #newspaper-b tbody tr.selected td {
        background: none repeat scroll 0 0 #FFCF8B;
        color: #000000;
    }

Answer №1

If you want to apply a .selected class to the row you click on, you'll need to use some JavaScript.

Take a look at this example http://jsfiddle.net/thebabydino/KzVfy/

I demonstrated using jQuery in this example, so the code is quite simple:

$("tr").click(function(){
    $(this).addClass("selected").siblings().removeClass("selected");
});​

However, if you prefer not to use a library like jQuery, it can also be achieved.


As an alternative, I created another version that doesn't rely on any libraries (no jQuery, no Mootools, no YUI, no Dojo, etc.) and allows for selecting multiple rows. You can view it here: http://jsfiddle.net/thebabydino/nY5jj/. There's also a variation that deselects a row when clicked again: http://jsfiddle.net/thebabydino/nY5jj/1/

The JavaScript code for this version is as follows:

var trs = document.querySelectorAll("tr");
for(var i = 0; i < trs.length; i++){
    trs[i].addEventListener("click", function(){this.className += " selected";});
}​

To deselect a row when clicked on a second time:

var trs = document.querySelectorAll("tr");
for(var i = 0; i < trs.length; i++){
    trs[i].addEventListener("click", function(){
        var cn = this.className, thc = " selected", start_idx = cn.indexOf(thc);
        if(start_idx == -1) cn += thc;
        else cn = cn.replace(thc,"");
        this.className = cn;
    });
}​

Answer №2

Using CSS alone may not achieve this effect, but you can utilize jQuery. Here is a quick example (though there are other methods to accomplish the same):

 <table class="tab" cellpading="0" cellspacing="0" border="1">
    <tr>
      <td>lol</td>
      <td>lol</td>
    </tr>
    <tr>
      <td>lol</td>
      <td>lol</td>
    </tr>
    <tr>
      <td>lol</td>
      <td>lol</td>
    </tr>
   </table>

Add the following to your CSS file:

tr.clicked {
      background-color: #abc;
}

Include this jQuery script:

$('.tab tr').click(function() {
      $(this).toggleClass("clicked");
    });

By clicking on a row in your table, jQuery will apply a background-color to that row. Click again to remove the class. Hope this explanation helps.

Answer №3

Check out this demonstration using dojo - incorporating familiar concepts discussed by many others.

http://jsfiddle.net/cswing/SG9dp/

Important to note: In this example, I enabled the selection of multiple rows even though it was not specified in the original question.

Answer №4

<!DOCTYPE html>
<html>
<head>
<style>
table, th {
    border: 1px dotted black;
    border-collapse: separate;
    padding: 7px;
    margin: 3px;
}
</style>
</head>
<body onload="initializeTable()">

<table id="myTable" onkeydown="handleKeyPress()">
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
    <th>Header 3</th>
    <th>Header 4</th>
    <th>Header 5</th>
  </tr>
  <tr>
    <td>data 1</td>
    <td>data 2</td>
    <td>data 3</td>
    <td>data 4</td>
    <td>data 5</td>
  </tr>
  <tr>
    <td>data 6</td>
    <td>data 7</td>
    <td>data 8</td>
    <td>data 9</td>
    <td>data 10</td>
  </tr>
  <tr>
    <td>data 11</td>
    <td>data 12</td>
    <td>data 13</td>
    <td>data 14</td>
    <td>data 15</td>
  </tr>
  <tr>
    <td>data 16</td>
    <td>data 17</td>
    <td>data 18</td>
    <td>data 19</td>
    <td>data 20</td>
  </tr>
</table>

<script>

var currentRow = 0;
var currentCell = 0;
var selectedCellStyle = "3px solid #ff0000";
var defaultCellStyle = "1px solid #000000";

function initializeTable() {
     var table = document.getElementById("myTable");
  table.rows[currentRow].cells.item(currentCell).style.border = selectedCellStyle;

}

document.addEventListener('keydown', handleKeyPress);
function handleKeyPress(event){
  console.log(event.keyCode);
  var table = document.getElementById("myTable");
  var previousRow = table.rows[currentRow];
  var nextRow = null;
  var nextCell = null;
  
  if(event.keyCode == 40){
    if(previousRow){
      previousRow.cells.item(currentCell).style.border = defaultCellStyle;
    }
    currentRow++;
    nextRow = table.rows[currentRow];
    
    if(nextRow){
        nextRow.cells.item(currentCell).style.border = selectedCellStyle;
    }else{
      currentRow = 0;
      nextRow = table.rows[currentRow];
      nextRow.cells.item(currentCell).style.border = selectedCellStyle;
    }
  } else if(event.keyCode == 38){
    previousRow.cells.item(currentCell).style.border = defaultCellStyle;
    currentRow--;
    
    if(currentRow < 0){
      currentRow = table.rows.length - 1;
    }
    
    table.rows[currentRow].cells.item(currentCell).style.border = selectedCellStyle;
  } else if(event.keyCode == 39){
    previousRow.cells.item(currentCell).style.border = defaultCellStyle;
    currentCell++;
    nextCell = previousRow.cells.item(currentCell);
    
    if(nextCell){
      previousRow.cells.item(currentCell).style.border = selectedCellStyle;
    }else{
      currentCell = 0;
      previousRow.cells.item(currentCell).style.border = selectedCellStyle;
    }
  } else if(event.keyCode == 37){
    previousRow.cells.item(currentCell).style.border = defaultCellStyle;
    currentCell--;
    
    if(currentCell < 0){
      currentCell = previousRow.cells.length - 1;
    }
    
    previousRow.cells.item(currentCell).style.border = selectedCellStyle;
  }

}
</script>

</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I use HTML code to style the header cell values of a table?

Can someone please assist me with creating a table header style that looks like the one in the image? Additionally, how can I turn the name and picture area into a block and add borders to them? I'm also having trouble with my list icons showing up a ...

Adjust the initial slider according to the values displayed in the following four sliders

Having an issue updating the slider value in the first one based on selected values from four other sliders. The selected value should not exceed 50, which is the maximum value in the first slider. Link to Working Fiddle : Below is the HTML code : & ...

Is there a term similar to "Rise above the Rest" in the world of Web Development?

Hey, I've encountered a new issue right now. Currently, I have two elements that are fixed to the top and bottom of the page. However, the elements in between them are overlapping the top element. Even though I tried keeping both elements fixed, th ...

Image link in HTML / CSS not functional on one half of the image

My webpage has an image thumbnail with accompanying text positioned to the right. I have a hyperlink on the image that should open the full-size version when clicked. However, there seems to be an issue where the hyper link only activates on the lower hal ...

Incorporate a fresh button into the Tinymce toolbar using C# programming

I have utilized Tinymce text editor/textarea in my webpage. How can I incorporate an additional button onto the toolbar? For instance, upon clicking the added button, it should prompt a dialog with three textfields: title, age, and gender. Upon filling ou ...

div that adjusts its max-width to always perfectly match the width of its contents

Check out this jsfiddle for more information: http://jsfiddle.net/tN6QE/2/ The CSS code we are using is as follows: div { display: inline-block; border: solid 1px black; padding: 10px; max-width: 200px; } We are dealing with two scenarios here. ...

Problem with datepicker interface not aligning properly with Bootstrap grid

I am encountering a challenge with aligning the input controls in my UI design. Specifically, I am trying to create rectangular borders/containers around each set of input controls and looking for a way to achieve this using Booststrap. For reference, y ...

Ways to move the cursor to the search field after the placeholder text

I'm working on a Vue project with a small app featuring an input type search. The issue I'm facing is that the cursor appears at the beginning of the input, whereas I want it to appear after the placeholder text. How can I make this adjustment? ...

Mobile responsiveness issues with Bootstrap 4 row

<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS ...

What is the best way to stack a canvas box on top of another canvas box?

My goal is to have two canvas squares stacked on top of each other. While I am familiar with drawing on canvas, I need assistance in placing one canvas on top of another. Despite my attempts at setting the position, I have not been successful. <canvas ...

I want to use flexbox to center three divs on my webpage

I am trying to align 3 divs inside a flex container in the center of the page with equal distance between them and also from the edge of the page. .container { display : flex; width : 60%; } .para { width : 33%; padding : 1em; borde ...

The issue with rendering CSS styles from <style></style> tags in Visual Studio while debugging in VB is causing a problem

<style> #ctrtable{width:600px;margin-left:auto;margin-right:auto;} </style> For the purpose of centering a table on the viewport, the above style block is added to the web page.   While using Visual Studio 2013 Express in debug mode, t ...

Transform Arabic numerals into Roman numerals using only CSS styling

Currently developing a custom theme for a website and faced with the restriction of not being able to use Javascript. My goal is to translate certain numbers into Roman numerals. I attempted the following: .score:before { counter-reset: mycounter att ...

Design your own custom up and down arrow icons or buttons using CSS styling techniques

Is there a way to create "up and down" control buttons using only CSS and no background image? I attempted to add CSS for arrows in "li.className:after or li.className:before", but it caused the main boxes to move. Check out the Fiddle link to see the is ...

Unable to reduce the height of the li element

Even though I've attempted to adjust the height of the lis in this section using CSS, I can't seem to shorten them as desired: I've experimented with setting a line-height, adjusting the height, ensuring that paddings and margins are set to ...

Troubles encountered when wrapping columns in bootstrap framework

I'm experimenting with a design that utilizes Bootstrap's grid system, but I'm experiencing some challenges with the content either wrapping or extending off-screen. What I want is to have a sidebar with fixed width (around 250px), and its a ...

To prevent flickering when using child flex elements, it's best to use position fixed along with a dynamically updated scrollbar position using Javascript

My navigation component includes a slim banner that should hide upon scroll and a main-nav bar that should stick to the top of the screen and shrink when it does so. I initially looked into using Intersection Observer based on a popular answer found here: ...

Modifying the colors of my navigation links is not within my control

How can I modify my CSS to change the color of the navigation links to white? Below is the code snippet: <div class="col-sm-12"> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header" ...

Text Alignment Issue in Icon Bar of Zurb Foundation 5

There's an unusual problem I'm encountering with the alignment of text under the icon bar not being properly centered below the icons. Here is a snippet of the code: <div class="row"> <div class="small-12 columns"> < ...

Gap created between two td or tr elements

Can someone please help me solve a troubling issue I'm facing with my CSS and HTML code? body { background-color:#ffffff; margin:0; padding-top:0px; } table.main-table-default { margin:0 auto; background-color:#00ffff; width:700px; border-collapse:co ...