Question

Here is my jfiddle: http://jsfiddle.net/D3zyt/8/

html:

<div class="board">
 <table id="mastermind_table_one">
    <td></td>
    <td></td>
    <td></td>
    <td></td>
 </table>

 <table id="mastermind_table_two">
    <td></td>
    <td></td>
    <td></td>
    <td></td>
</table>

 <table id="mastermind_table_three">
    <td></td>
    <td></td>
    <td></td>
    <td></td>
 </table>

You'll notice in the html that I have three tables. Is there a way when I click "next_round", the background colors change for the next table and not the current (hardcoded) table?

Was it helpful?

Solution

This does it by storing the current table in a variable and using .next() to find the next table:

Fiddle

var current;

$('.next_round').click(function() {

   if(typeof current == 'undefined' || current.next('table').length == 0){
       current = $('.board table').first();   
   } else {
       current = current.next('table'); 
   }

   $(current).find('td').each(function() {
     $(this).css("background-color", setRandomColor);
   });

});

OTHER TIPS

Something like this helps?

var tables = $('.board table');
var currentTable = 0;

$('.next_round').click(function() {
    var table = tables[currentTable];

    table.find('td').each(function() {
        $(this).css("background-color", setRandomColor);
      });

    currentTable++;
    if(currentTable > tables.length){
       currentTable = 0;
    }
}

This is a solution that implements event data in jquery.

And here is a fiddle: http://jsfiddle.net/D3zyt/10/

var randomColor = ["red", "blue", "green", "#9CBA7F", "yellow", "#BF5FFF"];

function setRandomColor() {
    return randomColor[Math.floor(Math.random() * randomColor.length)];
}


$('.next_round').on("click", {i: 0}, function(e) {
    var selectorFragment = ["one","two","three"]

    $('#mastermind_table_'+selectorFragment[e.data.i]).each(function() {
      $(this).find('td').each(function() {
        $(this).css("background-color", setRandomColor);
      })
    })

    e.data.i += 1
    if (e.data.i === 3) e.data.i = 0 
})

However, restructuring your html would probably make for an easier solution later down the road ;)

Note: this post contains a bad practice, I left it maybe someone could learn from it, read the comment

just use one table like:

<table id="mastermind_table_three">
<td></td>
<td></td>
<td></td>
<td></td>
</table>

and then add a button <button onclick="nextRound(this) />

with the function as:

function nextRound(that) {
that.i = that.i ? (that.i + 1) : 1; 
$('table').removeClass("mastermind_table_" + that.i - 1);
$('table').addClass("mastermind_table_" + that.i);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top