Using jQuery to changing background colour of a div

I’m trying to change the background colour of my div when the user presses either C, M or Y. I need to use the keypress method, but for some reason my code doesn’t work.

$(document).ready(function() {
  $(document).keypress(function(event) {
    if (event === 99) {
      $(".light").css('background-color', "#00ffff");
    } else if (event === 121) {
      $(".light").css('background-color', "#00ffff");
    } else if (event === 109) {
      $(".light").css('background-color', "#00ffff");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="light"></div>

Answer

You need to use event.which to determine which key was pressed. Here’s working code:

$(document).ready(function() {
  $(document).keypress(function(event) {
    if (event.which === 99) {
      $(".light").css('background-color', "#00ffff");
    } else if (event.which === 121) {
      $(".light").css('background-color', "#00ffff");
    } else if (event.which === 109) {
      $(".light").css('background-color', "#00ffff");
    }
  });
});
div.light {
  width: 50px;
  height: 50px;
  background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="light"></div>

Leave a Reply

Your email address will not be published. Required fields are marked *