Ironcar Driftman
Ironcar Driftman

Reputation: 101

how to set color in table rows randomly with on click button?

this is my code: link I have table with 9 row. on click button, one must change color randomly. if I click button once more, it must continue change color randomly

I don't want random color. I want next thing:

first click: random row must be colorized red

second click: random row must be colorized red

and so on...

Upvotes: 0

Views: 1656

Answers (3)

Azad
Azad

Reputation: 5264

here is the code it changes first table cell color randomly.

$("button").on("click", function() {
  // math random function

  //rand id
  var id = Math.floor((Math.random() * 10));
    
  $("#" + id).css("background-color", getRandomColor);
});


function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>CLICK</button>
<br>
<br>
<table border="1" style="width:15%">
  <tr>
    <td id="1">1</td>
    <td id="2">2</td>
    <td id="3">3</td>
  </tr>
  <tr>
    <td id="4">4</td>
    <td id="5">5</td>
    <td id="6">6</td>
  </tr>
  <tr>
    <td id="7">7</td>
    <td id="8">8</td>
    <td id="9">9</td>
  </tr>
</table>

Upvotes: 2

user4554100
user4554100

Reputation:

Try this:

$('#btn').on( "click", function() {

var colors = [ 'red', 'green', 'yellow', 'blue' ];

var random  = Math.floor((Math.random() * 9) + 1);
var color   = Math.floor((Math.random() * colors.length - 1) + 1);

$($('.col')[random]).css('background-color',colors[color]);

} );

You have to give your columns a class too.

Full code here: https://jsfiddle.net/qsLeejo4/5/

Upvotes: 3

Vitalii Petrychuk
Vitalii Petrychuk

Reputation: 14225

All you have to do is just iterate through tds and change their css rules. To generate a random color you can use this snippet:

'#' + (~~(Math.random() * (1<<24))).toString(16)

Upvotes: 3

Related Questions