How can I modify the style of table rows with CSS?

Is there a way to change the color/background of a selected row just like it does on hover, and also have the option to deselect the row?

To see how it looks on hovering, check out: http://jsfiddle.net/q7ApN/

If you want to make a Change:

#gradient-style tbody tr:hover td {
    background: #d0dafd url('table-images/gradhover.png') repeat-x;
    color: #339;
}

The Change Would Be:

#gradient-style tbody tr:hover, tr.selected td {
    background: #d0dafd url('table-images/gradhover.png') repeat-x;
    color: #339;
}

Actual HTML Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
... [remaining code omitted for brevity] ...

Any suggestions or solutions for this issue?

Answer №1

Here is a solution that should meet your needs. When you click on a row, the selected class will toggle on the tr element. If you then click on another row, the selected class will be removed from the previously selected row.

$(document).ready( function() {
    $("tr").click(function(){
        $(this).toggleClass('selected').siblings().removeClass('selected'); 
    });
});

To update the styles accordingly, as mentioned by others before, you can use the following CSS:

#gradient-style tbody tr:hover td,
#gradient-style tbody tr.selected td {
    background: #d0dafd url('table-images/gradhover.png') repeat-x;
    color: #339;
}

You can view a live example of this code in action here: http://jsfiddle.net/davidpauljunior/q7ApN/8/

Answer №2

Give this code a try, it should do the trick

Make the following changes in your CSS

#gradient-style tbody tr.selected td {
        background: #d0dafd url('table-images/gradhover.png') repeat-x;
        color: #339;
    }

Script to Add

$("#gradient-style tr").click(function(){
    $(this).toggleClass('selected').siblings().removeClass('selected'); 
});

Check out the Fiddle

Answer №3

http://example.com/jsfiddle

Everything seems to be functioning properly.

$("tr").on('click', function(){
    $('.selected').removeClass('selected');
    $(this).addClass("selected");
});

The addition of !important is necessary for the following:

.selected td {
        background: #d0dafd url('table-images/gradhover.png') repeat-x !important;
        color: #339;
}

Answer №4

Make sure to review the link provided http://jsfiddle.net/q7ApN/3/

$("tr").click(function(){
    $('.selected').removeClass('selected');
    $(this).addClass("selected");

});

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

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

Flask Modal fails to function properly in the absence of table data

I'm currently troubleshooting an issue with my modal on a Flask web app that utilizes a SQLite database. When trying to add new rows to the table using some JavaScript code, everything works perfectly unless the table is empty. In that case, I am unab ...

Update links within a designated div section

How can I change the color and alignment of anchor tags within the third child div that is part of a set of three nested divs? These child divs are arranged side by side within a parent div with the class .logo-bckgrnd-rpt. Although I have successfully tar ...

The method to permit a single special character to appear multiple times in a regular expression

I am currently working on developing a REGEX pattern that specifically allows alphanumeric characters along with one special character that can be repeated multiple times. The permitted special characters include ()-_,.$. For instance: abc_def is conside ...

Retrieve various URLs within an object using React

My task involves extracting all URLs from a specific object. Object { "Info": "/api/2", "Logo": "/api/2/Logo", "Photo": "/api/2/photo", } I aim to store the responses in a state, ensuring t ...

Adjusting the height of the Owl Carousel div to enhance image hover effects

Seeking help with implementing a hover effect on an img within an Owl Carousel div. I have applied a simple CSS transition to the Owl Carousel container div, but the Carousel is automatically setting a standard height. Images included for reference. I have ...

Server side Meteor with reactive coffee on client

Is it possible to run 'client' Meteorite packages on the server? I want to implement reactive coffee for generating a newsletter on the server. I haven't been able to find any information on this, even though it seems like a logical choice. ...

Ensure that the footer remains at the bottom of the page without being fixed to the bottom

I am currently working on configuring the footer placement on pages of my website that contain the main body content class ".interior-health-main". My goal is to have a sticky footer positioned at the very bottom of these pages in order to eliminate any wh ...

Issue: Module 'connect' is not found?

Hey there! I'm fairly new to the world of servers, and I've been learning by watching YouTube tutorials. Following one such tutorial, I installed 'connect' using npm in my project folder. Here's the structure of my project: serv ...

The ngFor directive is not compatible with third-party library elements

I am currently working on an Angular application that utilizes a UMD library for the user interface. However, I have encountered a problem where I am unable to use the ngFor directive on an element from the library. Here is an example: <lib-select> & ...

Keep updating every second using setInterval

Currently, I have a function that refreshes a page every second and logs a message using console.log: function autoRefresh() { $.ajax({ type: "POST", url: "refresh.php", //data: dataString, dataType: "json", suc ...

Identify when two calendar dates have been modified

Creating a financial report requires the user to select two dates, search_date1 and search_date2, in order for a monthly report to be generated. Initially, I developed a daily report with only one calendar, where I successfully implemented an AJAX script ...

Replace automatically generated CSS with custom styles

When using a Jquery wysiwyg editor, I have encountered an issue where it automatically adds code to the textarea at runtime. The problem arises from it inserting an inline style of style="width:320px" when I need it to be 100% width due to styles already ...

Four unique chip/tag colors, personalized to suit your style

Currently, I have integrated two arrays into my autocomplete menu where the chip/tag color is either primary or secondary based on the array the selected component belongs to. I aim to include all four arrays in the menu (top10Songs, top10Artists, top10Fi ...

Accessing Ionic rootScope within the config stateprovider - A step-by-step guide

Is it possible to access the value of $rootScope in the following line? .config(function($stateProvider, $urlRouterProvider) { $stateProvider // I am trying to retrieve the value of $rootScope here. } ...

Delaying Default Event Behavior in Jquery

I have a function to manage the submit event for a form. My goal within the handler is to delay the default behavior until an Ajax function has completed its execution. Here's an example of the code: $("#some_form").on("submit", function(event){ ...

issues with redirection of form validation

I am currently working on a Django project where users can add comments to posts. The information is saved directly in the database, which is functioning properly. However, I am facing an issue where after submitting the comment, the form keeps resubmittin ...

Synchronizing code paths that involve both ajax and non-ajax functions can be achieved by

My website features a basket functionality where users can enter an author's name and see the available books. After selecting desired books, they have the option to click on another author for more selection. The displayed list includes books by Step ...

Effortless File Uploading in JERSEY using jquery and AJAX

I'm looking to achieve file uploads with Jersey through jQuery/AJAX, but I'm struggling with extracting the file from the input and sending it via AJAX. Below is my current code: HTML <form action="rest/files/upload" method="post" enctype=" ...

Guide to integrating external plugins in an Angular application

Currently in the process of converting my project from jQuery to Angular. Wondering the best approach for utilizing plugins: 1. Is it advisable to swap out old jQuery plugins with Angular-specific ones? 2. Or would it be better to integrate them using co ...