Animating the background color of an HTML table cell (or the entire row) in an event

I have a table with a menu (batteries) with several rows and columns. The second column contains a link to a food product. When the user clicks on it, the item is added to the cart.

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

I would like the cell of the table (or the entire row) to start instantly. "Flashing" I mean "smoothly change the background color from the current (light gray) to for example yellow, and then back to normal." This should happen only once.

I am using jQuery 2.x and Bootstrap 3.x.

My (simplified) code 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>
Run codeHide result

How to make flash string instead of just changing background color?

+4
source share
1 answer

It is often better 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>
Run codeHide result

Screenshot

+7
source

Source: https://habr.com/ru/post/1626924/


All Articles