This is a working example of how I would it: http://jsbin.com/ogika
CSS:
.month.hide { display: none; }
HTML
<p><a href="#" class="month-next">Next Month</a></p>
<table class="month"><tr><td>a</td></tr></table>
<table class="month hide"><tr><td>b</td></tr></table>
<table class="month hide"><tr><td>c</td></tr></table>
<table class="month hide"><tr><td>d</td></tr></table>
JavaScript:
$(function () {
$(".month-next").click(function () {
var months = $(".month"), numMonths = months.length, curr = 0;
return function () {
//Hide the current table, by adding the 'hide' class
months.eq(curr).addClass("hide");
//Get the index of next table in the list
curr = (curr + 1) % numMonths;
//Show the next table, by removing the 'hide' class
months.eq(curr).removeClass("hide");
}
}());
});
In the above code, months
is the list of tables...which in this case, holds 4 elements; and numMonths
is the number of elements...ie, 4.
The 'magic' of the above code is this line: curr = (curr + 1) % numMonths;
That line gets the index of the next element to be displayed, and it works in a circular fashion.
Let's take an example:
0 1 2 3
=========================
| a | b | c | d |
=========================
Now, let's say curr
is 0:
0 1 2 3
=========================
| a | b | c | d |
=========================
^
//curr is currently 0
curr = (curr + 1) % numMonths; //(0 + 1) % 4
//now, curr is 1
0 1 2 3
=========================
| a | b | c | d |
=========================
^
After that line of code is executed, curr
becomes 1: (0 + 1) % 4 = 1. This means that the next index of the element to be displayed is 1. Therefore, we get the next element and show it, by removing the hide
class: months.eq(curr).removeClass("hide");
Now let's look at the example where curr
is the last element: 3
0 1 2 3
=========================
| a | b | c | d |
=========================
^
//curr is currently 3
curr = (curr + 1) % numMonths; //(3 + 1) % 4
//now, curr is 0
0 1 2 3
=========================
| a | b | c | d |
=========================
^
As you can see, curr
is now 0...and thus the cycle continues.