Click here to Skip to main content
15,920,602 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need some help in solving this task. I have a table 2 rows &2 columns. I need to color each and every cell in a table (4 colors) with button click. Change the colors in 4cells dynamically.

Example:
Suppose if i have 4 cells in a table i want to color each cell frequently change with a different color . like a serial bulbs.

Can you guys please help. Thanks in advance
Posted

1 solution

Hi,
Below is the code I have made for you.

HTML code.
HTML
<div>
        <table width="10%" border="1" cellspacing="0">
            <tr>
                <td id="cell1">1</td>
                <td id="cell2">2</td>
            </tr>
            <tr>
                <td id="cell3">3</td>
                <td id="cell4">4</td>
            </tr>
        </table>
        <br />
        <br />
        <input type="button" value="Change Colour" id="btn" onclick="return ChangeColour();" />
    </div>


Javascript Code
JavaScript
<script type="text/javascript">
        function ChangeColour() {
            var arr = [["000000", "000033"],["000066", "000099"],["0000CC", "0000FF"],["003300", "003333"],["003366", "003399"],
["0033CC", "0033FF"],["006600", "006633"],["006666", "006699"],["0066CC", "0066FF"],["009900", "009933"],["009966", "009999"],
["0099CC", "0099FF"],["00CC00", "00CC33"],["00CC66", "00CC99"],["00CCCC", "00CCFF"],["00FF00", "00FF33"],["00FF66", "00FF99"],
["00FFCC", "00FFFF"],["330000", "330033"],["330066", "330099"],["3300CC", "3300FF"],["333300", "333333"],["333366", "333399"],
["3333CC", "3333FF"],["336600", "336633"],["336666", "336699"],["3366CC", "3366FF"],["339900", "339933"],["339966", "339999"],
["3399CC", "3399FF"],["33CC00", "33CC33"],["33CC66", "33CC99"],["33CCCC", "33CCFF"]];
            arr_length = arr.length;
            first_row = Math.floor(Math.random() * arr_length) - 1;
            second_row = Math.floor(Math.random() * arr_length) - 1;

            document.getElementById("cell1").style.backgroundColor = "#"+arr[first_row][0];
            document.getElementById("cell2").style.backgroundColor = "#" + arr[first_row][1];

            document.getElementById("cell3").style.backgroundColor = "#" + arr[second_row][0];
            document.getElementById("cell4").style.backgroundColor = "#" + arr[second_row][1];


            return true;
        }
    </script>


You can rearrange your color code array to get more colorful background color.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900