I am attempting to create a table that will only display one row at a time and also randomize on each refresh. Here is my code:
<script>
var maxRows = 1; //displays one row at a time
$('#song-list').each(function() {
var cTable = $(this);
var cRows = cTable.find('tr:gt(0)');
var cRowCount = cRows.size();
if (cRowCount < maxRows) {
return;
}
/* hide all rows above the max initially */
cRows.filter(':gt(' + (maxRows - 1) + ')').hide();
var cPrev = cTable.siblings('.prev');
var cNext = cTable.siblings('.next');
/* start with previous disabled */
cPrev.addClass('disabled');
cPrev.click(function() {
var cFirstVisible = cRows.index(cRows.filter(':visible'));
if (cPrev.hasClass('disabled')) {
return false;
}
cRows.hide();
if (cFirstVisible - maxRows - 1 > 0) {
cRows.filter(':lt(' + cFirstVisible + '):gt(' + (cFirstVisible - maxRows - 1) + ')').show();
} else {
cRows.filter(':lt(' + cFirstVisible + ')').show();
}
if (cFirstVisible - maxRows <= 0) {
cPrev.addClass('disabled');
}
cNext.removeClass('disabled');
return false;
});
cNext.click(function() {
var cFirstVisible = cRows.index(cRows.filter(':visible'));
if (cNext.hasClass('disabled')) {
return false;
}
cRows.hide();
cRows.filter(':lt(' + (cFirstVisible +2 * maxRows) + '):gt(' + (cFirstVisible + maxRows - 1) + ')').show();
if (cFirstVisible + 2 * maxRows >= cRows.size()) {
cNext.addClass('disabled');
}
cPrev.removeClass('disabled');
return false;
});
});
</script>
Second piece of code:
<script>
Array.prototype.shuffle = function() {
for (var i = 0; i < this.length; i++) {
// Random item in this array.
var r = parseInt(Math.random() * this.length);
var obj = this[r];
// Swap.
this[r] = this[i];
this[i] = obj;
}
}
function randomize(tableID) {
var myTable = document.getElementById(tableID);
var myRows = new Array();
for (i=myTable.rows.length-1; i>=0; i--) {
var theRow = myTable.rows[i];
myRows.push(theRow);
theRow.parentNode.removeChild(theRow);
}
myRows.shuffle();
for (j=0; j<myRows.length; j++) {
myTable.appendChild(myRows[j]);
}
}
window.onload = function() {
randomize("song-list");
}
//-->
</script>
Both pieces work fine on their own but when I try to combine them the randomize function supersedes the other code and I get a long list of tr that randomize after refresh.
I know there is something I can do to make these codes agree with one another.
Have any suggestions?
put the whole 1st block of code into a function:
and call it after randomize: