Build A Lizard
Build A Lizard

Reputation: 23

How do I make shapes change color after clicked on using Javascript?

I'm working on a project and am trying to create a simple reaction game.

To make it more interesting I want the shapes to change color after being clicked on. I researched multiple solution to this problem, but all of them require the page to be refreshed. I also don't understand how to attach it to a specific shape, and not to the background-color of the whole page.

Here is my code...

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf=8">
    <style>
        #shape {
            width: 200px;
            height: 200px;
            background-color: red;
            display: none;
            position: relative;
        }

        body {
            font-family: sans-serif;
        }

        h1 {
            position: relative;
            top: -20px;
        }

        p {
            position: relative;
            top: -30px;
        }

        #yourTime {
            font-weight: bold;
        }
    </style>
</head>

<body>
    <h1 id="h1">Test Your Reactions!</h1>
    <p>Click on the squre or circle as soon as it appears!</p>
    <p id="yourTime"> Your time: <span id="timeTaken"></span></p>
    <div id="shape"></div>
    <script type="text/javascript">
        var start = new Date().getTime();

        function makeShapeAppear()
        {
            var top = Math.random() * 400;
            var left = Math.random() * 700;
            var width = (Math.random() * 200) + 100;
            if (Math.random() > 0.5) {
                document.getElementById("shape").style.borderRadius = "50%";
            } else {
                document.getElementById("shape").style.borderRadius = "0"
            }
            document.getElementById("shape").style.backgroundColor = "red";
            document.getElementById("shape").style.width = width + "px";
            document.getElementById("shape").style.height = width + "px";
            document.getElementById("shape").style.top = top + "px";
            document.getElementById("shape").style.left = left + "px";
            document.getElementById("shape").style.display = "block"
            start = new Date().getTime();
        }

        function appearAfterDelay()
        {
            setTimeout(makeShapeAppear, Math.random() * 1000);
        }

        appearAfterDelay()

        document.getElementById("shape").onclick = function()
        {
            document.getElementById("shape").style.display = "none";
            var end = new Date().getTime();
            var timeTaken = (end - start) / 1000;
            document.getElementById("timeTaken").innerHTML = timeTaken + "s"
            appearAfterDelay();
        }
    </script>
</body>

</html>

As you can see the shape is supposed to change its color to a different color each time it's clicked on. Please help me figure out how to change the color to a random one each time.

Any help and suggestions are welcomed ! (Please excuse me if I'm not phrasing or asking the question correctly, this is my first post on Stack Overflow, so I will get better with time!)

Upvotes: 2

Views: 5667

Answers (2)

Quentin Roy
Quentin Roy

Reputation: 7887

The background-color may be the background of the shape, it is not necessarily the background of the page. This is usually the style attribute you use to make a div change color.

var colors = ["blue", "yellow", "green", "purple", "rgb(250, 175, 72)"];
var shapes = document.querySelectorAll(".shape");
Array.prototype.forEach.call(shapes, function(shape){
  shape.addEventListener("click", function(){
    var colorNum = Math.floor(Math.random() * colors.length);
    shape.style['background-color'] = colors[colorNum];
  });
});
.shape{
  display: inline-block;
  width: 50px;
  height: 50px;
  margin: 10px;
  border-radius: 5px;
  background-color: gray;
  cursor: pointer;
}
<h3>Click on the shapes to change their color</h3>

<div class="shape"></div>
<div class="shape"></div>
<div class="shape"></div>
<div class="shape"></div>
<div class="shape"></div>
<div class="shape"></div>
<div class="shape"></div>

With your code.

// Just add all the possible colours in this array.
var colors = ["blue", "yellow", "green", "purple", "rgb(250, 175, 72)"];
var start = new Date().getTime();

function makeShapeAppear() {
  var top = Math.random() * 400;
  var left = Math.random() * 700;
  var width = (Math.random() * 200) + 100;
  if (Math.random() > 0.5) {
    document.getElementById("shape").style.borderRadius = "50%";
  } else {
    document.getElementById("shape").style.borderRadius = "0"
  }
  document.getElementById("shape").style.backgroundColor = "red";
  document.getElementById("shape").style.width = width + "px";
  document.getElementById("shape").style.height = width + "px";
  document.getElementById("shape").style.top = top + "px";
  document.getElementById("shape").style.left = left + "px";
  document.getElementById("shape").style.display = "block"
  start = new Date().getTime();
}
function appearAfterDelay() {
  setTimeout(makeShapeAppear, Math.random() * 1000);
}

appearAfterDelay()

document.getElementById("shape").onclick = function() {
  var colorNum = Math.floor(Math.random() * colors.length);
  document.getElementById("shape").style.backgroundColor = colors[colorNum];;
  var end = new Date().getTime();
  var timeTaken = (end - start) / 1000;
  document.getElementById("timeTaken").innerHTML = timeTaken + "s"
  appearAfterDelay(); 
}
#shape {
  width: 200px;
  height: 200px;
  background-color: red;
  display: none;
  position: relative;
}
body {
  font-family: sans-serif;
}
h1 {
  position: relative;
  top: -20px;
}
p {
  position: relative;
  top: -30px;
}
#yourTime {
  font-weight: bold;
}
<h1 id="h1">Test Your Reactions!</h1>
<p>Click on the square or circle as soon as it appears!</p>
<p id="yourTime"> Your time: <span id="timeTaken"></span></p>
<div id="shape"></div>

Upvotes: 0

Leonid Shipulya
Leonid Shipulya

Reputation: 127

Random colors can be generated with the following function…

function getRandomColor()
{
  var letters = '0123456789ABCDEF'.split('');

  var color = '#';

  for (var i = 0; i < 6; i++ )
  {
      color += letters[Math.floor(Math.random() * 16)];
  }

  return color;
}

You can paste it in after your script declaration and start variable…

<script type="text/javascript">

var start = new Date().getTime();

function getRandomColor()
{
  var letters = '0123456789ABCDEF'.split('');

  var color = '#';

  for (var i = 0; i < 6; i++ )
  {
      color += letters[Math.floor(Math.random() * 16)];
  }

  return color;
}

You will then have to exchange “red” with getRandomColor()

document.getElementById("shape").style.backgroundColor = getRandomColor();

If you have any other question please ask!

Upvotes: 1

Related Questions