Site icon codippa

How to highlight a table row on click using jQuery

Any element is highlighted due to its background-color property. By default this property has NO value, hence the element is not highlighted when it is at first added to the page.
If we change the value of this property, we are easily able to highlight the element. For highlighting an element (such as a table row) on click, there are a couple of approaches using jQuery:

I. Change the ‘background-color’ property of the row in the click event handler of the row. Code would be:

//attach an onclick event handler to the table rows 
$(“#myTable tbody tr”).click(function(){
	//change the ‘background-color’ property to the desired color.
	$(this).css(‘background-color’,’ yellow’);
});


Let’s tweak in:

1. The code alongwith its comments is self-explanatory.
2. Hex code of the color may also be used instead of color name.

II. Add a css class to the application css file which will have the ‘background-property’ property alongwith its value. In the onclick event handler of table row add this class to the clicked table row. Code would be:

//attach an onclick event handler to the table rows 
$(“#myTable tbody tr”).click(function(){
	//add the css class which has the required background color property to the clicked table row
	$(this).addClass(‘rowColor’);
});

The css class would have an entry like this:

.rowColor{
	background-color:yellow;
}

Let’s tweak in:

1. Code is self-explanatory.
2. Again, in place of color string value, a hex code of the desired color may also be used.

Exit mobile version