"Using jQuery to add emphasis to a table row and remove it again

I have a table with multiple rows, where I have styled each odd row in one shade of gray and the even rows in slightly different shades to make it easier to read.

When clicking on a row, I am currently highlighting it with a different color to indicate which record has been selected. However, I'm not sure how to revert the color back to its original when selecting a different row.

Currently, I find myself having to set all the rows back to their alternate gray colors as a workaround, and then apply the new highlighted color to the selected row.

I was hoping to find a better way to achieve this effect without resorting to such workarounds.

$(document).on("click","#div2 tr#abc", function(event) {

    barcode = $(this).data('barcode');

    $('tr:odd[id="abc"]').css('backgroundColor', '#FAFAFA');
    $('tr:even[id="abc"]').css('backgroundColor', '#F2F2F2');

    $(this).css('backgroundColor','#FFD6F5');

});

Answer №1

My recommendation is to utilize CSS classes instead of relying on the css() function:

CSS

.highlight { background-color:yellow }

jQuery

When a row is clicked, first remove the highlight class from all rows and then add this class to the clicked row:

$('#yourTable tr').on('click', function() {
   $('#yourTable tr').removeClass('highlight');
   $(this).addClass('highlight');
});

Answer №2

Avoid inline styling and utilize classes instead.

Update your CSS file with the following:

.selected {
    background-color: #FFD6F5
}

Update your JavaScript code as follows:

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

Answer №3

Here is a simple solution for your problem:

By toggling CSS classes on rows, you can achieve the desired effect.

$(document).on("click","tr", function(event) {

  $('tr').removeClass('active');  
  $(this).addClass('active');

});
tr:nth-child(even) {background: #F2F2F2}
tr:nth-child(odd) {background: #FAFAFA}

td{ width:200px; height:20px;border:1px solid black;}

tr.active{background:#FFD6F5};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
  <tr>
    <td>
      </td>
    <td>
      </td>
    
    </tr>
    </table>

Answer №4

If you want to improve your code, consider working with classes instead of directly setting css attributes:

CSS (order matters; refer to Rory McCrossan's response for different baseline coloring):

.color-even { background-color: #F2F2F2; }
.color-odd  { background-color: #FAFAFA; }
.color-hilite { background-color: #FFD6F5; }

JavaScript:

$(document).ready( function() {
    //...
    $('tr:even').addClass('color-even');
    $('tr:odd').addClass('color-odd');
    //...
});

//...

$(document).on("click","#div2 tr", function(event) {
    barcode = $(this).data('barcode');

    $('.color-hilite').removeClass('color-hilite');
    $(this).addClass('color-hilite');
});

If you want to allow selection of multiple rows, make sure to move the 'removeClass' method to where you handle deselection.

jsFiddle (live demo)

NB (id attribute)

In your click handler selector, you used the id 'abc' with the tr element. This may not be logical unless you have multiple rows sharing the same id. It's better to use classes for this purpose and you can add multiple classes in a single class attribute. jQuery makes handling this easier even though it can get a little tricky without convenience code.

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

Internet Explorer 9 (IE9) causing CSS dropdown menu to be truncated due

My issue is very similar to the problem described in this post: CSS Flyout menu gets cut off by borders of its container in IE9 The difference in my case is that I need to set the z-index (and position) on the container. You can view my JSFiddle here: h ...

Creating a Jquery function to clone a select element with an inline onchange event and handle multiple ajax requests

I am dealing with a select dropdown that gets populated with numbers 14 through an ajax request. Each time a number is chosen from the dropdown, two signs are displayed as options. These signs are fetched using an onchange function attached to the select e ...

How can I dismiss a pop-up window for adding a new record in a jQuery jTable after it has been saved in an MVC application

I have integrated the jTable plugin from jQuery into my CRUD application. The issue I am facing is that when I click on Add New Record, a confirmation dialog pops up but after entering the details and clicking Save, the dialog does not close. However, the ...

Issue with TinyMCE Editor: Inoperative

<script type="text/javascript" src="<your installation path>/tinymce/tinymce.min.js"></script> <script type="text/javascript"> tinymce.init({ selector: "textarea", theme: "modern", plugins: [ "advlist autolink li ...

The issue with the material design checkbox change functionality not functioning as expected

Currently, I am attempting to dynamically set the state of checkboxes to either true or false. The following code snippet demonstrates what I have tried so far: for(var i = 0; i < bookmakers.length; i++) { $('#' + bookmakers[i].id + &apos ...

Disabling the search function when it is clicked (before any actions are taken)

I've recently implemented a search form on my website, where the search field opens up upon clicking the search icon.https://i.stack.imgur.com/UeErx.png To make the search icon clickable, I disabled the search function. var $searchBtn = $search.find ...

Incorporate the selectpicker feature into a dynamic input field

I am currently utilizing Laravel for my web development. In my controller, I pass a list of questions to the view and display them as follows: @foreach($questions as $q) <div class="col-xs-12"> <input type="{{ $q["type"] }}" class="fo ...

Tips for refreshing the appearance of a window in angular when it is resized

I have a chat feature integrated into my application. I am looking to dynamically resize an image within the chat window when the width of the window falls below a certain threshold. Is there a method available to modify the CSS style or class based on the ...

Determine if a specific date occurred at least one day ago using momentjs

Is there a way to determine if a specific date is at least one day (24 hours) in the past using momentjs? For example: const currentDate = moment() const isAtLeastOneDayAgo = currentDate.subtract(dateToVerify) > 1 // How can this be done? ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Yii: Error: The method 'typeahead' is not defined for the object [object Object]

I am currently working on a project using Yii and I encountered a small issue with the Typeahead widget from Yiistrap. It seems that jQuery is being included multiple times - twice before the inclusion of bootstrap.js and once after. Uncaught TypeError: O ...

The functionality of saving a file using the jsPDF method is not functioning properly

After dedicating four days to resolving a seemingly straightforward task that involved the jsPDF library, I found myself faced with a challenge. My goal was to save a file using this library, not just print it like I had successfully done before. This is ...

Add a CSS class to a dropdown menu option in HTML and JavaScript (JQuery) if it has a specified ID

I am brand new to HTML and JQuery, and I'm struggling with setting a class for my select element when the currently selected option has an ID of "answer". This is crucial for checking the correctness of a multiple choice question. If achieving this i ...

How to create a vibrant and colourful full background

How can I make the background color fill the entire width of the page? I am new to HTML and CSS, so below is the code I have used for setting the background. Please provide clear instructions on what changes I need to make in my code to achieve this. I kno ...

Sliding content with the grace of a visual journey

I'm currently working on a content slider that is very similar to this one. My goal is to make it rotate automatically, but I've been struggling to get it to work. I've attempted various methods, including triggering a click event on the lin ...

powerful enhancer separates the heading into a layout

I have an HTML div element that just isn't behaving right when I resize the screen. The title pretty much sums it up: <div class='serveMessage'><strong>Fun fact:</strong>&nbsp;over 1,259,468 American students fail ev ...

Adding classes to a randomly generated <li> element in a unique and one-time fashion

My task involves using jQuery to dynamically add <li> elements inside a <div>: countItems = 60; for (i = 1; i <= countItems; i++) { $('#head #lol').append("<li id='item_"+ i++ +"' clas ...

What is the best way to retrieve the JQuery property from within a regular JavaScript function?

I am facing an issue with a function that takes an array as input and manipulates its values. The problem lies in the fact that the array is composed of JQuery nodes (specifically spans), and I retrieve the span value by utilizing the .text() method in jQu ...

Don't forget to preserve the hover state of divs even after refreshing

I recently added a navigation bar that expands in width upon hovering over it. For an illustration, check out this example: http://jsfiddle.net/Gsj27/822/ However, I encountered an issue when clicking on a button within the hover effect area. After load ...

Locating the jQuery element just one element next to it

Having set up my HTML like this. <div id="wrap"> <div class="left"></div> <div class="right"> <a href="#">link</a> </div> <div class="listings" style="display:none"> <ul> ...