Search code examples
javascripthtmlevent-handlingdom-eventsonclicklistener

How would I make the color of squares change when they are clicked using Javascript?


I have written it out using an event listener but it does not work and the squares remain black even when they are clicked. I found a few typos that I fixed but I am not sure whether I was correct in using getElementsByClassName.

html:

<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
    .square {
        width: 100px;
        height: 100px;
        background-color: #000000;
        margin: 5px;
     }
   </style>
  </head>
 <body>

 <div id="container">
 <div class="square"></div>
 <div class="square"></div>
 <div class="square"></div>
 <div class="square"></div>
 </div>

<script src="js/main.js"></script>
</body>
</html>

and Javascript:

var squares = document.getElementsByClassName('square');

for(var i = 0; i < squares.length; i++) {
squares[0].addEventListener("click", changeColor);
}

function changeColor(event) {
event.style.backgroundColor = randomColor();
}


function randomColor() {

var randomRed = Math.floor(Math.random() * 255);
var randomGreen = Math.floor(Math.random() * 255);
var randomBlue = Math.floor(Math.random() * 255);
//create the string that is the ‘random color’
var randomColor = "rgb("+randomRed+","+randomGreen+","+randomBlue+")";

return randomColor;
}

Solution

  • Two basic problems:

    1. Your for loop has a hardcoded squares[0] when it should be squares[i], so you're binding the handler to the first element multiple times and not to the others.
    2. The event object doesn't have a style property. Use this.style.backgroundColor - within the handler this will refer to the clicked element. Or use event.target.style.backgroundColor.

    So like this:

    for(var i = 0; i < squares.length; i++) {
      squares[i].addEventListener("click", changeColor);
    }
    
    function changeColor(event) {
      this.style.backgroundColor = randomColor();
    }
    

    Demo: http://jsfiddle.net/oueLs5dp/