jQuery Style How to - Toggle 2 background color per second








Question

We would like to know how to toggle 2 background color per second.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.7.1.js'></script>
<style type='text/css'>
td.bgimage {<!--   w  w w . ja  v a2  s  .  c om-->
  padding: 10px;
  background: #333;
}

td.bgimage.toggled {
  background: #f00;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    function colorChange(){
        setTimeout(function(){
            $('td.bgimage').toggleClass('toggled');
            colorChange();
        }, 1000);
    }
    colorChange();
});
</script>
</head>
<body>
  <table>
    <tr>
      <td class="bgimage">&nbsp;</td>
    </tr>
  </table>
</body>
</html>

The code above is rendered as follows: