Reputation: 297
I have created a table having rows with alternating colours(say yellow and red). Now, I want to change the colour of the clicked row to one common colour(say blue).And revert back to its original colour when clicked again. I'm able to change the colour using this code
$("#mainTable").find('#'+IDClicked).css("background-color", "#bbbbff");
I'm not able to figure out how to revert back.
Upvotes: 4
Views: 39791
Reputation: 7295
Answering exactly to your question:
$('#box').on('click', function() {
var box$ = $(this),
isBgColorChanged = box$.data('isBgColorChanged'),
bgColor = !!isBgColorChanged ? '#444' : '#ccc';
box$.css('background-color', bgColor)
.data('isBgColorChanged', !isBgColorChanged);
});
More elegant solution:
$('#box').on('click', function() {
$(this).toggleClass('activated');
});
Upvotes: 3
Reputation: 167172
We assume that your code this this way:
<table id="rowClick">
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
$(document).ready(function(){
$("#rowClick > tr").click(function(){
$(this).toggleClass("active");
});
});
table tr.active {background: #ccc;}
Upvotes: 10
Reputation: 8476
Try this demo:
$('table tr').toggle(function(){
$(this).addClass('myclass');
}, function(){
$(this).removeClass('myclass');
});
css
.myclass{
background: red;
}
table tr{
background: yellow;
}
Upvotes: 2
Reputation: 22619
Try this below code
CSS
.high-light{background:blue !important;}
jQuery
$(document).ready(function(){
$('table tr').click(function(){ $(this).addClass("high-light"); });
//If you have TD's background set try the below commented code
$('table tr td').click(function(){ $(this).parent().find('td').addClass("high-light"); });
});
Upvotes: 3