jQuery: How to use setTimeout for temporary change of background color

2.1k views Asked by At

I am new to jQuery and hope someone can help me with this.

I am trying to temporarily change the background color of a table row, then switch back to its original color and do something else, e.g. in the below example remove the row.

With my code it removes the correct row but I don't see the highlighting of this row before that.

How do I tell it to wait x milliseconds before the next step and (for other examples) how do I set it to reverse back to the original color after that (usually I would use .css('background-color', '') for that).

My jQuery:

if($(this).closest('table').find('tbody > tr').length > 1) {
    setTimeout(function(){
        $(this).closest('tr').css('background-color', 'red');
    }, 1200);
    $(this).closest('tr').remove();

Many thanks in advance, Mike

1

There are 1 answers

2
Ted Nyberg On BEST ANSWER

Try this:

   if($(this).closest('table').find('tbody > tr').length > 1) {

       // Change background
       $(this).closest('tr').css('background-color', 'red');

       var that = this;

       // Wait 1.2 seconds, then remove the row
       setTimeout(function(){           
          $(that).closest('tr').remove();
       }, 1200);
    }