Prathiba
Prathiba

Reputation: 297

Change colour of table row onclick

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

Answers (4)

Eugene Naydenov
Eugene Naydenov

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);
});​

Fiddle

More elegant solution:

$('#box').on('click', function() {
    $(this).toggleClass('activated');
});​

Fiddle

Upvotes: 3

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

We assume that your code this this way:

HTML

<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>

In that case, you can use jQuery this way:

$(document).ready(function(){
    $("#rowClick > tr").click(function(){
        $(this).toggleClass("active");
    });
});

And finally the CSS part:

table tr.active {background: #ccc;}

Fiddle: http://jsbin.com/icusec/2

Upvotes: 10

Pragnesh Chauhan
Pragnesh Chauhan

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

Murali Murugesan
Murali Murugesan

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

Related Questions