I want to continuously cycle through the rows of a table, highlighting a row, then pausing and moving to the next row. When I reach the end I want to go back around and start at the beginning again.
I liked roXon’s answer the best because it felt more concise and functional, so I expanded it to work with three tables. But now there’s code duplication — what is the most elegant way to write the code without duplication, that allows for different tables and colors? Here’s the working three-table solution (also, is the inner function strictly necessary?):
<!doctype html>
<html>
<head>
<style>
.highlight1 { background:gold; }
.highlight2 { background:lightblue; }
.highlight3 { background:lightgreen; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$(function() {
var $TR1=$('#table1 tr:gt(0)'), TRn1=$TR1.length, c1=0;
var $TR2=$('#table2 tr:gt(0)'), TRn2=$TR2.length, c2=0;
var $TR3=$('#table3 tr:gt(0)'), TRn3=$TR3.length, c3=0;
function loop(){
$TR1.eq(c1++%TRn1).addClass('highlight1').siblings().removeClass('highlight1');
$TR2.eq(c2++%TRn2).addClass('highlight2').siblings().removeClass('highlight2');
$TR3.eq(c3++%TRn3).addClass('highlight3').siblings().removeClass('highlight3');
}
setInterval(loop, 1000);
});
});
</script>
</head>
<body>
<table id="table1" border="1">
<th>Table One</th>
<tr><td>Table Row 1</td></tr>
<tr><td>Table Row 2</td></tr>
<tr><td>Table Row 3</td></tr>
<tr><td>Table Row 4</td></tr>
<tr><td>Table Row 5</td></tr>
<tr><td>Table Row 6</td></tr>
</table>
<table id="table2" border="1">
<th>Table Two</th>
<tr><td>Table Row 1</td></tr>
<tr><td>Table Row 2</td></tr>
<tr><td>Table Row 3</td></tr>
<tr><td>Table Row 4</td></tr>
<tr><td>Table Row 5</td></tr>
<tr><td>Table Row 6</td></tr>
</table>
<table id="table3" border="1">
<th>Table Three</th>
<tr><td>Table Row 1</td></tr>
<tr><td>Table Row 2</td></tr>
<tr><td>Table Row 3</td></tr>
<tr><td>Table Row 4</td></tr>
<tr><td>Table Row 5</td></tr>
<tr><td>Table Row 6</td></tr>
</table>
</body>
</html>
Create a CSS class
.highlightBe more specific while using selectors. I added a table ID
LIVE DEMO
c++%TRnwill increment our counter on each loop iteration, but thanks to theModulooperator – once the counter and the number of TR elements matches – our counter will be reset to0(e.g.4%4=0)