Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating the background color of an HTML table's cell (or the whole row) on an event

I have a table with a menu (food items) with several rows and columns. The 2nd column contains a link to the food item. When the user clicks it, the item is added to a shopping cart.

I'd like to give the user some visual feedback that the click and adding actually worked. I already have a click handler for the link that adds the item clicked on to the cart. A simple alert('Item successfully added'); works but is not really pretty.

I'd like the table cell (or the whole row) to "flash" once. By "flashing" I mean "change its background color smoothly from current (light gray) to e.g. yellow and then back to normal". This should happen only once.

I'm using jQuery 2.x and Bootstrap 3.x.

My (simplified) code so far looks like this:

  $('a[href="#"]').on('click', function(event) {
    // code to add the item to shopping cart (AJAX), omitted here
    // Upon successful return of the AJAX data:
    $(this).closest('tr').css('background-color', 'yellow');
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td><a href="#">Hamburger</a>
    </td>
    <td>2.65</td>
  </tr>
  <tr>
    <td>2</td>
    <td><a href="#">Cheeseburger</a>
    </td>
    <td>3.25</td>
  </tr>
</table>

How do I make the row flash instead of simply changing its background color?

like image 701
PerlDuck Avatar asked Feb 01 '16 21:02

PerlDuck


1 Answers

It's often best to use CSS classes rather than directly manipulating styles:

$('a[href="#"]').on('click', function(event) {
    // code to add the item to shopping cart (AJAX), omitted here
    // Upon successful return of the AJAX data:
    var myRow = $(this).closest('tr');

    myRow.addClass('stylish');

    setTimeout(function() {
        myRow.removeClass('stylish');
    }, 1000);
});
tr {
    background-color: white;
    transition: background-color 1s;
}

.stylish {
    background-color: orange;
    transition: background-color 1s;
}
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>

<table>
    <tr>
        <td>1</td>
        <td><a href="#">Hamburger</a>
        </td>
        <td>2.65</td>
    </tr>
    <tr>
        <td>2</td>
        <td><a href="#">Cheeseburger</a>
        </td>
        <td>3.25</td>
    </tr>
</table>

Fiddle demo

like image 96
isherwood Avatar answered Nov 10 '22 00:11

isherwood